Course page › Code of Lecture 3 › lab.py · 5081 lines
raw file

Boole Lab: interactive proofs in Boolean algebra (lecture 3).

Code with colored syntax: click a line number to get a link to it; an underlined name leads to its definition.

1"""Boole Lab: interactive proofs in Boolean algebra (lecture 3).
2
3The driver of the lab (in the browser and in the terminal), modelled on
4Peano Lab: the proof state, tactics written as in Lean 4, suggestions, a
5solver (its strategies are in solver.py: a proof of every true equation)
6and the export to Lean. All of this lies OUTSIDE the kernel. Tactics build
7a tree of the rules Refl, Symm, Trans, CongrArg and Inst, and qed hands it
8to the kernel (kernel.py) together with the ORIGINAL statement. Three laws:
9
10 1. every qed is checked by the kernel (Kernel.theorem) against the
11 original statement;
12 2. a failing tactic leaves the proof state unchanged;
13 3. the kernel imports nothing from the tactics or the lab.
14
15The semantics of rw is that of Lean (kabstract): the first match of the
16pattern in prefix order (the left side of the goal first, then the right
17one) fixes the instance, and ALL its occurrences are rewritten; at the end
18rw tries rfl. That is why the scripts carry over to Lean unchanged
19(scripts/lean_biblioteka.py checks this with the compiler).
20
21The code is English; the messages are in two languages. The library
22(library.py) gives every theorem an English and a Polish name: a session
23in English uses the English names, a session in Polish ("pl") registers
24the theorems under their Polish names, with Polish descriptions and with
25the scripts translated (theorem names and library.COMMENTS_PL).
26
27In the terminal: python3 lab.py [--pl] [-c command ...]
28"""
29
30import difflib
31import importlib
32import json
33import os
34import re
35import sys
36import time
37import urllib.parse
38from collections import deque
39from dataclasses import dataclass
40from itertools import product
41
42import boolean
43import library
44import solver as sv
45import tactics as tac
46import theories
47from kernel import (CongrArg, Inst, Kernel, ProofError, Refl, Symm, Trans,
48 subst, used_facts)
49from syntax import show, show_equation, show_lean, size
50from syntax import term as core_term
51
52TacticError = tac.TacticError
53
54
55def _import_or_fetch(name):
56 """import name — and in the browser, if an old copy of the page's
57 worker (kept in the browser's cache) did not fetch this newer module
58 of the lab, fetch it from the same server first (the worker lives in
59 applets/js/, the code in kernel/). On a computer the module is simply
60 next to lab.py; the browser's modules js and pyodide exist only there,
61 hence the imports by name."""
62 try:
63 return importlib.import_module(name)
64 except ImportError:
65 if sys.platform != "emscripten":
66 raise
67 where = importlib.import_module("js").location.href
68 url = urllib.parse.urljoin(str(where), f"../../kernel/{name}.py")
69 source = importlib.import_module("pyodide.http").open_url(url).read()
70 here = os.path.dirname(os.path.abspath(__file__))
71 with open(os.path.join(here, name + ".py"), "w", encoding="utf-8") as f:
72 f.write(source)
73 importlib.invalidate_caches()
74 return importlib.import_module(name)
75
76
77tc = _import_or_fetch("tacticals")
78
79_ENGINE = {}
80
81
82def robbins_engine():
83 """The modules of the Robbins theories (ac, robbins, robbins_proof,
84 robbins_lab), imported on first use from the directory of lab.py.
85 The Polish notebooks of the book put the Polish lecture code (jadro/,
86 which has its own ac.py and robbins.py) first on sys.path; their
87 modules of those names are set aside for the import and put back."""
88 if not _ENGINE:
89 here = os.path.dirname(os.path.abspath(__file__))
90 names = ("ac", "robbins", "robbins_proof", "robbins_lab")
91 other = {n: sys.modules.pop(n) for n in names if n in sys.modules
92 and os.path.dirname(os.path.abspath(
93 getattr(sys.modules[n], "__file__", None) or ""))
94 != here}
95 sys.path.insert(0, here)
96 try:
97 for n in names:
98 _ENGINE[n] = _import_or_fetch(n)
99 finally:
100 sys.path.remove(here)
101 sys.modules.update(other)
102 return _ENGINE
103
104
105class _Engine:
106 """A module of robbins_engine(), imported when first used."""
107
108 def __init__(self, name):
109 self.name = name
110
111 def __getattr__(self, attribute):
112 return getattr(robbins_engine()[self.name], attribute)
113
114
115acm = _Engine("ac") # the tactic ac_rfl (A1, A2)
116rb = _Engine("robbins") # rw_ac, ac_simp, auto modulo AC
117rl = _Engine("robbins_lab") # the variants of the proof
118
119VARIABLE = re.compile(r"[A-Za-z][0-9]*") # a letter and a number: x, a1
120NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
121FORBIDDEN = set("""at by do fun have show from then else if let in with match
122end open theorem lemma def example where calc rfl symm trans exact rw nth_rw
123sorry variable class instance namespace section import true false True False
124Type Prop Sort this refine auto n bl qed undo restart abort script hint clear
125help AlgebraBoolea HuntingtonAlgebra Eq first try repeat iterate all_goals
126any_goals skip done fail macro tactic syntax set_option""".split())
127# tactics of core Lean 4 (and common Mathlib ones): a tactic of the user
128# becomes a Lean macro, so its name must not be one of them
129LEAN_TACTICS = set("""simp simp_all simpa dsimp ring ring_nf omega decide
130norm_num linarith nlinarith positivity aesop tauto apply intro intros cases
131rcases obtain induction constructor exists use refine refine' exfalso
132contradiction assumption trivial unfold change subst split by_cases
133injection rename_i specialize generalize revert clear congr ext funext
134nth_rewrite rewrite erw rwa sleep stop checkpoint save trace guard_target
135guard_hyp conv exacts left right focus case next calc have show let sorry
136admit apply_rules solve_by_elim field_simp abel group push_neg contrapose
137by_contra rintro choose lift set existsi all any rfl' symm_saturate
138with_reducible unhygienic""".split())
139TACTIC_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]{1,29}")
140# words reserved since the tacticals (2026-12-03): a theorem saved earlier
141# under such a name is still replayed
142LEGACY_NAMES = set("""first try repeat iterate all_goals any_goals skip done
143fail macro tactic syntax set_option""".split())
144# not names of user tactics: the lab reads these words itself
145LAB_WORDS = {"cls", "design", "forget", "check", "trace"}
146KINDS = ("closes", "shrinks", "same", "grows")
147MAX_STATEMENT = 150 # nodes in the statement of bl prove
148MAX_HINT_SIZE = 220 # a larger goal: no suggestions (the UI stays fast)
149
150# The Lean class of the axioms: lean/Lecture03.lean (English) and
151# lean/Wyklad03.lean (Polish); scripts/lean_biblioteka.py checks that both
152# files hold the same text as LEAN_CLASS.
153LEAN_CLASS_NAME = {"en": "HuntingtonAlgebra", "pl": "AlgebraBoolea"}
154_LEAN_FIELDS = """\
155 n : α → α
156 H1 : ∀ x y : α, x + y = y + x
157 H2 : ∀ x y : α, x * y = y * x
158 H3 : ∀ x y z : α, x + y * z = (x + y) * (x + z)
159 H4 : ∀ x y z : α, x * (y + z) = x * y + x * z
160 H5 : ∀ x : α, x + 0 = x
161 H6 : ∀ x : α, x * 1 = x
162 H7 : ∀ x : α, x + n x = 1
163 H8 : ∀ x : α, x * n x = 0
164"""
165LEAN_CLASS = {
166 lang: f"class {name} (α : Type) extends Add α, Mul α, Zero α, One α "
167 f"where\n{_LEAN_FIELDS}"
168 for lang, name in LEAN_CLASS_NAME.items()}
169
170
171# --- notation: abbreviations -------------------------------------------------
172
173# Expanded by the parser: the kernel, the solver and Lean see +, *, n, 0, 1.
174ABBREVIATIONS = {
175 "med": (("a", "b", "c"), "a * b + a * c + b * c"), # majority
176 "xor": (("a", "b"), "a * n(b) + n(a) * b"), # symm. difference
177 "ite": (("p", "a", "b"), "p * a + n(p) * b"), # if p then a…
178 "nand": (("a", "b"), "n(a * b)"), # Sheffer stroke
179}
180_TEMPLATES = {k: (p, core_term(s)) for k, (p, s) in ABBREVIATIONS.items()}
181_TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_][A-Za-z0-9_]*)|(.))")
182
183
184def term(text, abbrevs=None, funcs=None):
185 """A term in the notation of the lab: like syntax.term, plus calls
186 f(a, b, …) — abbreviations (ABBREVIATIONS by default, expanded at once)
187 and function symbols of a theory (funcs: name -> arity)."""
188 abbrevs = _TEMPLATES if abbrevs is None else abbrevs
189 funcs = funcs or {}
190 toks = [m.group(1) or m.group(2) or m.group(3)
191 for m in _TOKEN.finditer(text) if m.group(0).strip()]
192 pos = 0
193
194 def peek():
195 return toks[pos] if pos < len(toks) else None
196
197 def take(expected=None):
198 nonlocal pos
199 z = peek()
200 if z is None or (expected and z != expected):
201 raise SyntaxError(f"in {text!r}: expected "
202 f"{expected or 'an expression'}, got {z!r}")
203 pos += 1
204 return z
205
206 def sum_term():
207 t = product_term()
208 while peek() == "+":
209 take()
210 t = ("+", t, product_term())
211 return t
212
213 def product_term():
214 t = atom()
215 while peek() == "*":
216 take()
217 t = ("*", t, atom())
218 return t
219
220 def atom():
221 z = take()
222 if z == "(":
223 t = sum_term()
224 take(")")
225 return t
226 if z.isidentifier() and peek() == "(":
227 take("(")
228 args = [sum_term()]
229 while peek() == ",":
230 take()
231 args.append(sum_term())
232 take(")")
233 if z == "n" and len(args) == 1:
234 return ("n", args[0])
235 if z in abbrevs and len(abbrevs[z][0]) == len(args):
236 params, template = abbrevs[z]
237 return subst(template, dict(zip(params, args)))
238 if funcs.get(z) == len(args):
239 return (z,) + tuple(args)
240 raise SyntaxError(f"in {text!r}: unknown function {z}"
241 f" with {len(args)} arguments")
242 if z in ("0", "1") or (z.isidentifier() and z != "n"):
243 return z
244 raise SyntaxError(f"in {text!r}: unexpected character {z!r}")
245
246 t = sum_term()
247 if peek() is not None:
248 raise SyntaxError(f"in {text!r}: unexpected {peek()!r} at "
249 "the end")
250 return t
251
252
253def equation(text, abbrevs=None, funcs=None):
254 """'x + x = x' -> (('+', 'x', 'x'), 'x'); abbreviations as in term."""
255 left, right = text.split("=")
256 return term(left, abbrevs, funcs), term(right, abbrevs, funcs)
257
258
259def has_abbreviations(text):
260 return any(re.search(rf"\b{k}\s*\(", text) for k in ABBREVIATIONS)
261
262
263# --- terms -------------------------------------------------------------------
264
265def term_size(t):
266 """The number of nodes of a term: x has 1, x + n(y) has 4."""
267 return 1 if isinstance(t, str) else 1 + sum(map(term_size, t[1:]))
268
269
270def positions(t, path=()):
271 """Pairs (path, subterm) in prefix order."""
272 yield path, t
273 if not isinstance(t, str):
274 for i, a in enumerate(t[1:], start=1):
275 yield from positions(a, path + (i,))
276
277
278def replace_at(t, path, u):
279 """The term t with the subterm at the path replaced by u."""
280 if not path:
281 return u
282 i = path[0]
283 return t[:i] + (replace_at(t[i], path[1:], u),) + t[i + 1:]
284
285
286def replace_all(t, u, v):
287 """Every occurrence of u in t replaced by v (without going into u)."""
288 if t == u:
289 return v
290 if isinstance(t, str):
291 return t
292 return (t[0],) + tuple(replace_all(a, u, v) for a in t[1:])
293
294
295def occurrences(t, u, path=()):
296 """Paths of the occurrences of u in t, in prefix order."""
297 if t == u:
298 return [path]
299 if isinstance(t, str):
300 return []
301 result = []
302 for i, a in enumerate(t[1:], start=1):
303 result += occurrences(a, u, path + (i,))
304 return result
305
306
307def leaves(t):
308 if isinstance(t, str):
309 return {t}
310 return set().union(*map(leaves, t[1:]))
311
312
313def head(t):
314 return t if isinstance(t, str) else t[0]
315
316
317def path_id(side, path):
318 """The id of a subterm for the interface: '0.1.2' (0 left, 1 right)."""
319 return ".".join(map(str, (side,) + tuple(path)))
320
321
322def tree(t, p="0", prec=0):
323 """A term as a tree of pieces of text with the ids of subterms.
324
325 The flattened text is exactly syntax.show(t)."""
326 if isinstance(t, str):
327 return {"p": p, "c": [t]}
328 f = t[0]
329 if f == "n":
330 c = ["n(", tree(t[1], p + ".1", 0), ")"]
331 elif f == "+":
332 c = [tree(t[1], p + ".1", 0), " + ", tree(t[2], p + ".2", 1)]
333 if prec >= 1:
334 c = ["("] + c + [")"]
335 elif f == "*":
336 c = [tree(t[1], p + ".1", 1), " * ", tree(t[2], p + ".2", 2)]
337 if prec >= 2:
338 c = ["("] + c + [")"]
339 else: # a function symbol of another theory
340 c = [f + "("]
341 for i, a in enumerate(t[1:], start=1):
342 c += ([", "] if i > 1 else []) + [tree(a, f"{p}.{i}", 0)]
343 c.append(")")
344 return {"p": p, "c": c}
345
346
347def tree_text(d):
348 return "".join(x if isinstance(x, str) else tree_text(x) for x in d["c"])
349
350
351def equation_vars(l, r):
352 return tuple(tac.variables(r, tac.variables(l)))
353
354
355def canonical(l, r):
356 """The equation with renamed variables (v0, v1, …): a key for lookups."""
357 ren = {v: f"v{i}" for i, v in enumerate(equation_vars(l, r))}
358 return subst(l, ren), subst(r, ren)
359
360
361def value(t, v):
362 """The value of a term in the two-element Boolean algebra {0, 1}."""
363 if isinstance(t, str):
364 return {"0": 0, "1": 1}.get(t, v.get(t))
365 a = [value(u, v) for u in t[1:]]
366 if t[0] == "+":
367 return a[0] | a[1]
368 if t[0] == "*":
369 return a[0] & a[1]
370 return 1 - a[0]
371
372
373def counterexample(l, r):
374 """A valuation in {0, 1} with l ≠ r (or None)."""
375 vs = equation_vars(l, r)
376 for vals in product((0, 1), repeat=len(vs)):
377 v = dict(zip(vs, vals))
378 if value(l, v) != value(r, v):
379 return v
380 return None
381
382
383# --- rw rules ----------------------------------------------------------------
384
385def split_top(text, sep):
386 """Splits text at the separators `sep` outside parentheses."""
387 parts, depth, current = [], 0, ""
388 for c in text:
389 if c in "([":
390 depth += 1
391 elif c in ")]":
392 depth -= 1
393 if c == sep and depth == 0:
394 parts.append(current)
395 current = ""
396 else:
397 current += c
398 parts.append(current)
399 return parts
400
401
402def arg_text(t):
403 """A rule argument in the course notation: compound ones in parentheses."""
404 s = show(t)
405 return f"({s})" if not isinstance(t, str) and t[0] in "+*" else s
406
407
408@dataclass(frozen=True)
409class Rule:
410 """An rw rule: a fact, a direction (←) and explicit (leading) arguments."""
411 name: str
412 backward: bool = False
413 args: tuple = ()
414
415 def text(self):
416 s = " ".join([self.name] + [arg_text(a) for a in self.args])
417 return ("← " if self.backward else "") + s
418
419 def lean(self, show_arg=None):
420 show_arg = show_arg or (lambda a: show_lean(a, 3))
421 s = " ".join([self.name] + [show_arg(a) for a in self.args])
422 return ("← " if self.backward else "") + s
423
424
425def parse_rule(text, notation=None):
426 """'← H6 (x + x)' -> Rule('H6', True, (('+', 'x', 'x'),)).
427 notation: (abbreviations, function symbols) of another theory."""
428 text = " ".join(text.split())
429 backward = text.startswith(("←", "<-"))
430 if backward:
431 text = text[1 if text.startswith("←") else 2:].strip()
432 parts = [c for c in split_top(text, " ") if c]
433 if not parts or not NAME.fullmatch(parts[0]):
434 raise TacticError(("rule", "rule", text))
435 args = []
436 for c in parts[1:]:
437 try:
438 args.append(term(c, *(notation or ())))
439 except (SyntaxError, ValueError, IndexError):
440 raise TacticError(("argument", "argument", c)) from None
441 return Rule(parts[0], backward, tuple(args))
442
443
444def pattern(kernel, rule):
445 """(free, pattern, replacement): fact variables not given as '?x'."""
446 vs, l, r = kernel.facts[rule.name]
447 if len(rule.args) > len(vs):
448 raise TacticError(("too_many_args", rule.name, len(vs)))
449 if rule.backward:
450 l, r = r, l
451 s = dict(zip(vs, rule.args))
452 s.update({x: "?" + x for x in vs[len(rule.args):]})
453 free = tuple("?" + x for x in vs[len(rule.args):])
454 return free, subst(l, s), subst(r, s)
455
456
457def check_pattern(rule, free, pat):
458 if pat in free:
459 raise TacticError(("metavariable", rule, pat))
460 missing = [v for v in free if v not in leaves(pat)]
461 if missing:
462 raise TacticError(("undetermined", rule, pat, missing))
463
464
465def find_match(kernel, goal, rule, which=None):
466 """The match that rw [rule] (which=None) or nth_rw which picks:
467 (side, path, instance u, replacement v, full arguments).
468
469 As kabstract in Lean: prefix order, the left side of the goal first;
470 nth_rw counts nested matches too."""
471 free, pat, repl = pattern(kernel, rule)
472 check_pattern(rule, free, pat)
473 counter = 0
474 for side, t in enumerate(goal):
475 for path, u in positions(t):
476 s = tac.match_pattern(pat, u, free, {})
477 if s is None:
478 continue
479 counter += 1
480 if which is None or counter == which:
481 args = rule.args + tuple(s[x] for x in free)
482 return side, path, subst(pat, s), subst(repl, s), args
483 if which is not None and counter:
484 raise TacticError(("no_such_match", rule, which, counter))
485 raise TacticError(("no_pattern", rule, pat, goal))
486
487
488def rewrite(kernel, goal, rule, which=None):
489 """One step of rw (which=None) or nth_rw (which=k), Lean's semantics.
490
491 Returns (new goal, compose), where compose(q) turns a proof q of the new
492 goal into a proof of the old one — from the kernel's rules (CongrArg,
493 Inst, Symm, Trans)."""
494 side, path, u, v, args = find_match(kernel, goal, rule, which)
495 L, R = goal
496 z = tac.fresh(L, R, u, v)
497 if which is None: # every occurrence of u
498 CL, CR = tac.abstract(L, u, z), tac.abstract(R, u, z)
499 elif side == 0: # only the chosen occurrence
500 CL, CR = replace_at(L, path, z), R
501 else:
502 CL, CR = L, replace_at(R, path, z)
503 pe = Inst(rule.name, args)
504 if rule.backward:
505 pe = Symm(pe)
506 new = (subst(CL, {z: v}), subst(CR, {z: v}))
507
508 def compose(q): # L = L' (q: L' = R') R' = R
509 return tac.trans(tac.congr(z, CL, pe), q,
510 tac.symm(tac.congr(z, CR, pe)))
511 return new, compose
512
513
514def balance(d, statement):
515 """The same proof as a balanced tree: depth log n instead of n.
516
517 A long script gives a chain Trans(step, Trans(step, …)) as deep as the
518 number of steps — and the kernel checks a proof recursively. We flatten
519 the chain (without recursion; Symm is pushed down to the pieces, since
520 Symm(Trans(a, b)) proves the same as Trans(Symm(b), Symm(a)), and Refl
521 is dropped) and compose it in pairs. The kernel checks the result like
522 any other proof, so this rearrangement needs no trust."""
523 pieces, stack = [], [(d, False)]
524 while stack:
525 x, flipped = stack.pop()
526 if isinstance(x, Trans):
527 if flipped:
528 stack += [(x.p, True), (x.q, True)]
529 else:
530 stack += [(x.q, False), (x.p, False)]
531 elif isinstance(x, Symm):
532 stack.append((x.p, not flipped))
533 elif not isinstance(x, Refl):
534 pieces.append(Symm(x) if flipped else x)
535 if not pieces:
536 return Refl(statement[0])
537 while len(pieces) > 1:
538 pieces = [Trans(pieces[i], pieces[i + 1]) if i + 1 < len(pieces)
539 else pieces[i] for i in range(0, len(pieces), 2)]
540 return pieces[0]
541
542
543class NotInLean(Exception):
544 """A script line that Lean has no tactic for (rw_ac, ac_simp, auto
545 modulo AC): bl lean gives the kernel's proof as a term instead."""
546
547
548def lean_proof_term(d):
549 """The kernel's proof in Lean: Eq.refl, Eq.symm, Eq.trans, congrArg
550 and the facts applied to their arguments."""
551 def arg(t):
552 return theories.lean_term(t, 3)
553 match d:
554 case Refl(t):
555 return f"Eq.refl {arg(t)}"
556 case Symm(p):
557 return f"Eq.symm ({lean_proof_term(p)})"
558 case Trans(p, q):
559 return f"Eq.trans ({lean_proof_term(p)}) ({lean_proof_term(q)})"
560 case CongrArg(z, C, p):
561 return (f"congrArg (fun {z} => {theories.lean_term(C)}) "
562 f"({lean_proof_term(p)})")
563 case Inst(name, args):
564 return " ".join([name] + [arg(a) for a in args])
565 raise ValueError(d)
566
567
568# --- script lines ------------------------------------------------------------
569
570def strip_comment(line):
571 return line.split("--", 1)[0].strip()
572
573
574def parse_line(line, notation=None):
575 """A tactic line -> (tag, data). Tags: rw, rfl, symm, exact, trans,
576 auto. A comment (-- …) and an empty line: ('nothing', None).
577 notation: (abbreviations, function symbols) of another theory."""
578 s = strip_comment(line)
579 if not s:
580 return "nothing", None
581 m = re.fullmatch(r"(rw|nth_rw\s+(\d+))\s*\[(.*)\]", s, re.S)
582 if m:
583 which = int(m.group(2)) if m.group(2) else None
584 if which == 0:
585 raise TacticError(("nth_zero",))
586 rules = [c.strip() for c in split_top(m.group(3), ",")]
587 if not any(rules):
588 raise TacticError(("empty_rw",))
589 if not all(rules):
590 raise TacticError(("empty_rule",))
591 return "rw", (which, [parse_rule(c, notation) for c in rules])
592 word, _, rest = s.partition(" ")
593 rest = rest.strip()
594 if word in ("rfl", "symm") and not rest:
595 return word, None
596 if word == "exact" and rest:
597 rule = parse_rule(rest, notation)
598 if rule.backward:
599 raise TacticError(("exact_backward",))
600 return "exact", rule
601 if word == "trans" and rest:
602 try:
603 return "trans", term(rest, *(notation or ()))
604 except (SyntaxError, ValueError, IndexError):
605 raise TacticError(("argument", "argument", rest)) from None
606 if word == "ac_rfl" and not rest:
607 return "ac_rfl", None
608 m = re.fullmatch(r"(rw_ac|ac_simp)\s*\[(.*)\]", s, re.S)
609 if m:
610 rules = [c.strip() for c in split_top(m.group(2), ",")]
611 if not any(rules):
612 raise TacticError(("empty_rw",))
613 if not all(rules):
614 raise TacticError(("empty_rule",))
615 return m.group(1), [parse_rule(c, notation) for c in rules]
616 if word == "auto":
617 m = re.fullmatch(r"(\d+)?\s*(?:\[(.*)\])?", rest, re.S)
618 if m:
619 budget = int(m.group(1)) if m.group(1) else None
620 lemmas = None
621 if m.group(2) is not None:
622 lemmas = [c.strip() for c in m.group(2).split(",")
623 if c.strip()]
624 return "auto", (budget, lemmas)
625 raise TacticError(("unknown_tactic", s))
626
627
628# --- proof state -------------------------------------------------------------
629
630class ProofState:
631 """The proof state: a list of goals; a tactic acts on the first one.
632
633 Every tactic stores in its node a function compose, which builds a proof
634 of the goal from proofs of the new goals — the tree for the kernel comes
635 into being only at qed."""
636
637 def __init__(self, name, statement, available, exercise=None, taken=False,
638 command="", constants=()):
639 self.name, self.statement = name, statement
640 self.variables = tuple(v for v in equation_vars(*statement)
641 if v not in constants)
642 self.constants = tuple(constants)
643 self.available = list(available)
644 self.available_set = set(available)
645 self.exercise, self.taken = exercise, taken
646 self.command = command
647 self.goals = [(0, statement)]
648 self.nodes = {}
649 self.script = []
650 self.next_id = 1
651 self.history = []
652 self.seen = [] # goals seen before (also inside an rw)
653 self.plans = [] # (steps, terms, method, thm) of recent hints
654 self.undo_target = None # the goal the hints lead back to
655
656 def apply(self, new_goals, compose, lines, intermediate=()):
657 self.history.append((list(self.goals), dict(self.nodes),
658 list(self.script), self.next_id,
659 list(self.seen)))
660 gid = self.goals[0][0]
661 self.seen += [self.goals[0][1]] + list(intermediate)
662 ids = list(range(self.next_id, self.next_id + len(new_goals)))
663 self.next_id += len(new_goals)
664 self.nodes[gid] = (ids, compose)
665 self.goals = list(zip(ids, new_goals)) + self.goals[1:]
666 self.script.extend(lines)
667
668 def undo(self):
669 (self.goals, self.nodes, self.script, self.next_id,
670 self.seen) = self.history.pop()
671
672 def build(self):
673 """A proof of the statement from the nodes (no recursion), balanced."""
674 done, stack = {}, [(0, False)]
675 while stack:
676 gid, expanded = stack.pop()
677 children, compose = self.nodes[gid]
678 if expanded:
679 done[gid] = compose(*[done.pop(c) for c in children])
680 else:
681 stack.append((gid, True))
682 stack += [(c, False) for c in reversed(children)]
683 return balance(done[0], self.statement)
684
685
686class _Focus:
687 """The proof seen with one goal: a basic tactic inside a tactic
688 expression acts on that goal (the rest is the proof's: the facts and
689 variables it may use)."""
690
691 def __init__(self, proof, goal):
692 self.goals = [(0, goal)]
693 self._proof = proof
694
695 def __getattr__(self, name):
696 return getattr(self._proof, name)
697
698
699def goal_size(goal):
700 return term_size(goal[0]) + term_size(goal[1])
701
702
703def term_depth(t):
704 """The nesting of a term, without recursion."""
705 best, stack = 0, [(t, 1)]
706 while stack:
707 u, d = stack.pop()
708 best = max(best, d)
709 if not isinstance(u, str):
710 stack.extend((a, d + 1) for a in u[1:])
711 return best
712
713
714def goal_depth(goal):
715 return max(term_depth(goal[0]), term_depth(goal[1]))
716
717
718# --- solver: breadth-first search from both ends -----------------------------
719
720class BfsSolver:
721 """Like tactics.search, but every step is one rewrite at one place,
722 remembered so that it can be written as an rw rule."""
723
724 def __init__(self, kernel, facts):
725 self.by_head, self.anywhere = {}, []
726 for name in facts:
727 vs, l, r = kernel.facts[name]
728 ren = {x: "?" + x for x in vs}
729 free = tuple(ren.values())
730 for backward, (a, b) in ((False, (l, r)), (True, (r, l))):
731 pat, repl = subst(a, ren), subst(b, ren)
732 extra = tuple(v for v in free if v not in leaves(pat))
733 entry = (name, backward, free, pat, repl, extra)
734 if pat in free:
735 self.anywhere.append(entry)
736 else:
737 self.by_head.setdefault(head(pat), []).append(entry)
738
739 def neighbours(self, t, pool, bound):
740 size_t = term_size(t)
741 for path, u in positions(t):
742 size_u = term_size(u)
743 for entry in self.by_head.get(head(u), []) + self.anywhere:
744 name, backward, free, pat, repl, extra = entry
745 s = tac.match_pattern(pat, u, free, {})
746 if s is None:
747 continue
748 for choice in product(pool, repeat=len(extra)):
749 s2 = dict(s)
750 s2.update(zip(extra, choice))
751 v = subst(repl, s2)
752 if size_t - size_u + term_size(v) > bound:
753 continue
754 args = tuple(s2[x] for x in free)
755 yield replace_at(t, path, v), (path, name, backward, args)
756
757 def search(self, l, r, budget=20000, seconds=None, bound=None,
758 forbidden=(frozenset(), frozenset())):
759 """((steps from the left, steps from the right) or None, visited).
760
761 A step: (term before, (path, fact, backward, arguments)). Terms in
762 `forbidden` (left, right) are skipped on their side — so a hint
763 never sends us back to a side of the goal we already had."""
764 if l == r:
765 return ([], []), 1
766 pool = tac.variables(r, tac.variables(l)) or ["0", "1"]
767 if bound is None:
768 bound = max(term_size(l), term_size(r)) + 5
769 parent = ({l: None}, {r: None})
770 queues = (deque([l]), deque([r]))
771 start = time.perf_counter()
772 while queues[0] or queues[1]:
773 if len(parent[0]) + len(parent[1]) >= budget:
774 break
775 if seconds is not None and time.perf_counter() - start > seconds:
776 break
777 side = 0 if queues[0] and (
778 not queues[1] or len(queues[0]) <= len(queues[1])) else 1
779 t = queues[side].popleft()
780 for new, step in self.neighbours(t, pool, bound):
781 if new in parent[side] or new in forbidden[side]:
782 continue
783 parent[side][new] = (t, step)
784 if new in parent[1 - side]:
785 visited = len(parent[0]) + len(parent[1])
786 return (self._path(parent[0], new),
787 self._path(parent[1], new)), visited
788 queues[side].append(new)
789 return None, len(parent[0]) + len(parent[1])
790
791 @staticmethod
792 def _path(parent, t):
793 steps = []
794 while parent[t] is not None:
795 previous, step = parent[t]
796 steps.append((previous, step))
797 t = previous
798 return steps[::-1]
799
800
801# --- texts -------------------------------------------------------------------
802
803FORMS = {
804 "theorem": (("twierdzenie", "twierdzenia", "twierdzeń"),
805 ("theorem", "theorems")),
806 "step": (("krok", "kroki", "kroków"), ("step", "steps")),
807 "goal": (("cel", "cele", "celów"), ("goal", "goals")),
808 "node": (("węzeł", "węzły", "węzłów"), ("node", "nodes")),
809 "term": (("term", "termy", "termów"), ("term", "terms")),
810 "line": (("wiersz", "wiersze", "wierszy"), ("line", "lines")),
811 "command": (("polecenie", "polecenia", "poleceń"),
812 ("command", "commands")),
813 "match": (("dopasowanie", "dopasowania", "dopasowań"),
814 ("match", "matches")),
815 "argument": (("argument", "argumenty", "argumentów"),
816 ("argument", "arguments")),
817 "earlier": (("wcześniejsze", "wcześniejsze", "wcześniejszych"),
818 ("earlier", "earlier")),
819 "turn": (("obrót", "obroty", "obrotów"), ("turn", "turns")),
820 "alternative": (("alternatywa", "alternatywy", "alternatyw"),
821 ("alternative", "alternatives")),
822}
823
824# what each part of a tactic expression does (bl tactic name, the
825# structure in the workshop)
826KIND_LABELS = {
827 "seq": ("; — po kolei: każda część na tym, co zostawiła poprzednia",
828 "; — in turn: each part on what the previous one left"),
829 "then": ("<;> — druga część na każdym celu, który zrobiła pierwsza",
830 "<;> — the second part on every goal the first one made"),
831 "first": ("first — pierwsza alternatywa, która się uda",
832 "first — the first alternative that succeeds"),
833 "try": ("try — spróbuj; porażka niczego nie zmienia",
834 "try — attempt it; a failure changes nothing"),
835 "repeat": ("repeat — powtarzaj, dopóki się udaje",
836 "repeat — again and again, while it succeeds"),
837 "iterate": ("iterate {n} — dokładnie {n} razy",
838 "iterate {n} — exactly {n} times"),
839 "all_goals": ("all_goals — na każdym celu; porażka na jednym to "
840 "porażka całości",
841 "all_goals — on every goal; failing on one fails all"),
842 "any_goals": ("any_goals — na każdym celu; wystarczy jeden sukces",
843 "any_goals — on every goal; one success is enough"),
844 "skip": ("skip — nic nie robi", "skip — does nothing"),
845 "done": ("done — udaje się tylko, gdy nie ma celów",
846 "done — succeeds only when no goal is left"),
847 "fail": ("fail — zawsze zawodzi", "fail — always fails"),
848 "hole": ("□ — do uzupełnienia", "□ — to fill in"),
849}
850MAX_TRACE_ROWS = 250 # rows of bl trace in the terminal
851
852# bl tactic first, …: the tacticals (tacticals.py) and how to design a
853# tactic; the same structure as the cards of the basic tactics in p_tactic
854TACTICAL_CARDS = {
855 "first": (
856 "first | t₁ | t₂ | … — pierwsza alternatywa, która się uda",
857 "first | t₁ | t₂ | … — the first alternative that succeeds",
858 ["Próbuje t₁; jeśli zawiedzie, stan wraca do poprzedniego i próbuje "
859 "t₂ itd. Zawodzi, gdy zawiodą wszystkie. Kolejność to priorytet: "
860 "najpierw reguły konkretne i tanie.",
861 "Alternatywa, która nigdy nie zawodzi (try, skip, symm), zasłania "
862 "wszystkie następne — analiza to wskazuje. LCF: ORELSE."],
863 ["Tries t₁; if it fails, the state goes back and t₂ is tried, and "
864 "so on. Fails when all fail. The order is the priority: specific, "
865 "cheap rules first.",
866 "An alternative that never fails (try, skip, symm) hides all the "
867 "later ones — the analysis points this out. LCF: ORELSE."],
868 "bl prove x * 1 = x\nfirst | rw [H5] | rw [H6]"),
869 "try": (
870 "try t — spróbuj; porażka nic nie zmienia",
871 "try t — attempt it; a failure changes nothing",
872 ["try t to first | t | skip: nigdy nie zawodzi. Wygodne na końcu "
873 "(try rfl), groźne w repeat: repeat (try t) nie ma kiedy przestać."],
874 ["try t is first | t | skip: it never fails. Handy at the end "
875 "(try rfl), dangerous inside repeat: repeat (try t) never gets a "
876 "reason to stop."],
877 "bl prove x + 0 = x\ntry rw [H6]\nrw [H5]"),
878 "repeat": (
879 "repeat t — powtarzaj, dopóki się udaje",
880 "repeat t — again and again, while it succeeds",
881 ["Kończy się przy pierwszej porażce t (to nie błąd: repeat sam nigdy "
882 "nie zawodzi). Zatrzyma się na pewno, jeśli każdy obrót zmniejsza "
883 "miarę — tu: sumę rozmiarów celów. Reguły skracające (x + 0 → x) "
884 "ją zmniejszają, przemienność (x + y → y + x) nie, a reguła "
885 "wydłużająca ją zwiększa.",
886 "Gdy cele po obrocie są takie same jak wcześniej, laboratorium "
887 "przerywa całą taktykę: ta pętla nie skończyłaby się nigdy (w "
888 "Leanie: aż do limitu czasu). LCF: REPEAT."],
889 ["It ends at the first failure of t (that is no error: repeat itself "
890 "never fails). It surely stops if every turn decreases a measure — "
891 "here: the sum of the sizes of the goals. Shortening rules "
892 "(x + 0 → x) decrease it, commutativity (x + y → y + x) does not, "
893 "and a lengthening rule increases it.",
894 "When the goals after a turn are the same as before, the lab stops "
895 "the whole tactic: this loop would never end (in Lean: until the "
896 "time runs out). LCF: REPEAT."],
897 "bl prove (x + 0) * 1 = x\nrepeat (first | rw [H5] | rw [H6])"),
898 "iterate": (
899 "iterate n t — dokładnie n razy",
900 "iterate n t — exactly n times",
901 ["Zawodzi, jeśli t zawiedzie przy którymkolwiek z n razy."],
902 ["Fails if t fails at any of the n times."],
903 "bl prove x + 0 + 0 = x\niterate 2 rw [H5]"),
904 "<;>": (
905 "t₁ <;> t₂ — t₂ na każdym celu, który zrobiła t₁",
906 "t₁ <;> t₂ — t₂ on every goal that t₁ made",
907 ["Jak w Leanie: t₁ działa na pierwszym celu, potem t₂ na każdym "
908 "celu, który z niego powstał; porażka na jednym to porażka "
909 "całości. Ma sens po taktyce, która robi kilka celów (trans t)."],
910 ["As in Lean: t₁ acts on the first goal, then t₂ on every goal that "
911 "came from it; failing on one fails it all. It makes sense after a "
912 "tactic that makes several goals (trans t)."],
913 "bl prove x + 0 = x * 1\ntrans x <;> first | rw [H5] | rw [H6]"),
914 ";": (
915 "t₁; t₂ — po kolei", "t₁; t₂ — in turn",
916 ["t₂ działa na tym, co zostawiła t₁ (na pierwszym celu). Porażka "
917 "którejkolwiek to porażka całości. LCF: THEN."],
918 ["t₂ acts on what t₁ left (on the first goal). Failing either "
919 "fails it all. LCF: THEN."],
920 "bl prove x + 0 = x\nrw [H5]; done"),
921 "all_goals": (
922 "all_goals t · any_goals t — na wszystkich celach",
923 "all_goals t · any_goals t — on all goals",
924 ["all_goals t: t na każdym celu osobno; zawodzi, jeśli zawiedzie "
925 "na którymkolwiek. any_goals t: wystarczy, że uda się na jednym; "
926 "cele, na których zawiodła, zostają."],
927 ["all_goals t: t on every goal on its own; fails if it fails on any "
928 "of them. any_goals t: one success is enough; the goals where it "
929 "failed stay."],
930 "bl prove x + 0 = x * 1\ntrans x\nall_goals first | rw [H5] | "
931 "rw [H6]"),
932 "skip": (
933 "skip · done · fail — klocki kontrolne",
934 "skip · done · fail — control blocks",
935 ["skip nic nie robi i nigdy nie zawodzi. done udaje się tylko wtedy, "
936 "gdy nie ma celów (sprawdza, że taktyka coś domknęła). fail "
937 "\"komunikat\" zawsze zawodzi."],
938 ["skip does nothing and never fails. done succeeds only when no "
939 "goals are left (it checks that a tactic finished the job). fail "
940 "\"message\" always fails."],
941 "bl prove x + 0 = x\nrw [H5]; done"),
942 "design": (
943 "Jak projektować taktyki", "How to design tactics",
944 ["1. Taktyka to funkcja: cele → nowe cele i przepis, jak z ich "
945 "dowodów złożyć dowód starego celu. qed oddaje całe drzewo jądru, "
946 "więc zła taktyka nie udowodni fałszu — może tylko zawieść albo "
947 "się nie skończyć.",
948 "2. Ma się kończyć: każdy obrót repeat musi zmniejszać miarę "
949 "(sumę rozmiarów celów). Reguły skracające — tak; przemienność — "
950 "pętla; reguły wydłużające — rozrost.",
951 "3. Ma zawodzić wyraźnie: taktyka, która nie może pomóc, zawodzi "
952 "(wtedy first próbuje następnej). try i skip nie zawodzą nigdy — "
953 "w repeat to pętla bez końca.",
954 "4. Kolejność to priorytet: first próbuje od lewej — najpierw "
955 "reguły konkretne i tanie.",
956 "5. Zamknij albo zawiedź: taktyka kończąca (rfl, exact, done) nie "
957 "zostawia celu w połowie.",
958 "6. Buduj z małych części i sprawdzaj: nazwane taktyki wywołują "
959 "inne jak lematy; bl tactic nazwa pokazuje budowę i analizę, "
960 "bl trace — przebieg krok po kroku."],
961 ["1. A tactic is a function: goals → new goals plus a recipe for "
962 "building a proof of the old goal from their proofs. qed hands "
963 "the whole tree to the kernel, so a bad tactic cannot prove a "
964 "falsehood — it can only fail or never finish.",
965 "2. It must stop: every turn of repeat must decrease a measure "
966 "(the sum of the sizes of the goals). Shortening rules — yes; "
967 "commutativity — a loop; lengthening rules — growth.",
968 "3. It must fail clearly: a tactic that cannot help fails (then "
969 "first tries the next one). try and skip never fail — inside "
970 "repeat they make an endless loop.",
971 "4. The order is the priority: first tries from the left — "
972 "specific, cheap rules first.",
973 "5. Close or fail: a finishing tactic (rfl, exact, done) does not "
974 "leave a goal half done.",
975 "6. Build from small parts and check: named tactics call others "
976 "like lemmas; bl tactic name shows the structure and the "
977 "analysis, bl trace the run step by step."],
978 "bl tactic units := repeat (first | rw [H5] | rw [H6])\n"
979 "bl trace units"),
980}
981
982
983def short_text(s, limit=240):
984 return s if len(s) <= limit else s[:limit - 1] + "…"
985
986TACTICS = ("rw", "nth_rw", "rfl", "symm", "trans", "exact", "auto",
987 "ac_rfl", "rw_ac", "ac_simp")
988TACTICALS = ("first", "try", "repeat", "iterate", "all_goals", "any_goals",
989 "skip", "done", "fail")
990COMMANDS = ("help", "axioms", "lib", "prove", "lean", "model", "tactic",
991 "kernel", "forget", "theory", "trace", "replay")
992
993# Example tactics of the workshop (English names of the theorems; a Polish
994# session translates them): (name, Polish name, body, good?, what it
995# teaches in Polish and in English).
996EXAMPLE_TACTICS = [
997 ("units", "jednostki",
998 "repeat (first | rw [H5] | rw [H6] | rw [zero_add] | rw [one_mul])",
999 True,
1000 "usuwa + 0, * 1, 0 + i 1 *; każda reguła skraca cel, więc repeat "
1001 "się zatrzyma",
1002 "removes + 0, * 1, 0 + and 1 *; every rule shortens the goal, so "
1003 "repeat stops"),
1004 ("simp_basic", "upraszczaj",
1005 "repeat (first | rw [H5] | rw [H6] | rw [zero_add] | rw [one_mul] | "
1006 "rw [H7] | rw [H8] | rw [compl_add] | rw [compl_mul] | rw [add_idem] | "
1007 "rw [mul_idem] | rw [add_one] | rw [one_add] | rw [mul_zero] | "
1008 "rw [zero_mul] | rw [absorb] | rw [absorb_mul] | rw [compl_compl] | "
1009 "rw [compl_zero] | rw [compl_one])",
1010 True,
1011 "własny „simp”: same reguły skracające cel — kolejność alternatyw to "
1012 "priorytet",
1013 "a home-made “simp”: only rules that shorten the goal — the order of "
1014 "the alternatives is the priority"),
1015 ("close", "zamknij", "first | rfl | exact H1 | exact H2",
1016 True,
1017 "zamyka cel albo zawodzi — nigdy nie zostawia go w połowie",
1018 "closes the goal or fails — never leaves it half done"),
1019 ("simp_close", "upraszczaj_zamknij", "simp_basic; try close",
1020 True,
1021 "taktyka z taktyk: najpierw upraszczanie, potem próba zamknięcia",
1022 "a tactic made of tactics: simplify first, then try to close"),
1023 ("simp_every", "upraszczaj_wszystkie", "all_goals simp_basic",
1024 True,
1025 "upraszcza każdy cel, nie tylko pierwszy (np. po trans t)",
1026 "simplifies every goal, not only the first one (e.g. after trans t)"),
1027 ("comm_loop", "petla_przem", "repeat rw [H1]",
1028 False,
1029 "zła: H1 tylko zamienia składniki, więc repeat kręciłby się w kółko",
1030 "bad: H1 only swaps the summands, so repeat would go round forever"),
1031 ("try_forever", "wieczne_try", "repeat (try rw [H5])",
1032 False,
1033 "zła: try nigdy nie zawodzi, więc repeat nie ma kiedy przestać",
1034 "bad: try never fails, so repeat never gets a reason to stop"),
1035]
1036
1037
1038def fmt_number(n, lang):
1039 s = f"{n:,}"
1040 if lang == "pl":
1041 return s.replace(",", " ") if n >= 10000 else s.replace(",", "")
1042 return s
1043
1044
1045def word_form(n, word, lang):
1046 pl, en = FORMS[word]
1047 if lang == "en":
1048 return en[0] if n == 1 else en[1]
1049 if n == 1:
1050 return pl[0]
1051 if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14:
1052 return pl[1]
1053 return pl[2]
1054
1055
1056class Output:
1057 """The answer to a command: lines made of pieces
1058 (text, style[, action]); an action is {'insert': …}, {'run': …}
1059 or {'href': …}."""
1060
1061 def __init__(self):
1062 self.rows, self.error, self.extras = [], False, {}
1063
1064 def add(self, *pieces):
1065 row = []
1066 for k in pieces:
1067 row.append([k, ""] if isinstance(k, str) else list(k))
1068 self.rows.append(row)
1069 return self
1070
1071 def text(self):
1072 return "\n".join("".join(k[0] for k in w) for w in self.rows)
1073
1074
1075# --- the library in two languages --------------------------------------------
1076
1077def library_names(lang):
1078 """English theorem name -> its name in a session in `lang` (the Polish
1079 edition keeps the Polish names)."""
1080 return {t["name"]: t["name_pl"] if lang == "pl" else t["name"]
1081 for s in library.SECTIONS for t in s["theorems"]}
1082
1083
1084def localize_script(script, lang, names):
1085 """The lines of a library script for a session in `lang`. In Polish
1086 the theorem names in the tactics (whole words) become the session's
1087 names and each comment goes through library.COMMENTS_PL (a comment
1088 without words stays as it is)."""
1089 lines = [x.strip() for x in script.strip().split("\n")]
1090 if lang != "pl":
1091 return lines
1092 word = re.compile(r"\b(" + "|".join(sorted(
1093 map(re.escape, names), key=len, reverse=True)) + r")\b")
1094 result = []
1095 for line in lines:
1096 code, sep, comment = line.partition("--")
1097 code = word.sub(lambda m: names[m.group(1)], code)
1098 if sep:
1099 comment = library.COMMENTS_PL.get(sep + comment, sep + comment)
1100 result.append(code + comment)
1101 return result
1102
1103
1104# keys of the theorems saved by the first (Polish) version of the page
1105LEGACY_KEYS = {"nazwa": "name", "rownosc": "equation", "skrypt": "script"}
1106
1107
1108# --- session -----------------------------------------------------------------
1109
1110class Session:
1111 """One session of the lab: a kernel with the axioms H1–H8, the library
1112 (replayed by the kernel at the start), the user's theorems and at most
1113 one proof in progress."""
1114
1115 def __init__(self, lang="en", base_url="../kernel/"):
1116 self.lang = lang if lang in ("pl", "en") else "en"
1117 self.base_url = base_url
1118 self.kernel = boolean.theory()
1119 self.axioms = [n for n, _ in boolean.AXIOMS]
1120 self.names = library_names(self.lang) # English -> session's name
1121 self.lib = {} # name -> a library theorem
1122 self.order = [] # library names in order
1123 self.own = {} # name -> the user's theorem
1124 self.proofs = {} # name -> tree accepted by the kernel
1125 self.proof = None # the proof in progress
1126 self.last = None # the last checked script
1127 self.lib_index = {} # canonical equation -> library name
1128 self._bfs_cache = None # solver for the last set of facts
1129 self._expander = None # solver.Expander (proofs of theorems)
1130 self._normal_form = None # solver.NormalForm
1131 self._hint_cache = (None,) # suggestions for the last goal
1132 self._auto_info = None # (steps, visited, time) of last auto
1133 self._intermediate = [] # goals inside the last rw
1134 self.theory = None # another axiom system (bl theory)
1135 self.notation = None # its (abbreviations, function symbols)
1136 self.models = [] # finite models of its axioms
1137 self._saved = None # the Boolean state while in a theory
1138 self.tactics = {} # name -> a tactic expression (below)
1139 self._replaying = False # replaying the user's saved theorems
1140 self._compound = None # (node, trace, runner, end) of the last
1141 self._runner = None # the runner of the last expression
1142 t0 = time.perf_counter()
1143 self.library_errors = self._replay_library()
1144 self.library_time = time.perf_counter() - t0
1145 self._define_examples()
1146
1147 # -- other axiom systems (bl theory; theories.py) --
1148
1149 def parse_equation(self, text):
1150 """An equation in the notation of the session: with the lab's
1151 abbreviations, or with the function symbols of the theory."""
1152 if self.theory is None:
1153 return equation(text)
1154 return equation(text, *self.notation)
1155
1156 def theory_name(self, key):
1157 """The name of a theory as the session shows it."""
1158 if key is None:
1159 return "boole"
1160 return self.tr(theories.THEORIES[key]["name_pl"], key)
1161
1162 def model_cex(self, l, r):
1163 """(model, valuation) for the first model of the theory's axioms
1164 in which l = r fails, or None."""
1165 for model in self.models:
1166 v = theories.counterexample(l, r, model)
1167 if v is not None:
1168 return model, v
1169 return None
1170
1171 def model_text(self, model):
1172 info = theories.MODELS[model]
1173 return f"{model}, {self.tr(info['desc_pl'], info['desc_en'])}"
1174
1175 def theory_falsity_text(self, goal, found, undo=False):
1176 model, v = found
1177 vals = ", ".join(f"{k} = {x}" for k, x in v.items()) or "—"
1178 lv = theories.value(goal[0], model, v)
1179 rv = theories.value(goal[1], model, v)
1180 return self.tr(
1181 f"fałsz w modelu {self.model_text(model)} — dla {vals}: lewa "
1182 f"{lv}, prawa {rv}; w tym modelu zachodzą wszystkie aksjomaty, "
1183 "więc to nie wynika z aksjomatów i nie ma dowodu"
1184 + (" — cofnij krok (undo)" if undo else ""),
1185 f"false in the model {self.model_text(model)} — for {vals}: "
1186 f"left {lv}, right {rv}; all the axioms hold in that model, so "
1187 "it does not follow from the axioms and has no proof"
1188 + (" — undo the step (undo)" if undo else ""))
1189
1190 def notation_text(self):
1191 if self.theory is None:
1192 return "x + y, x * y, n(x), 0, 1"
1193 parts = []
1194 for s, k in theories.THEORIES[self.theory]["signature"].items():
1195 if s in ("+", "*"):
1196 parts.append(f"x {s} y")
1197 elif k == 0:
1198 parts.append(s)
1199 else:
1200 parts.append(f"{s}({', '.join('xyz'[:k])})")
1201 return ", ".join(parts)
1202
1203 def lean_term(self, t, prec=0):
1204 if self.theory is None:
1205 return show_lean(t, prec)
1206 return theories.lean_term(t, prec)
1207
1208 def lean_class_name(self):
1209 if self.theory is None:
1210 return LEAN_CLASS_NAME[self.lang]
1211 return theories.THEORIES[self.theory]["lean_class"]
1212
1213 def lean_class_text(self):
1214 if self.theory is None:
1215 return LEAN_CLASS[self.lang]
1216 given = [(n, i["statement"]) for n, i in self.own.items()
1217 if i.get("given")]
1218 text = theories.lean_class(self.theory,
1219 theories.axioms(self.theory) + given)
1220 if given:
1221 first = text.index(f" {given[0][0]} :")
1222 text = text[:first] + self.tr(
1223 " -- fakty dane: lematy Manna z założeniami, dowiedzione "
1224 "przez silnik\n -- (ich termy mają tysiące węzłów; jądro "
1225 "sprawdza je w bl replay mann)\n",
1226 " -- given facts: Mann's lemmas with hypotheses, proved by "
1227 "the engine\n -- (their terms have thousands of nodes; the "
1228 "kernel checks them in bl replay mann)\n") + text[first:]
1229 return text
1230
1231 def _reset_caches(self):
1232 self.proof, self.last = None, None
1233 self._bfs_cache = self._expander = self._normal_form = None
1234 self._hint_cache = (None,)
1235 self._auto_info = None
1236
1237 def enter_theory(self, key):
1238 info = theories.THEORIES[key]
1239 if self._saved is None:
1240 self._saved = (self.kernel, self.axioms, self.lib, self.order,
1241 self.own, self.proofs, self.lib_index)
1242 k = Kernel(info["signature"])
1243 axioms = theories.axioms(key)
1244 for name, (l, r) in axioms:
1245 k.axiom(name, [v for v in theories.variables_of(
1246 r, theories.variables_of(l)) if v not in info["signature"]],
1247 l, r)
1248 self.kernel, self.axioms = k, [n for n, _ in axioms]
1249 self.lib, self.order, self.own = {}, [], {}
1250 self.proofs, self.lib_index = {}, {}
1251 self.theory, self.notation = key, ({}, dict(info["functions"]))
1252 self.models = [m for m, bad in theories.models(key) if not bad]
1253 self._reset_caches()
1254 for name, l, r, d, note_pl, note_en in (
1255 rl.given(key, k) if "ac" in info else ()):
1256 k.theorem(name, (), l, r, d)
1257 self.proofs[name] = d
1258 self.own[name] = {"statement": (l, r), "script": [],
1259 "variables": (), "steps": 0, "command": "",
1260 "given": True,
1261 "description": self.tr(note_pl, note_en)}
1262 return self.theory_card()
1263
1264 def leave_theory(self):
1265 t = self.tr
1266 if self.theory is None:
1267 return Output().add((t(
1268 " już pracujesz z aksjomatami Huntingtona H1–H8",
1269 " you are already working with Huntington's axioms H1–H8"),
1270 "dim"))
1271 (self.kernel, self.axioms, self.lib, self.order, self.own,
1272 self.proofs, self.lib_index) = self._saved
1273 self._saved, self.theory, self.notation, self.models = \
1274 None, None, None, []
1275 self._reset_caches()
1276 return Output().add(("✓ ", "ok"), (t(
1277 "z powrotem: aksjomaty Huntingtona H1–H8, biblioteka i Twoje "
1278 "twierdzenia", "back to Huntington's axioms H1–H8, the library "
1279 "and your theorems"), "ok"))
1280
1281 def theory_card(self):
1282 """What the current theory is: axioms, models, how to work."""
1283 t = self.tr
1284 info = theories.THEORIES[self.theory]
1285 w = Output()
1286 w.add((t("Teoria ", "Theory "), "heading"),
1287 (self.theory_name(self.theory), "name"), " — ",
1288 (t(info["title_pl"], info["title_en"]), "heading"))
1289 for name in self.axioms:
1290 w.add((" ", ""), (name.ljust(6), "name",
1291 {"insert": f"rw [{name}]"}),
1292 (self.fact_text(name), "goal"))
1293 w.add((t("Modele skończone", "Finite models"), "heading"))
1294 for model, bad in theories.models(self.theory):
1295 if bad:
1296 note = t(f"nie spełnia: {', '.join(bad)}",
1297 f"fails: {', '.join(bad)}")
1298 else:
1299 note = t("spełnia wszystkie aksjomaty — w nim sprawdzam cele",
1300 "satisfies all the axioms — goals are checked in it")
1301 w.add((" ", ""), (self.model_text(model), "code"), " — ",
1302 (note, "dim"))
1303 if "ac" in info and rl.steps_of(self.theory):
1304 self.variants_card(w)
1305 return w
1306 w.add((t("Do udowodnienia (spróbuj)", "To prove (try it)"),
1307 "heading"))
1308 for text in info["challenges"]:
1309 l, r = self.parse_equation(text)
1310 found = self.model_cex(l, r)
1311 mark = "✗ " if found else " "
1312 note = t(f" (fałsz w {found[0]})", f" (false in {found[0]})") \
1313 if found else ""
1314 w.add((" " + mark, "error" if found else ""),
1315 (f"bl prove {show_equation((l, r))}", "code",
1316 {"insert": f"bl prove {show_equation((l, r))}"}),
1317 (note, "dim"))
1318 w.add((t(
1319 " Jądro jest nowe: zna tylko te aksjomaty (biblioteka "
1320 "i ćwiczenia są wyłączone). Podpowiedzi i auto szukają dowodu "
1321 "wszerz — "
1322 "postać normalna działa tylko w algebrze Boole'a. Cel fałszywy "
1323 "w modelu aksjomatów nie ma dowodu. bl lean nazwa — dowód "
1324 "w Leanie; bl theory boole — powrót.",
1325 " The kernel is new: it knows only these axioms (the library and "
1326 "the exercises are off). Hints and auto search breadth-first — "
1327 "the normal form works only in Boolean algebra. A goal that is "
1328 "false in a model of the axioms has no proof. bl lean name — the "
1329 "proof in Lean; bl theory boole — back."), "dim"))
1330 return w
1331
1332 def variants_card(self, w):
1333 """The part of the card of a Robbins theory: the given facts, the
1334 stages of both variants proved here, the other stages."""
1335 t = self.tr
1336 given = [n for n, i in self.own.items() if i.get("given")]
1337 if given:
1338 w.add((t("Fakty dane (lematy z założeniami, dowiedzione przez "
1339 "silnik — jądro je sprawdziło)",
1340 "Given facts (lemmas with hypotheses, proved by the "
1341 "engine — checked by the kernel)"), "heading"))
1342 for name in given:
1343 w.add((" ", ""), (name.ljust(6), "name",
1344 {"insert": f"rw_ac [{name}]"}),
1345 (self.fact_text(name), "goal"))
1346 w.add((" " + self.own[name]["description"], "dim"))
1347 w.add((t("Warianty dowodu twierdzenia Robbinsa",
1348 "Variants of the proof of the Robbins theorem"),
1349 "heading"))
1350 for key, variant in rl.VARIANTS.items():
1351 for i, stage in enumerate(variant["stages"], 1):
1352 if stage["theory"] != self.theory:
1353 continue
1354 first = stage["steps"][0]["name"]
1355 w.add((" ", ""), (t(variant["title_pl"], variant["title_en"])
1356 + t(f", etap {i}: ", f", stage {i}: "),
1357 "name"),
1358 (t(stage["title_pl"], stage["title_en"]), ""),
1359 (f" ({self.counted(len(stage['steps']), 'step')})",
1360 "dim"))
1361 w.add((" ", ""), (f"bl prove {first}", "code",
1362 {"insert": f"bl prove {first}"}),
1363 t(" — pierwszy krok (hint pokazuje skrypt wzorcowy) · ",
1364 " — the first step (hint shows the reference "
1365 "script) · "),
1366 (f"bl replay {key} {i}", "code",
1367 {"run": f"bl replay {key} {i}"}),
1368 t(" — cały etap", " — the whole stage"))
1369 w.add((t("Wszystkie etapy", "All the stages"), "heading"))
1370 for key, variant in rl.VARIANTS.items():
1371 parts = []
1372 for i, stage in enumerate(variant["stages"], 1):
1373 where = stage["theory"] or t("silnik", "engine")
1374 parts.append(f"{i}. {where}")
1375 w.add((" ", ""), (t(variant["title_pl"], variant["title_en"]),
1376 "name"), (": " + " · ".join(parts), "dim"),
1377 (" ", ""), (f"bl replay {key}", "code",
1378 {"run": f"bl replay {key}"}))
1379 w.add((t(
1380 " Taktyki modulo przemienność i łączność (A1, A2): ac_rfl, "
1381 "rw_ac [h] (wzorzec dopasowany do części sumy), ac_simp [h, …] "
1382 "(przepisuje, dopóki się da) i auto [h, …] (szuka przepisań z obu "
1383 "stron celu; bez listy: tylko R). Jądro jest nowe: zna aksjomaty "
1384 "teorii i fakty dane. bl theory boole — powrót.",
1385 " Tactics modulo commutativity and associativity (A1, A2): "
1386 "ac_rfl, rw_ac [h] (the pattern matched to a part of a sum), "
1387 "ac_simp [h, …] (rewrites while it can) and auto [h, …] (looks "
1388 "for rewrites on both sides of the goal; without a list: R "
1389 "only). The kernel is new: it knows the axioms of the theory and "
1390 "the given facts. bl theory boole — back."), "dim"))
1391
1392 def variant_step(self, name=None, statement=None):
1393 """(variant, stage, step) of the current theory with this name (and
1394 the same statement) or with this statement; None otherwise."""
1395 if self.theory is None or "ac" not in theories.THEORIES[self.theory]:
1396 return None
1397 for key, i, step in rl.steps_of(self.theory):
1398 l, r = self.parse_equation(step["statement"])
1399 same = statement is not None and \
1400 canonical(*statement) == canonical(l, r)
1401 if (name == step["name"] and (statement is None or same)) or \
1402 (name is None and same):
1403 return key, i, step
1404 return None
1405
1406 def variant_plan(self, proof, step):
1407 """The goals before each line of the reference script, run from
1408 the statement in a trial proof: ([goal before line 1, ...],
1409 error or None) — an error stops the plan (e.g. a fact not proved
1410 yet)."""
1411 key = (self.theory, step["name"], tuple(proof.available))
1412 cache = getattr(self, "_plans", {})
1413 if key in cache:
1414 return cache[key]
1415 goal = self.parse_equation(step["statement"])
1416 trial = ProofState(step["name"], goal, proof.available,
1417 constants=proof.constants)
1418 goals, error = [], None
1419 for line in step["script"]:
1420 if not trial.goals:
1421 break
1422 goals.append(trial.goals[0][1])
1423 try:
1424 self.run_line(trial, line)
1425 except (TacticError, ProofError) as e:
1426 error = (line, self.error_text(e))
1427 break
1428 self._plans = {**cache, key: (goals, error)}
1429 return goals, error
1430
1431 def variant_suggestion(self, proof, goal):
1432 """The next line of the reference script when the goal lies on it
1433 (the hint and the ghost of TAB); None otherwise."""
1434 found = self.variant_step(proof.name, proof.statement) or \
1435 self.variant_step(None, proof.statement)
1436 if found is None:
1437 return None
1438 key, stage, step = found
1439 goals, _ = self.variant_plan(proof, step)
1440 k = max((i for i, g in enumerate(goals) if g == goal), default=None)
1441 if k is None:
1442 return None
1443 line = step["script"][k]
1444 trial = ProofState(proof.name, goal, proof.available,
1445 constants=proof.constants)
1446 try:
1447 new_goals, _, _ = self.tactic(trial, line)
1448 except (TacticError, ProofError):
1449 return None
1450 new = new_goals[0] if new_goals else None
1451 before = term_size(goal[0]) + term_size(goal[1])
1452 after = term_size(new[0]) + term_size(new[1]) if new else 0
1453 kind = "closes" if new is None else "shrinks" if after < before \
1454 else "same" if after == before else "grows"
1455 entry = self._hint_entry(line, None, kind, new, [], "variant", 0, -1)
1456 entry.update({"solver": len(step["script"]) - k,
1457 "method": "variant",
1458 "theorem": self.tr(step["source_pl"],
1459 step["source_en"]),
1460 "variant": key, "reverts": False})
1461 return entry
1462
1463 def variant_hint(self, w, proof, goal):
1464 """For a step of a variant: its reference script, the lines done
1465 (✓), the next one (▸), and what it still needs."""
1466 t = self.tr
1467 found = self.variant_step(proof.name, proof.statement) or \
1468 self.variant_step(None, proof.statement)
1469 if found is None:
1470 return
1471 key, stage, step = found
1472 goals, error = self.variant_plan(proof, step)
1473 k = max((i for i, g in enumerate(goals) if g == goal), default=None)
1474 w.add((t("Skrypt wzorcowy ", "The reference script "), "heading"),
1475 (f"({t(step['source_pl'], step['source_en'])})", "heading"))
1476 for i, line in enumerate(step["script"]):
1477 mark = "✓ " if k is not None and i < k else \
1478 "▸ " if i == k else " "
1479 w.add((" " + mark, "ok" if mark == "✓ " else ""),
1480 (line, "code", {"insert": line}))
1481 if k is None:
1482 w.add((t(" cel zszedł ze skryptu wzorcowego — cofnij (undo) "
1483 "albo zacznij od nowa (restart)",
1484 " the goal left the reference script — go back (undo) "
1485 "or start again (restart)"), "warning"))
1486 elif error is not None and k == len(goals) - 1:
1487 line, why = error
1488 missing = [n for n in re.findall(r"[A-Za-z_][A-Za-z0-9_]*",
1489 line)
1490 if n not in proof.available and
1491 self.variant_step(n) is not None]
1492 if missing:
1493 w.add((t(" ten krok korzysta z wcześniejszych — "
1494 "najpierw: ", " this step uses earlier ones — "
1495 "first: "), "warning"),
1496 *[piece for n in dict.fromkeys(missing) for piece in
1497 ((f"bl prove {n}", "code",
1498 {"insert": f"bl prove {n}"}), (" ", ""))])
1499 else:
1500 w.add((" " + why, "warning"))
1501
1502 def p_replay(self, rest=""):
1503 """bl replay mann | mccune [stage ...]: the steps of a variant
1504 proved by their reference scripts, theory by theory; without
1505 stages also the assembly of the whole proof in one kernel."""
1506 t = self.tr
1507 words = rest.split()
1508 if not words or words[0] not in rl.VARIANTS:
1509 w = Output().add((t("Warianty dowodu twierdzenia Robbinsa "
1510 "(bl replay wariant [etap])",
1511 "Variants of the proof of the Robbins "
1512 "theorem (bl replay variant [stage])"),
1513 "heading"))
1514 for key, variant in rl.VARIANTS.items():
1515 w.add((" ", ""), (f"bl replay {key}".ljust(18), "code",
1516 {"run": f"bl replay {key}"}),
1517 (t(variant["title_pl"], variant["title_en"]), "name"))
1518 for i, stage in enumerate(variant["stages"], 1):
1519 where = stage["theory"] or t("silnik", "engine")
1520 w.add((" ", ""), (f"{i}. ", "dim"),
1521 (f"{where}: ".ljust(13), "code"),
1522 (t(stage["title_pl"], stage["title_en"]), "dim"))
1523 return w if not words else w.add((t(
1524 f" nie znam wariantu {words[0]!r}",
1525 f" unknown variant {words[0]!r}"), "error"))
1526 key = words[0]
1527 variant = rl.VARIANTS[key]
1528 n = len(variant["stages"])
1529 if any(not x.isdigit() or not 1 <= int(x) <= n for x in words[1:]):
1530 return self.error(t(f"etapy to liczby 1–{n}",
1531 f"the stages are the numbers 1–{n}"))
1532 chosen = [int(x) for x in words[1:]] or list(range(1, n + 1))
1533 w = Output()
1534 if self.proof is not None:
1535 w.add((t(f" (porzucam dowód {self.proof.name})",
1536 f" (abandoning the proof of {self.proof.name})"),
1537 "dim"))
1538 self.proof = None
1539 t0 = time.perf_counter()
1540 for i in chosen:
1541 stage = variant["stages"][i - 1]
1542 w.add((t(f"{t(variant['title_pl'], variant['title_en'])}, "
1543 f"etap {i}: ", f"{variant['title_en']}, stage {i}: "),
1544 "heading"), (t(stage["title_pl"], stage["title_en"]),
1545 "heading"))
1546 if stage["theory"] is None:
1547 w.add((t(
1548 " Lematy 33–40 Manna mają założenia, a jądro nie ma "
1549 "implikacji: silnik dowodzi każdego raz, ze stałymi "
1550 "zamiast zmiennych (robbins_proof.hypothetical_lemmas), "
1551 "i podstawia go tam, gdzie jest potrzebny. W teorii "
1552 "robbins_ab trzy takie podstawienia są faktami danymi: "
1553 "m38, m40a, m40b.",
1554 " Mann's lemmas 33–40 have hypotheses, and the kernel "
1555 "has no implication: the engine proves each once, with "
1556 "constants instead of variables "
1557 "(robbins_proof.hypothetical_lemmas), and substitutes "
1558 "it where it is needed. In the theory robbins_ab three "
1559 "such substitutions are given facts: m38, m40a, m40b."),
1560 "dim"))
1561 continue
1562 if stage["theory"] != self.theory:
1563 self.enter_theory(stage["theory"])
1564 w.add((" → ", "dim"), (f"bl theory {stage['theory']}",
1565 "code"))
1566 for step in stage["steps"]:
1567 if not self.replay_step(w, step):
1568 return w
1569 if not words[1:]:
1570 K, name = rl.assemble(key)
1571 _, l, r = K.facts[name]
1572 w.add((t("Złożenie etapów w jednym jądrze",
1573 "The stages joined in one kernel"), "heading"))
1574 w.add(("✓ ", "ok"), (name, "name"), " : ",
1575 (show_equation((l, r)), "goal"))
1576 w.add((t(" założenia (jak #print axioms): ",
1577 " assumptions (like #print axioms): "), "dim"),
1578 (", ".join(sorted(K.assumptions[name])), "code"),
1579 (t(" — stałe etapów zastąpione termami, każdy dowód "
1580 "sprawdzony od nowa",
1581 " — the constants of the stages replaced by terms, "
1582 "every proof checked again"), "dim"))
1583 w.add((t(" czas: ", " time: ")
1584 + self.fmt_seconds(time.perf_counter() - t0), "dim"))
1585 return w
1586
1587 def replay_step(self, w, step):
1588 """Proves one step by its reference script; a line of the report
1589 (False when the script fails)."""
1590 t = self.tr
1591 name = step["name"]
1592 if name in self.kernel.facts:
1593 w.add((" · ", "dim"), (name, "name"),
1594 (t(" — już udowodnione", " — already proved"), "dim"))
1595 return True
1596 start = self.p_prove(name)
1597 if start.error:
1598 w.rows += start.rows
1599 return False
1600 for line in step["script"]:
1601 try:
1602 self.run_line(self.proof, line)
1603 except (TacticError, ProofError) as e:
1604 w.add((" ✗ ", "error"), (name, "name"), (f" {line}: ",
1605 "code"),
1606 (self.error_text(e), "error"))
1607 self.proof = None
1608 return False
1609 done = self.p_qed()
1610 if done.error:
1611 w.rows += done.rows
1612 return False
1613 d = self.proofs[name]
1614 w.add((" ✓ ", "ok"), (name, "name", {"run": f"bl lean {name}"}),
1615 " : ", (show_equation(self.own[name]["statement"]), "goal"),
1616 (f" {t(step['source_pl'], step['source_en'])}", "dim"))
1617 w.add((" ", ""), (" · ".join(step["script"]), "code"),
1618 (t(f" ({self.counted(size(d), 'node')})",
1619 f" ({self.counted(size(d), 'node')})"), "dim"))
1620 return True
1621
1622 def p_theory(self, rest=""):
1623 t = self.tr
1624 name = rest.strip()
1625 if not name:
1626 return self.theory_list()
1627 if name in ("boole", "boolean", "huntington", "H"):
1628 return self.leave_theory()
1629 aliases = {info["name_pl"]: key
1630 for key, info in theories.THEORIES.items()}
1631 key = name if name in theories.THEORIES else aliases.get(name)
1632 if key is None:
1633 names = ", ".join(["boole"] + [self.theory_name(k)
1634 for k in theories.THEORIES])
1635 return self.error(t(f"nie znam teorii {name!r} — są: {names}",
1636 f"unknown theory {name!r} — there are: "
1637 f"{names}"))
1638 w = Output()
1639 if self.proof is not None:
1640 w.add((t(f" (porzucam dowód {self.proof.name})",
1641 f" (abandoning the proof of {self.proof.name})"),
1642 "dim"))
1643 w.rows += self.enter_theory(key).rows
1644 return w
1645
1646 def theory_list(self):
1647 t = self.tr
1648 w = Output()
1649 w.add((t("Inne aksjomaty (bl theory nazwa)",
1650 "Other axioms (bl theory name)"), "heading"))
1651 rows = [("boole", t("aksjomaty Huntingtona H1–H8 i biblioteka "
1652 "(domyślnie)", "Huntington's axioms H1–H8 and "
1653 "the library (default)"), None)]
1654 for key, info in theories.THEORIES.items():
1655 rows.append((self.theory_name(key),
1656 t(info["title_pl"], info["title_en"]), key))
1657 for name, title, key in rows:
1658 mark = "● " if key == self.theory else " "
1659 w.add((" " + mark, "ok"), (name.ljust(10), "code",
1660 {"run": f"bl theory {name}"}),
1661 (title, "dim"))
1662 return w
1663
1664 # -- small helpers --
1665
1666 def tr(self, pl, en):
1667 return pl if self.lang == "pl" else en
1668
1669 def counted(self, n, word):
1670 return f"{fmt_number(n, self.lang)} {word_form(n, word, self.lang)}"
1671
1672 def in_steps(self, n):
1673 """Polish locative: „w 1 kroku”, „w 5 krokach” (en: in 5 steps)."""
1674 if self.lang == "en":
1675 return self.counted(n, "step")
1676 return f"{fmt_number(n, 'pl')} {'kroku' if n == 1 else 'krokach'}"
1677
1678 def fmt_seconds(self, t):
1679 s = f"{t:.2f}" if t < 10 else f"{t:.1f}"
1680 return (s.replace(".", ",") if self.lang == "pl" else s) + " s"
1681
1682 def error(self, *pieces):
1683 w = Output()
1684 w.error = True
1685 return w.add(("✗ ", "error"), *pieces)
1686
1687 def error_text(self, e):
1688 """The message of a tactic error (a key tuple or a string)."""
1689 a = e.args[0] if e.args else ""
1690 if not isinstance(a, tuple):
1691 return str(a)
1692 k = a[0]
1693 if k in ("rule", "argument"):
1694 return self.tr(f"nie rozumiem: {a[2]!r}",
1695 f"cannot parse: {a[2]!r}")
1696 if k == "too_many_args":
1697 return self.tr(
1698 f"{a[1]} ma tylko {self.counted(a[2], 'argument')}",
1699 f"{a[1]} takes only {self.counted(a[2], 'argument')}")
1700 if k == "metavariable":
1701 rule = a[1]
1702 return self.tr(
1703 f"{rule.text()}: wzorzec to sama zmienna, więc pasowałby do "
1704 "każdego podtermu (Lean: „pattern is a metavariable”); "
1705 "podaj jako argument podterm, który chcesz przepisać, np. "
1706 f"{rule.text()} (x + x)",
1707 f"{rule.text()}: the pattern is a bare variable, so it would "
1708 "match every subterm (Lean: “pattern is a metavariable”); "
1709 "give the subterm you want to rewrite as an argument, e.g. "
1710 f"{rule.text()} (x + x)")
1711 if k == "undetermined":
1712 rule, pat, missing = a[1], a[2], a[3]
1713 names = ", ".join(missing)
1714 return self.tr(
1715 f"{rule.text()}: wzorzec {show(pat)} nie wyznacza {names} — "
1716 f"podaj argumenty, np. {rule.text()} x",
1717 f"{rule.text()}: the pattern {show(pat)} does not "
1718 f"determine {names} — give arguments, e.g. "
1719 f"{rule.text()} x")
1720 if k == "no_pattern":
1721 rule, pat, goal = a[1], a[2], a[3]
1722 return self.tr(
1723 f"{rule.text()}: w celu {show_equation(goal)} nie ma wzorca "
1724 f"{show(pat)}",
1725 f"{rule.text()}: the pattern {show(pat)} does not occur "
1726 f"in the goal {show_equation(goal)}")
1727 if k == "no_such_match":
1728 rule, which, n = a[1], a[2], a[3]
1729 return self.tr(
1730 f"{rule.text()}: wzorzec ma tylko "
1731 f"{self.counted(n, 'match')}, nie ma {which}.",
1732 f"{rule.text()}: the pattern has only "
1733 f"{self.counted(n, 'match')}, there is no match {which}")
1734 if k == "nth_zero":
1735 return self.tr("nth_rw liczy dopasowania od 1",
1736 "nth_rw counts matches from 1")
1737 if k in ("empty_rw", "empty_rule"):
1738 return self.tr("rw [ … ] potrzebuje reguł, np. rw [H1]",
1739 "rw [ … ] needs rules, e.g. rw [H1]")
1740 if k == "exact_backward":
1741 return self.tr("exact nie przyjmuje ← (użyj symm albo rw)",
1742 "exact does not take ← (use symm or rw)")
1743 if k == "unknown_tactic":
1744 return self.tr(
1745 f"nieznane polecenie albo taktyka: {a[1]!r} (bl help)",
1746 f"unknown command or tactic: {a[1]!r} (bl help)")
1747 if k.startswith("tc_"):
1748 return self.tacticals_error(a)
1749 return " ".join(map(str, a))
1750
1751 def tacticals_error(self, a):
1752 """The messages of tacticals.py (keys tc_…)."""
1753 t, k = self.tr, a[0]
1754 if k == "tc_parse":
1755 what, pos, text = a[1], a[2], a[3]
1756 near = text[pos:pos + 12].strip()
1757 where = t(f" (znak {pos + 1}: {near!r})" if near else
1758 " (na końcu)", f" (character {pos + 1}: {near!r})"
1759 if near else " (at the end)")
1760 msg = {
1761 "empty": ("pusta taktyka", "an empty tactic"),
1762 "missing": ("tu brakuje taktyki", "a tactic is missing here"),
1763 "close": ("brakuje nawiasu )", "a ) is missing"),
1764 "stray_close": ("nawias ) bez (", "a ) without a ("),
1765 "first": ("po first piszemy alternatywy: first | t₁ | t₂",
1766 "first takes alternatives: first | t₁ | t₂"),
1767 "bar": ("| należy do first: first | t₁ | t₂",
1768 "| belongs to first: first | t₁ | t₂"),
1769 "stray_bar": ("| należy do first: first | t₁ | t₂",
1770 "| belongs to first: first | t₁ | t₂"),
1771 "count": (f"po iterate piszemy liczbę od 1 do "
1772 f"{tc.MAX_ITERATE}: iterate 3 t",
1773 f"iterate takes a number from 1 to "
1774 f"{tc.MAX_ITERATE}: iterate 3 t"),
1775 "string": ("fail \"komunikat\" — brakuje cudzysłowu",
1776 "fail \"message\" — a quote is missing"),
1777 "escape": ("w komunikacie fail nie może być znaku \\",
1778 "a fail message cannot contain \\"),
1779 "auto": ("auto nie może być częścią taktyki — Lean go nie "
1780 "zna; jego dowód zapisuje się jako zwykłe kroki",
1781 "auto cannot be part of a tactic — Lean does not "
1782 "know it; its proof is written as ordinary steps"),
1783 "ac_tactic": ("rw_ac i ac_simp nie mogą być częścią "
1784 "taktyki — Lean nie ma takich taktyk; użyj ich "
1785 "w osobnym wierszu (ac_rfl wolno)",
1786 "rw_ac and ac_simp cannot be part of a tactic "
1787 "— Lean has no such tactics; use them on a "
1788 "line of their own (ac_rfl is allowed)"),
1789 "depth": (f"za głęboko zagnieżdżone (najwyżej "
1790 f"{tc.MAX_DEPTH} poziomów)",
1791 f"nested too deeply (at most {tc.MAX_DEPTH} "
1792 "levels)"),
1793 "unexpected": ("tego tu się nie spodziewałem",
1794 "this is not expected here"),
1795 }.get(what, (what, what))
1796 return t("taktyka: " + msg[0], "tactic: " + msg[1]) + where
1797 if k == "tc_step":
1798 return self.error_text(a[1])
1799 if k == "tc_no_goals":
1800 return t("nie ma celu, na którym można by działać",
1801 "there is no goal to act on")
1802 if k == "tc_unknown":
1803 return t(f"nie ma taktyki {a[1]} (bl tactic {a[1]} := …)",
1804 f"there is no tactic {a[1]} (bl tactic {a[1]} := …)")
1805 if k == "tc_done":
1806 return t(f"done: zostało jeszcze {self.counted(a[1], 'goal')}",
1807 f"done: {self.counted(a[1], 'goal')} left")
1808 if k == "tc_fail":
1809 return t("fail" + (f": {a[1]}" if a[1] else ""),
1810 "fail" + (f": {a[1]}" if a[1] else ""))
1811 if k == "tc_hole":
1812 return t("□ — najpierw uzupełnij taktykę",
1813 "□ — fill in the tactic first")
1814 if k == "tc_first":
1815 return t(f"first: żadna z {a[1]} alternatyw się nie udała"
1816 if a[1] > 1 else "first: alternatywa się nie udała",
1817 f"first: none of the {a[1]} alternatives succeeded"
1818 if a[1] > 1 else "first: the alternative failed")
1819 if k == "tc_any_goals":
1820 return t("any_goals: nie udało się na żadnym celu",
1821 "any_goals: it failed on every goal")
1822 if k == "tc_loop":
1823 turn, earlier, goal = a[1], a[2], a[3]
1824 goal_text = show_equation(goal) if goal is not None else \
1825 t("brak celów", "no goals")
1826 if turn - earlier == 1 and goal is not None and earlier == \
1827 turn - 1 and turn == 1:
1828 return t(
1829 "repeat się zapętla: pierwszy obrót niczego nie zmienił "
1830 f"({goal_text}), a ciało się udaje — repeat nigdy by nie "
1831 "przestał. Ciało repeat musi zmieniać cel albo zawieść "
1832 "(bl tactic repeat)",
1833 "repeat loops: the first turn changed nothing "
1834 f"({goal_text}) and the body succeeds — repeat would "
1835 "never stop. The body of repeat must change the goal or "
1836 "fail (bl tactic repeat)")
1837 when = t(f"przed pierwszym obrotem" if earlier == 0 else
1838 f"po obrocie {earlier}", "before the first turn"
1839 if earlier == 0 else f"after turn {earlier}")
1840 return t(
1841 f"repeat się zapętla: po obrocie {turn} cele są takie same "
1842 f"jak {when} ({goal_text}) — kręciłby się w kółko bez końca "
1843 "(w Leanie: aż do limitu czasu). Każdy obrót musi zmniejszać "
1844 "cele (bl tactic repeat)",
1845 f"repeat loops: after turn {turn} the goals are the same as "
1846 f"{when} ({goal_text}) — it would go round forever (in "
1847 "Lean: until the time runs out). Every turn must make the "
1848 "goals smaller (bl tactic repeat)")
1849 if k == "tc_steps":
1850 return t(f"przekroczony limit {fmt_number(a[1], 'pl')} kroków — "
1851 "taktyka nie kończy się w rozsądnym czasie",
1852 f"over the limit of {fmt_number(a[1], 'en')} steps — "
1853 "the tactic does not finish in a reasonable time")
1854 if k == "tc_nodes":
1855 return t(f"przekroczony limit {fmt_number(a[1], 'pl')} wykonań "
1856 "części taktyki", f"over the limit of "
1857 f"{fmt_number(a[1], 'en')} runs of parts of the tactic")
1858 if k == "tc_time":
1859 return t(f"taktyka liczyła dłużej niż "
1860 f"{self.fmt_seconds(a[1])} — przerwana",
1861 f"the tactic ran longer than {self.fmt_seconds(a[1])} "
1862 "— stopped")
1863 if k == "tc_size":
1864 return t(f"cel urósł do {fmt_number(a[1], 'pl')} symboli (limit "
1865 f"{fmt_number(a[2], 'pl')}) — taktyka rozdmuchuje cel",
1866 f"the goal grew to {fmt_number(a[1], 'en')} symbols "
1867 f"(limit {fmt_number(a[2], 'en')}) — the tactic blows "
1868 "the goal up")
1869 if k == "tc_deep":
1870 return t(f"cel zagnieździł się głębiej niż {a[1]} poziomów — "
1871 "taktyka rozdmuchuje cel (każdy obrót go wydłuża?)",
1872 f"the goal got nested deeper than {a[1]} levels — the "
1873 "tactic blows the goal up (does every turn lengthen "
1874 "it?)")
1875 if k == "tc_depth":
1876 return t(f"za głęboko zagnieżdżone wywołania (najwyżej {a[1]})",
1877 f"calls nested too deeply (at most {a[1]})")
1878 return " ".join(map(str, a))
1879
1880 # -- facts --
1881
1882 def all_facts(self):
1883 return self.axioms + self.order + list(self.own)
1884
1885 def source(self, name):
1886 if name in self.axioms:
1887 return "axiom"
1888 return "library" if name in self.lib else "own"
1889
1890 def fact_text(self, name):
1891 _, l, r = self.kernel.facts[name]
1892 return f"{show(l)} = {show(r)}"
1893
1894 def check_rule(self, proof, rule):
1895 if rule.name not in self.kernel.facts:
1896 similar = difflib.get_close_matches(rule.name, self.all_facts(),
1897 n=3)
1898 raise TacticError(self.tr(
1899 f"nie znam faktu {rule.name}", f"unknown fact {rule.name}")
1900 + (self.tr(" (może: ", " (maybe: ") + ", ".join(similar)
1901 + ")" if similar else ""))
1902 if rule.name not in proof.available_set:
1903 raise TacticError(self.tr(
1904 f"{rule.name} jest w bibliotece dalej niż ćwiczenie "
1905 f"{proof.exercise} — tu niedostępne",
1906 f"{rule.name} comes later in the library than the exercise "
1907 f"{proof.exercise} — not available here"))
1908 self.check_variables(proof, rule.args)
1909
1910 def constants(self):
1911 """The constants of the theory written as names (A, B, e, ...)."""
1912 return tuple(s for s, k in self.kernel.signature.items()
1913 if k == 0 and s.isidentifier())
1914
1915 def ac_axioms(self):
1916 """The names of commutativity and associativity of + in this
1917 theory (for ac_rfl, rw_ac, ac_simp), or an error."""
1918 if self.theory is not None and \
1919 "ac" in theories.THEORIES[self.theory]:
1920 return theories.THEORIES[self.theory]["ac"]
1921 raise TacticError(self.tr(
1922 "ta taktyka działa w teoriach z przemiennością i łącznością "
1923 "jako aksjomatami (A1, A2): bl theory robbins",
1924 "this tactic works in theories with commutativity and "
1925 "associativity as axioms (A1, A2): bl theory robbins"))
1926
1927 def check_variables(self, proof, terms):
1928 for t in terms:
1929 foreign = sorted(v for v in set(tac.variables(t)) -
1930 set(proof.variables) if self.kernel.is_var(v))
1931 if foreign:
1932 raise TacticError(self.tr(
1933 f"zmienna {', '.join(foreign)} nie występuje w "
1934 "twierdzeniu (Lean: unknown identifier)",
1935 f"variable {', '.join(foreign)} does not occur in the "
1936 "theorem (Lean: unknown identifier)"))
1937
1938 # -- tactics: each returns (new goals, compose, script lines) --
1939
1940 def tactic(self, proof, line, log=None):
1941 tag, data = parse_line(line, self.notation)
1942 if tag == "nothing":
1943 return None
1944 if not proof.goals:
1945 raise TacticError(self.tr("nie ma już celów — wpisz qed",
1946 "no goals left — type qed"))
1947 goal = proof.goals[0][1]
1948 if tag == "rw":
1949 which, rules = data
1950 for rule in rules:
1951 self.check_rule(proof, rule)
1952 steps = []
1953 for rule in rules:
1954 new, compose = rewrite(self.kernel, goal, rule, which)
1955 steps.append((goal, compose))
1956 goal = new
1957 if log is not None:
1958 log.append((rule.text(), goal))
1959 end = goal
1960
1961 def compose_rw(*children):
1962 d = children[0] if children else Refl(end[0])
1963 for previous, comp in reversed(steps):
1964 d = comp(d) or Refl(previous[0])
1965 return d
1966 new_goals = [] if end[0] == end[1] else [end]
1967 rules_text = ", ".join(r.text() for r in rules)
1968 line_text = f"nth_rw {which} [{rules_text}]" if which \
1969 else f"rw [{rules_text}]"
1970 self._intermediate = [c for c, _ in steps[1:]]
1971 return new_goals, compose_rw, [line_text]
1972 if tag == "rfl":
1973 if goal[0] != goal[1]:
1974 raise TacticError(self.tr(
1975 f"rfl: strony są różne: {show_equation(goal)}",
1976 f"rfl: the sides differ: {show_equation(goal)}"))
1977 return [], lambda: Refl(goal[0]), ["rfl"]
1978 if tag == "symm":
1979 return ([(goal[1], goal[0])],
1980 lambda d: tac.symm(d) or Refl(goal[0]), ["symm"])
1981 if tag == "trans":
1982 t = data
1983 self.check_variables(proof, [t])
1984 self.kernel.term(t)
1985 return ([(goal[0], t), (t, goal[1])],
1986 lambda p, q: tac.trans(p, q) or Refl(goal[0]),
1987 [f"trans {show(t)}"])
1988 if tag == "exact":
1989 rule = data
1990 self.check_rule(proof, rule)
1991 vs, l, r = self.kernel.facts[rule.name]
1992 if len(rule.args) > len(vs):
1993 raise TacticError(("too_many_args", rule.name, len(vs)))
1994 s = dict(zip(vs, rule.args))
1995 s.update({x: "?" + x for x in vs[len(rule.args):]})
1996 free = tuple("?" + x for x in vs[len(rule.args):])
1997 found = tac.match_pattern(subst(l, s), goal[0], free, {})
1998 if found is not None:
1999 found = tac.match_pattern(subst(r, s), goal[1], free, found)
2000 if found is None:
2001 raise TacticError(self.tr(
2002 f"exact {rule.text()}: fakt {self.fact_text(rule.name)}"
2003 f" nie pasuje do celu {show_equation(goal)}",
2004 f"exact {rule.text()}: the fact "
2005 f"{self.fact_text(rule.name)} does not match the goal "
2006 f"{show_equation(goal)}"))
2007 args = rule.args + tuple(found[x] for x in free)
2008 full_rule = Rule(rule.name, False, args)
2009 return ([], lambda: Inst(rule.name, args),
2010 [f"exact {full_rule.text()}"])
2011 if tag == "ac_rfl":
2012 comm, assoc = self.ac_axioms()
2013 try:
2014 d = acm.ac_proof(self.kernel, goal[0], goal[1], comm, assoc)
2015 except TacticError:
2016 raise TacticError(self.tr(
2017 "ac_rfl: strony różnią się nie tylko kolejnością "
2018 f"i nawiasami w sumach: {show_equation(goal)}",
2019 "ac_rfl: the sides differ by more than the order and "
2020 f"brackets of sums: {show_equation(goal)}")) from None
2021 return [], lambda: d, ["ac_rfl"]
2022 if tag in ("rw_ac", "ac_simp"):
2023 self.ac_axioms()
2024 for rule in data:
2025 self.check_rule(proof, rule)
2026 texts = [r.text() for r in data]
2027 g = rb.Goal(self.kernel, goal)
2028 if tag == "rw_ac":
2029 g.rw_ac(*texts)
2030 else:
2031 g.ac_simp(*texts)
2032 return self.from_goal(g, f"{tag} [{', '.join(texts)}]")
2033 if tag == "auto" and self.theory is not None and \
2034 "ac" in theories.THEORIES[self.theory]:
2035 return self.ac_auto(proof, goal, data[1])
2036 if tag == "auto":
2037 return self.auto(proof, goal, *data)
2038 raise TacticError(("unknown_tactic", line))
2039
2040 def from_goal(self, g, line):
2041 """A step made by the Robbins tactics (robbins.Goal) in the form
2042 of the lab: the new goals and how to build the old proof."""
2043 l, r = g.goal()
2044 left, right = g.sides
2045 if g.closing is not None or l == r:
2046 d = tac.trans(left.proof, g.closing, tac.symm(right.proof)) \
2047 or Refl(left.start)
2048 return [], lambda: d, [line]
2049
2050 def compose(p):
2051 return tac.trans(left.proof, p, tac.symm(right.proof)) or p
2052 return [(l, r)], compose, [line]
2053
2054 def ac_auto(self, proof, goal, rules):
2055 """auto in a theory with A1, A2: robbins_lab.auto, the search of
2056 robbins.Goal.auto (one, then two rewrites on each side, modulo A1
2057 and A2). A rule without ← may be used in both directions; without
2058 a list: R."""
2059 texts = []
2060 for text in rules or []:
2061 rule = parse_rule(text, self.notation)
2062 self.check_rule(proof, rule)
2063 texts.append(rule.text())
2064 g = rb.Goal(self.kernel, goal)
2065 t0 = time.perf_counter()
2066 try:
2067 depth, _ = rl.auto(g, texts)
2068 except TacticError:
2069 raise TacticError(self.tr(
2070 "auto: nie znalazłem dowodu (do dwóch przepisań z każdej "
2071 "strony, modulo A1, A2) — podaj w liście instancje, np. "
2072 "auto [R (n(x)) y], albo podziel cel",
2073 "auto: no proof found (up to two rewrites on each side, "
2074 "modulo A1, A2) — give instances in the list, e.g. "
2075 "auto [R (n(x)) y], or split the goal")) from None
2076 self._auto_info = (depth, 0, time.perf_counter() - t0, "search")
2077 line = "auto" + (f" [{', '.join(rules)}]" if rules else "")
2078 return self.from_goal(g, line)
2079
2080 def run_line(self, proof, line, log=None):
2081 """Applies a line to the first goal; an error changes nothing."""
2082 self._intermediate = []
2083 node = self.compound(line)
2084 if node is not None:
2085 return self.run_compound(proof, node)
2086 result = self.tactic(proof, line, log)
2087 if result is None:
2088 return None
2089 new_goals, compose, lines = result
2090 proof.apply(new_goals, compose, lines, self._intermediate)
2091 return lines
2092
2093 # -- tactic expressions and the user's tactics (tacticals.py) --
2094
2095 def _define_examples(self):
2096 """The example tactics of the workshop, with the session's names
2097 of the theorems (and of the other examples)."""
2098 rename = dict(self.names)
2099 rename.update({en: self.tr(pl, en)
2100 for en, pl, *_ in EXAMPLE_TACTICS})
2101 word = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
2102 for en, pl, body, good, desc_pl, desc_en in EXAMPLE_TACTICS:
2103 text = word.sub(lambda m: rename.get(m.group(0), m.group(0)),
2104 body)
2105 node = self.parse_tactic(text)
2106 self.tactics[self.tr(pl, en)] = {
2107 "node": node, "text": tc.show(node), "example": True,
2108 "good": good, "description": self.tr(desc_pl, desc_en)}
2109
2110 def drop_example(self, name):
2111 """A theorem saved before the examples existed keeps its name:
2112 the example of that name goes, with the examples that call it."""
2113 if not self.tactics.get(name, {}).get("example"):
2114 return
2115 gone = {name}
2116 changed = True
2117 while changed:
2118 changed = False
2119 for n, info in self.tactics.items():
2120 if info.get("example") and n not in gone and \
2121 set(tc.calls(info["node"])) & gone:
2122 gone.add(n)
2123 changed = True
2124 for n in gone:
2125 del self.tactics[n]
2126
2127 def tactic_nodes(self):
2128 return {n: info["node"] for n, info in self.tactics.items()}
2129
2130 def check_step(self, text):
2131 """A basic tactic inside an expression: it must parse, and auto
2132 is not allowed (Lean has no auto; its proof is written out). A
2133 rule whose pattern leaves variables undetermined is refused: the
2134 lab rejects it, but Lean's rw would make a metavariable and go
2135 on — inside try or first the two would take different ways."""
2136 tag, data = parse_line(text, self.notation)
2137 if tag not in ("rw", "rfl", "symm", "exact", "trans", "ac_rfl"):
2138 raise TacticError(("unknown_tactic", text))
2139 if tag == "rw":
2140 for rule in data[1]:
2141 if rule.name in self.kernel.facts and \
2142 len(rule.args) <= len(self.kernel.facts[rule.name][0]):
2143 free, pat, _ = pattern(self.kernel, rule)
2144 missing = [v for v in free if v not in leaves(pat)]
2145 if missing and pat not in free:
2146 raise TacticError(("undetermined", rule, pat,
2147 missing))
2148
2149 def parse_tactic(self, text):
2150 return tc.parse(tc.blank_comments(text), self.check_step)
2151
2152 def compound(self, line):
2153 """The tactic expression of a line, or None for one basic tactic
2154 (or a comment). A line is an expression when it starts with a
2155 tactical or the name of a user tactic, with ( or □, or when it has
2156 ;, <;> or | outside brackets."""
2157 s = tc.blank_comments(line).strip()
2158 if not s:
2159 return None
2160 m = NAME.match(s)
2161 word = m.group(0) if m else ""
2162 if word in TACTICALS or word in self.tactics or \
2163 s.startswith(("(", tc.HOLE)) or tc.has_separator(s):
2164 return self.parse_tactic(s)
2165 return None
2166
2167 def kernel_steps(self, goal, text):
2168 """What one basic step gives the kernel, for the trace: per rule
2169 the instance of the fact and the rules of the kernel it uses."""
2170 tag, data = parse_line(text, self.notation)
2171 if tag == "rw":
2172 which, rules = data
2173 result = []
2174 for rule in rules:
2175 try:
2176 side, path, u, v, args = find_match(self.kernel, goal,
2177 rule, which)
2178 except TacticError:
2179 break
2180 fact = Rule(rule.name, False, args)
2181 pieces = ["Inst"] + (["Symm"] if rule.backward else []) + \
2182 (["CongrArg"] if path else []) + ["Trans"]
2183 result.append(f"{fact.text()}: {show(u)} = {show(v)} "
2184 f"[{', '.join(pieces)}]")
2185 goal, _ = rewrite(self.kernel, goal, rule, which)
2186 if goal[0] == goal[1]:
2187 result.append(f"rfl: {show(goal[0])} [Refl]")
2188 return result
2189 if tag == "rfl":
2190 return [f"{show(goal[0])} = {show(goal[1])} [Refl]"]
2191 if tag == "symm":
2192 return [f"{show_equation(goal)} ⟵ {show(goal[1])} = "
2193 f"{show(goal[0])} [Symm]"]
2194 if tag == "trans":
2195 return [f"{show(goal[0])} = {show(data)} = {show(goal[1])} "
2196 "[Trans]"]
2197 if tag == "exact":
2198 return [f"{data.text()} …: {show_equation(goal)} [Inst]"]
2199 return []
2200
2201 def runner(self, proof, seconds=tc.SECONDS):
2202 def step(goal, text):
2203 try:
2204 new_goals, compose, _ = self.tactic(_Focus(proof, goal),
2205 text)
2206 except ProofError as e: # e.g. a term outside the theory
2207 raise TacticError(str(e)) from None
2208 except TacticError as e:
2209 key = e.args[0] if e.args else None
2210 if isinstance(key, tuple) and key[:1] == ("undetermined",):
2211 raise tc.LimitError(key) from None
2212 raise
2213 try:
2214 info = self.kernel_steps(goal, text)
2215 except (TacticError, ProofError, RecursionError):
2216 info = []
2217 return new_goals, compose, info
2218 self._runner = tc.Runner(step, self.tactic_nodes(), size=goal_size,
2219 depth=goal_depth, seconds=seconds)
2220 return self._runner
2221
2222 def run_compound(self, proof, node, dry=False):
2223 """A tactic expression on the proof: all of it or nothing. The
2224 script gets one line and undo takes it back at once. dry: only
2225 run it (bl trace) — the proof does not change."""
2226 runner = self.runner(proof)
2227 start = tc.State(tuple(proof.goals), (), proof.next_id)
2228 end, trace = runner.run(node, start)
2229 self._compound = (node, trace, runner, end)
2230 if dry:
2231 return None
2232 proof.history.append((list(proof.goals), dict(proof.nodes),
2233 list(proof.script), proof.next_id,
2234 list(proof.seen)))
2235 if proof.goals:
2236 proof.seen.append(proof.goals[0][1])
2237 for gid, ids, compose, _ in tc.justifications(end):
2238 proof.nodes[gid] = (ids, compose)
2239 proof.goals, proof.next_id = list(end.goals), end.next_id
2240 line = tc.show(node)
2241 proof.script.append(line)
2242 return [line]
2243
2244 def steps_used(self, end):
2245 """The basic steps of the run that made the end state, counted."""
2246 counts = {}
2247 for *_, text in tc.justifications(end):
2248 counts[text] = counts.get(text, 0) + 1
2249 return counts
2250
2251 def compound_summary(self, w, runner, end):
2252 counts = self.steps_used(end)
2253 n = sum(counts.values())
2254 listed = " · ".join(f"{s} ×{k}" if k > 1 else s
2255 for s, k in list(counts.items())[:8])
2256 if len(counts) > 8:
2257 listed += " · …"
2258 w.add((" ⚙ ", "solver"), (self.tr(
2259 f"{self.counted(n, 'step')}", f"{self.counted(n, 'step')}"),
2260 "solver"), (": " if n else "", "dim"), (listed, "code"),
2261 (self.tr(f" (prób: {fmt_number(runner.steps, 'pl')})",
2262 f" (tried: {fmt_number(runner.steps, 'en')})"),
2263 "dim"))
2264
2265 # analysis
2266
2267 def step_info(self, text):
2268 """(effect on the measure, can it fail, rules) of a basic tactic
2269 for tacticals.analyse; rules: (text, effect, pattern, result)."""
2270 tag, data = parse_line(text, self.notation)
2271 if tag == "rw":
2272 rules = []
2273 for rule in data[1]:
2274 self.check_known(rule.name)
2275 free, pat, repl = pattern(self.kernel, rule)
2276 check_pattern(rule, free, pat)
2277 rules.append((rule.text(),
2278 tc.rule_effect(pat, repl, term_size),
2279 pat, repl))
2280 return tc.in_sequence(r[1] for r in rules), True, rules
2281 if tag == "exact":
2282 self.check_known(data.name)
2283 return tc.SHRINKS, True, []
2284 if tag in ("rfl", "ac_rfl"):
2285 return tc.SHRINKS, True, []
2286 if tag == "symm":
2287 return tc.SAME, False, []
2288 if tag == "trans":
2289 return tc.GROWS, False, []
2290 raise TacticError(("unknown_tactic", text))
2291
2292 def check_known(self, name):
2293 if name not in self.kernel.facts:
2294 similar = difflib.get_close_matches(name, self.all_facts(), n=3)
2295 raise TacticError(self.tr(
2296 f"nie znam faktu {name}", f"unknown fact {name}")
2297 + (self.tr(" (może: ", " (maybe: ") + ", ".join(similar)
2298 + ")" if similar else ""))
2299
2300 def analyse_tactic(self, node):
2301 return tc.analyse(node, self.step_info, self.tactic_nodes())
2302
2303 def rules_text(self, rules, limit=6):
2304 """'H5: x + 0 → x (−2) · …' — the rules and the change of size."""
2305 result, seen = [], set()
2306 for text, _, pat, repl in rules:
2307 if text in seen:
2308 continue
2309 seen.add(text)
2310 plain = {v: v[1:] for v in tc.metavariables(pat) |
2311 tc.metavariables(repl)}
2312 delta = term_size(repl) - term_size(pat)
2313 sign = "−" if delta < 0 else "+"
2314 result.append(f"{text}: {show(subst(pat, plain))} → "
2315 f"{show(subst(repl, plain))} ({sign}{abs(delta)})")
2316 if len(result) > limit:
2317 result = result[:limit] + ["…"]
2318 return " · ".join(result)
2319
2320 def finding_text(self, finding):
2321 level, key, _, data = finding
2322 t = self.tr
2323 if key == "step":
2324 return f"{data[0]}: {self.error_text(data[1])}"
2325 if key == "unknown":
2326 return t(f"nie ma taktyki {data[0]} — zdefiniuj ją najpierw "
2327 f"(bl tactic {data[0]} := …)",
2328 f"there is no tactic {data[0]} — define it first "
2329 f"(bl tactic {data[0]} := …)")
2330 if key == "hole":
2331 return t("□ — tu brakuje taktyki", "□ — a tactic is missing here")
2332 if key == "repeat_stops":
2333 rules = self.rules_text(data[0])
2334 return t("repeat się zatrzyma: każdy obrót zmniejsza cele (sumę "
2335 "ich rozmiarów), a liczba naturalna nie maleje bez końca"
2336 + (f" — {rules}" if rules else ""),
2337 "repeat stops: every turn makes the goals smaller (the "
2338 "sum of their sizes), and a natural number cannot go "
2339 "down forever" + (f" — {rules}" if rules else ""))
2340 if key == "repeat_may_loop":
2341 rules = self.rules_text(data[0])
2342 if rules:
2343 return t(f"repeat może się zapętlić: {rules} — ta reguła nie "
2344 "zmienia rozmiaru celu, więc obroty mogą wracać do "
2345 "tych samych celów",
2346 f"repeat may loop: {rules} — this rule keeps the "
2347 "size of the goal, so turns can come back to the "
2348 "same goals")
2349 return t("repeat może się zapętlić: obrót może nie zmienić "
2350 "rozmiaru celów (np. symm)",
2351 "repeat may loop: a turn may keep the size of the goals "
2352 "(e.g. symm)")
2353 if key == "repeat_may_grow":
2354 rules = self.rules_text(data[0])
2355 return t("repeat może się nie skończyć: obrót może powiększyć cele"
2356 + (f" — {rules}" if rules else " (np. trans)"),
2357 "repeat may never end: a turn may make the goals larger"
2358 + (f" — {rules}" if rules else " (e.g. trans)"))
2359 if key == "repeat_never_fails":
2360 return t(f"repeat nigdy się nie zatrzyma: {data[0]} nie zawodzi "
2361 "nawet bez celów (try, skip), a repeat kończy dopiero "
2362 "przy porażce",
2363 f"repeat never stops: {data[0]} does not fail even with "
2364 "no goals (try, skip), and repeat ends only at a "
2365 "failure")
2366 if key == "repeat_fails_only_empty":
2367 return t(f"repeat zatrzyma się tylko wtedy, gdy zamknie wszystkie "
2368 f"cele: {data[0]} nie zawodzi, dopóki jest cel (symm, "
2369 "trans, try…) — na celu, którego nie zamknie, kręci się "
2370 "w kółko",
2371 f"repeat stops only when it closes every goal: "
2372 f"{data[0]} does not fail while a goal is left (symm, "
2373 "trans, try…) — on a goal it cannot close it goes round "
2374 "forever")
2375 if key == "repeat_never_succeeds":
2376 return t(f"repeat nic nie zrobi: {data[0]} zawsze zawodzi",
2377 f"repeat does nothing: {data[0]} always fails")
2378 if key == "first_one":
2379 return t("first z jedną alternatywą to po prostu ta alternatywa",
2380 "first with one alternative is just that alternative")
2381 if key == "first_unreachable":
2382 return t(f"first: {data[0]} nie zawodzi, dopóki jest cel, "
2383 f"więc {', '.join(data[1])} nigdy nie będą próbowane — "
2384 "przenieś je wcześniej albo usuń",
2385 f"first: {data[0]} does not fail while a goal is left, "
2386 f"so {', '.join(data[1])} are never tried — move them "
2387 "earlier or remove them")
2388 if key == "try_useless":
2389 return t(f"try {data[0]}: {data[0]} nigdy nie zawodzi — try nic "
2390 "tu nie zmienia",
2391 f"try {data[0]}: {data[0]} never fails — try changes "
2392 "nothing here")
2393 if key == "greedy":
2394 kind, whole, first = data
2395 return t(f"{kind} bierze całą resztę sekwencji: {whole} — jeśli "
2396 f"miało działać tylko na {first}, dodaj nawiasy: "
2397 f"({kind} {first}); …",
2398 f"{kind} takes the whole rest of the sequence: {whole} "
2399 f"— if it was meant only for {first}, add brackets: "
2400 f"({kind} {first}); …")
2401 if key == "then_one":
2402 return t(f"{data[0]} zostawia najwyżej jeden cel, więc <;> działa "
2403 "tu jak ; — <;> przydaje się po taktyce, która robi "
2404 "kilka celów (trans t)",
2405 f"{data[0]} leaves at most one goal, so <;> works like ; "
2406 "here — <;> is for a tactic that makes several goals "
2407 "(trans t)")
2408 return key
2409
2410 def structure_rows(self, w, node, depth=2, budget=None):
2411 budget = budget if budget is not None else [150]
2412 if budget[0] <= 0:
2413 return
2414 budget[0] -= 1
2415 pad = " " * depth
2416 k = node.kind
2417 if k == "step":
2418 w.add((pad, ""), (node.text, "code"))
2419 elif k == "call":
2420 body = self.tactics.get(node.text)
2421 w.add((pad, ""), (node.text, "name"),
2422 (" := " + body["text"] if body else
2423 self.tr(" (nie ma takiej taktyki)",
2424 " (no such tactic)"), "dim"))
2425 else:
2426 pl, en = KIND_LABELS[k]
2427 label = self.tr(pl, en).replace("{n}", str(node.count))
2428 w.add((pad, ""), (label, "heading" if node.parts else "code"))
2429 for p in node.parts:
2430 self.structure_rows(w, p, depth + 1, budget)
2431 if budget[0] == 0:
2432 budget[0] = -1
2433 w.add((pad + "…", "dim"))
2434
2435 def describe_body(self, w, name, node):
2436 t = self.tr
2437 w.add((t(" budowa:", " structure:"), "heading"))
2438 self.structure_rows(w, node)
2439 findings = self.analyse_tactic(node)
2440 if findings:
2441 w.add((t(" analiza:", " analysis:"), "heading"))
2442 marks = {"ok": ("✓ ", "ok"), "info": ("· ", "dim"),
2443 "warning": ("⚠ ", "warning"), "error": ("✗ ", "error")}
2444 for f in findings:
2445 icon, style = marks[f[0]]
2446 w.add((" ", ""), (icon, style),
2447 (self.finding_text(f), "dim" if f[0] == "info" else style))
2448 w.add((t(" w Leanie 4 (bl lean dołącza ją do pliku):",
2449 " in Lean 4 (bl lean adds it to the file):"), "heading"))
2450 for line in self.lean_macro_text(name, node).split("\n"):
2451 w.add((" " + line, "lean"))
2452
2453 # definitions
2454
2455 def tactic_name_problem(self, name):
2456 t = self.tr
2457 if not TACTIC_NAME.fullmatch(name) or VARIABLE.fullmatch(name):
2458 return t("nazwa taktyki: od 2 do 30 liter, cyfr i _, na początku "
2459 "litera — i nie litera z numerem (tak wyglądają "
2460 "zmienne)",
2461 "a tactic name: 2 to 30 letters, digits and _, starting "
2462 "with a letter — and not a letter with a number (that "
2463 "is how variables look)")
2464 if name in FORBIDDEN or name in tc.KEYWORDS or name in LEAN_TACTICS \
2465 or name in COMMANDS or name in TACTICS or name in LAB_WORDS:
2466 return t(f"{name} to słowo Leana albo laboratorium — wybierz inną "
2467 "nazwę",
2468 f"{name} is a word of Lean or of the lab — choose "
2469 "another name")
2470 if name in self.kernel.facts or name in self.names.values() or \
2471 name in self.all_own() or (self._saved is not None and
2472 name in self._saved[0].facts):
2473 return t(f"{name} to nazwa twierdzenia — taktyka musi się nazywać "
2474 "inaczej (w Leanie byłyby tym samym słowem)",
2475 f"{name} is the name of a theorem — a tactic needs "
2476 "another one (in Lean they would be the same word)")
2477 if self.tactics.get(name, {}).get("example"):
2478 return t(f"{name} to przykład z warsztatu — nadaj swojej taktyce "
2479 "inną nazwę",
2480 f"{name} is an example of the workshop — give your "
2481 "tactic another name")
2482 return None
2483
2484 def tactics_called(self, nodes):
2485 """The user tactics that the expressions call, also through other
2486 tactics; each comes after the tactics it calls (as Lean needs)."""
2487 order, state = [], {}
2488
2489 def visit(name):
2490 if name in state or name not in self.tactics:
2491 return
2492 state[name] = "open"
2493 for c in tc.calls(self.tactics[name]["node"]):
2494 visit(c)
2495 order.append(name)
2496 for node in nodes:
2497 for c in tc.calls(node):
2498 visit(c)
2499 return order
2500
2501 def script_nodes(self, lines):
2502 nodes = []
2503 for line in lines:
2504 try:
2505 node = self.compound(line)
2506 except TacticError:
2507 node = None
2508 if node is not None:
2509 nodes.append(node)
2510 return nodes
2511
2512 def all_own(self):
2513 """The user's theorems: of this session and, in a theory, also
2514 the Boolean ones kept aside (they come back after the theory)."""
2515 result = dict(self._saved[4]) if self._saved else {}
2516 result.update(self.own)
2517 return result
2518
2519 def theorems_using(self, name):
2520 """What would break if the tactic changed or went away: the
2521 user's theorems that call it (also through other tactics) and the
2522 proof in progress."""
2523 users = [thm for thm, info in self.all_own().items()
2524 if name in self.tactics_called(
2525 self.script_nodes(info["script"]))]
2526 if self.proof is not None and name in self.tactics_called(
2527 self.script_nodes(self.proof.script)):
2528 users.append(self.tr("dowód w toku", "the proof in progress"))
2529 return users
2530
2531 def define_tactic(self, name, body, doc=""):
2532 t = self.tr
2533 problem = self.tactic_name_problem(name)
2534 if problem:
2535 return self.error(problem)
2536 try:
2537 node = self.parse_tactic(body)
2538 except TacticError as e:
2539 return self.error(self.error_text(e))
2540 if any(n.kind == "hole" for n in tc.walk(node)):
2541 return self.error(t("w taktyce zostało □ — uzupełnij je",
2542 "the tactic still has □ — fill it in"))
2543 unknown = [c for c in tc.calls(node) if c not in self.tactics]
2544 if unknown:
2545 return self.error(t(
2546 f"nie ma taktyki {unknown[0]} — taktyka może wywoływać tylko "
2547 "taktyki zdefiniowane wcześniej",
2548 f"there is no tactic {unknown[0]} — a tactic may call only "
2549 "tactics defined before it"))
2550 if name in tc.calls(node) or name in self.tactics_called([node]):
2551 return self.error(t(
2552 f"{name} wywoływałaby samą siebie — w Leanie makro nie może "
2553 "się rozwijać bez końca",
2554 f"{name} would call itself — in Lean a macro cannot expand "
2555 "forever"))
2556 users = self.theorems_using(name) if name in self.tactics else []
2557 if users:
2558 return self.error(t(
2559 f"z taktyki {name} korzystają twierdzenia: {', '.join(users)}"
2560 " — nowa wersja mogłaby je zepsuć; wybierz inną nazwę",
2561 f"the theorems {', '.join(users)} use the tactic {name} — a "
2562 "new version could break them; choose another name"))
2563 text = tc.show(node)
2564 doc = " ".join(str(doc or "").split())[:400]
2565 self.tactics.pop(name, None)
2566 self.tactics[name] = {"node": node, "text": text, "example": False,
2567 "doc": doc}
2568 w = Output()
2569 w.add(("✓ ", "ok"), (t("taktyka ", "tactic "), "ok"), (name, "name"),
2570 " := ", (text, "code"))
2571 w.add((t(f" od teraz możesz jej używać: {name}",
2572 f" from now on you can use it: {name}"), "dim"),
2573 (t(" · próba: ", " · dry run: "), "dim"),
2574 (f"bl trace {name}", "code", {"insert": f"bl trace {name}"}))
2575 self.describe_body(w, name, node)
2576 w.extras["tactic_new"] = {"name": name, "text": text, "doc": doc}
2577 return w
2578
2579 def forget_tactic(self, name):
2580 t = self.tr
2581 info = self.tactics.get(name)
2582 if info is None or info.get("example"):
2583 return self.error(t(f"{name} nie jest Twoją taktyką",
2584 f"{name} is not one of your tactics"))
2585 users = self.theorems_using(name) + [
2586 n for n, i in self.tactics.items() if n != name and
2587 name in tc.calls(i["node"])]
2588 if users:
2589 return self.error(t(
2590 f"z taktyki {name} korzystają: {', '.join(users)} — usuń je "
2591 "najpierw",
2592 f"{name} is used by: {', '.join(users)} — delete them first"))
2593 del self.tactics[name]
2594 w = Output().add(("✓ ", "ok"), (t(f"usunięta taktyka {name}",
2595 f"deleted the tactic {name}"),
2596 "ok"))
2597 w.extras["tactic_forget"] = name
2598 return w
2599
2600 def describe_tactic(self, name):
2601 t = self.tr
2602 info = self.tactics[name]
2603 w = Output()
2604 w.add((t("Taktyka ", "Tactic "), "heading"), (name, "name"), " := ",
2605 (info["text"], "code", {"insert": info["text"]}))
2606 if info.get("example"):
2607 mark = ("✓ ", "ok") if info["good"] else ("✗ ", "error")
2608 w.add((" ", ""), mark, (t("przykład: ", "example: ")
2609 + info["description"], "dim"))
2610 self.describe_body(w, name, info["node"])
2611 return w
2612
2613 def lean_macro_text(self, name, node):
2614 doc = self.tactics.get(name, {}).get("doc") or \
2615 self.tactics.get(name, {}).get("description") or ""
2616 text = tc.lean_macro(name, node, self._lean_basic)
2617 if doc: # a doc comment belongs to the macro
2618 doc = doc.replace("-/", "- /")
2619 first, _, rest = text.partition("\n")
2620 text = f"{first}\n/-- {doc} -/\n{rest}"
2621 return text
2622
2623 def load_tactics(self, entries):
2624 """The user's tactics saved by the page: [{name, text, doc}].
2625 A tactic may call one saved after it (a callee redefined later
2626 moves to the end), so the list is gone through until nothing
2627 changes."""
2628 waiting = []
2629 for entry in entries if isinstance(entries, list) else []:
2630 try:
2631 waiting.append((str(entry["name"]), str(entry["text"]),
2632 str(entry.get("doc") or "")))
2633 except (AttributeError, KeyError, TypeError):
2634 continue
2635 accepted = []
2636 while waiting:
2637 rest = []
2638 for name, text, doc in waiting:
2639 if self.define_tactic(name, text, doc).error:
2640 rest.append((name, text, doc))
2641 else:
2642 accepted.append(name)
2643 if len(rest) == len(waiting):
2644 break
2645 waiting = rest
2646 return accepted, [name for name, _, _ in waiting]
2647
2648 # bl trace
2649
2650 def p_trace(self, rest):
2651 t = self.tr
2652 text = rest.strip()
2653 if not text:
2654 return self.error(t(
2655 "użycie: bl trace taktyka, np. bl trace repeat (first | "
2656 "rw [H5] | rw [H6])",
2657 "usage: bl trace tactic, e.g. bl trace repeat (first | "
2658 "rw [H5] | rw [H6])"))
2659 d = self.proof
2660 if d is None:
2661 return self.error(t(
2662 "nie ma dowodu w toku — bl trace próbuje taktyki na bieżącym "
2663 "celu (zacznij od bl prove …)",
2664 "no proof in progress — bl trace tries a tactic on the "
2665 "current goal (start with bl prove …)"))
2666 try:
2667 node = self.parse_tactic(text)
2668 except TacticError as e:
2669 return self.error(self.error_text(e))
2670 error, end = None, None
2671 try:
2672 self.run_compound(d, node, dry=True)
2673 _, trace, runner, end = self._compound
2674 except TacticError as e:
2675 error, trace, runner = e, getattr(e, "trace", None), self._runner
2676 w = Output()
2677 w.add((t("Przebieg ", "Trace of "), "heading"),
2678 (tc.show(node), "code"),
2679 (t(" próba: stan dowodu się nie zmienia",
2680 " a dry run: the proof state does not change"), "dim"))
2681 if trace is not None:
2682 self.trace_rows(w, trace, 1, [0])
2683 if runner is not None and runner.truncated:
2684 w.add((t(" … dalszą część przebiegu pominięto",
2685 " … the rest of the trace is left out"), "dim"))
2686 if error is None:
2687 w.add((t(" wynik:", " result:"), "heading"))
2688 self.goal_rows(w, [g for _, g in end.goals])
2689 self.compound_summary(w, runner, end)
2690 w.add((t(" zastosuj: ", " apply it: "), "dim"),
2691 (tc.show(node), "code", {"insert": tc.show(node)}))
2692 else:
2693 w.add((" ✗ ", "error"), (self.error_text(error), "error"))
2694 return w
2695
2696 def goal_rows(self, w, goals):
2697 if not goals:
2698 w.add((" ✓ ", "ok"), (self.tr("brak celów", "no goals"), "ok"))
2699 for i, goal in enumerate(goals[:12]):
2700 w.add((" ⊢ ", "code" if i == 0 else "dim"),
2701 (show_equation(goal), "goal" if i == 0 else "dim"))
2702 if len(goals) > 12:
2703 w.add((f" … {self.counted(len(goals) - 12, 'goal')}", "dim"))
2704
2705 def short_error(self, e):
2706 a = e.args[0] if e.args else ""
2707 if isinstance(a, tuple) and a and a[0] == "no_pattern":
2708 return self.tr(f"nie ma wzorca {show(a[2])}",
2709 f"no pattern {show(a[2])}")
2710 return self.error_text(e)
2711
2712 def trace_label(self, tr):
2713 node = tr.node
2714 k = node.kind
2715 turn = f"[{tr.turn}] " if tr.turn else ""
2716 if k in ("step", "call"):
2717 return turn + node.text
2718 if k == "repeat":
2719 n = tr.turns or 0
2720 return turn + "repeat — " + self.counted(n, "turn")
2721 if k == "iterate":
2722 return turn + f"iterate {node.count}"
2723 if k == "fail":
2724 return turn + tc.show(node)
2725 return turn + {"seq": ";", "then": "<;>"}.get(k, k)
2726
2727 def trace_rows(self, w, tr, depth, counter):
2728 if counter[0] >= MAX_TRACE_ROWS:
2729 if counter[0] == MAX_TRACE_ROWS:
2730 w.add((" " * depth + "…", "dim"))
2731 counter[0] += 1
2732 return
2733 counter[0] += 1
2734 icon = ("✓ ", "ok") if tr.ok else ("✗ ", "error")
2735 pieces = [(" " * depth, ""), icon,
2736 (self.trace_label(tr), "code" if tr.node.kind == "step"
2737 else "name" if tr.node.kind == "call" else "dim")]
2738 if tr.node.kind == "step":
2739 if tr.ok:
2740 n, goal = tr.after
2741 pieces += [(" ⟶ ", "dim"),
2742 (show_equation(goal) if goal is not None and
2743 n >= tr.before[0] else self.tr("✓ cel zamknięty",
2744 "✓ goal closed"),
2745 "goal")]
2746 elif tr.error is not None:
2747 pieces += [(" " + self.short_error(tr.error), "dim")]
2748 elif not tr.ok and tr.error is not None and not tr.parts:
2749 pieces += [(" " + self.short_error(tr.error), "dim")]
2750 w.add(*pieces)
2751 for p in tr.parts:
2752 self.trace_rows(w, p, depth + 1, counter)
2753
2754 # the workshop of the page (JSON)
2755
2756 def trace_json(self, tr, budget=None, paths=None):
2757 """The trace for the page. paths: id(node) -> its path in the
2758 expression being run ("0", "0.1", …); a part of a called tactic
2759 has none (and no span: its span is in the callee's text)."""
2760 budget = budget if budget is not None else [tc.MAX_TRACE]
2761 if tr is None or budget[0] <= 0:
2762 return None
2763 budget[0] -= 1
2764 paths = paths or {}
2765 def goal_text(snap):
2766 n, goal = snap
2767 return {"n": n, "goal": short_text(show_equation(goal))
2768 if goal is not None else ""}
2769 path = paths.get(id(tr.node))
2770 entry = {"kind": tr.node.kind, "label": self.trace_label(tr),
2771 "path": path, "turn": tr.turn, "turns": tr.turns,
2772 "span": list(tr.node.span) if path is not None else None,
2773 "ok": bool(tr.ok), "before": goal_text(tr.before)}
2774 if tr.after is not None:
2775 entry["after"] = goal_text(tr.after)
2776 if tr.error is not None:
2777 entry["error"] = self.short_error(tr.error)
2778 if tr.info:
2779 entry["kernel"] = tr.info
2780 parts = [self.trace_json(p, budget, paths) for p in tr.parts]
2781 entry["parts"] = [p for p in parts if p is not None]
2782 return entry
2783
2784 def error_span(self, e):
2785 a = e.args[0] if e.args else ""
2786 if isinstance(a, tuple) and a and a[0] == "tc_parse":
2787 return [a[2], a[2] + 1]
2788 if isinstance(a, tuple) and a and a[0] == "tc_step":
2789 return [a[2], a[3]]
2790 return None
2791
2792 def json_tactic(self, text, name=""):
2793 """The tactic being built in the workshop: its structure, the
2794 analysis and Lean (it does not run)."""
2795 try:
2796 node = self.parse_tactic(text)
2797 except TacticError as e:
2798 return json.dumps({"ok": False, "error": self.error_text(e),
2799 "span": self.error_span(e)},
2800 ensure_ascii=False)
2801 findings = [{"level": f[0], "text": self.finding_text(f),
2802 "span": list(f[2])} for f in self.analyse_tactic(node)]
2803 name = name.strip()
2804 problem = self.tactic_name_problem(name) if name else ""
2805 own = name in self.tactics and not self.tactics[name].get("example")
2806 lean = [self.lean_macro_text(c, self.tactics[c]["node"])
2807 for c in self.tactics_called([node]) if c != name]
2808 lean.append(self.lean_macro_text(name, node) if name and
2809 (not problem or own) else
2810 tc.show(node, self._lean_basic))
2811 return json.dumps({
2812 "ok": True, "text": tc.show(node), "tree": tc.tree_json(node),
2813 "findings": findings, "lean": "\n\n".join(lean),
2814 "holes": sum(1 for n in tc.walk(node) if n.kind == "hole"),
2815 "name_problem": "" if own else (problem or "")},
2816 ensure_ascii=False)
2817
2818 def json_define(self, name, text, doc=""):
2819 """The Tactic Lab saves a tactic with its description (it becomes
2820 the Lean doc comment of the macro)."""
2821 result = self.define_tactic(str(name).strip(), str(text), doc)
2822 reply = {"lines": result.rows, "error": result.error}
2823 reply.update(result.extras)
2824 if not result.error:
2825 reply["library"] = self.library_json()
2826 return json.dumps(reply, ensure_ascii=False)
2827
2828 def json_trace(self, text):
2829 """A dry run of the tactic being built on the current goal."""
2830 t = self.tr
2831 d = self.proof
2832 if d is None or not d.goals:
2833 return json.dumps({"ok": False, "trace": None, "error": t(
2834 "nie ma celu, na którym można spróbować — zacznij dowód "
2835 "(bl prove …)", "there is no goal to try it on — start a "
2836 "proof (bl prove …)") if d is None else t(
2837 "nie ma już celów — wpisz qed", "no goals left — type qed")},
2838 ensure_ascii=False)
2839 try:
2840 node = self.parse_tactic(text)
2841 except TacticError as e:
2842 return json.dumps({"ok": False, "trace": None,
2843 "error": self.error_text(e),
2844 "span": self.error_span(e)},
2845 ensure_ascii=False)
2846 error, end = "", None
2847 try:
2848 self.run_compound(d, node, dry=True)
2849 _, trace, runner, end = self._compound
2850 except TacticError as e:
2851 error = self.error_text(e)
2852 trace, runner = getattr(e, "trace", None), self._runner
2853 reply = {"ok": not error, "error": error,
2854 "trace": self.trace_json(trace, paths=tc.paths(node)),
2855 "truncated": bool(runner and runner.truncated),
2856 "tried": runner.steps if runner else 0,
2857 "before": [short_text(show_equation(g))
2858 for _, g in d.goals[:6]]}
2859 if end is not None:
2860 counts = self.steps_used(end)
2861 reply["goals"] = [short_text(show_equation(g))
2862 for _, g in end.goals[:6]]
2863 reply["n_goals"] = len(end.goals)
2864 reply["steps"] = [[s, k] for s, k in counts.items()]
2865 return json.dumps(reply, ensure_ascii=False)
2866
2867 # -- auto and the solver --
2868
2869 def bfs_solver(self, facts):
2870 key = tuple(facts)
2871 if self._bfs_cache is None or self._bfs_cache[0] != key:
2872 self._bfs_cache = (key, BfsSolver(self.kernel, facts))
2873 return self._bfs_cache[1]
2874
2875 def steps_to_rules(self, goal, lefts, rights, limit=None):
2876 """Solver steps (each at one place) as rw / nth_rw lines which do
2877 exactly these rewrites in Lean's semantics.
2878
2879 We cut the full chain l = c₀ → … → cₙ = r at the smallest term c_k:
2880 the left side goes c₀ → … → c_k, the right one cₙ → … → c_k
2881 (reversed steps). Both sides then get smaller. With `limit` only
2882 that many first lines are returned (a hint needs one)."""
2883 facts = self.kernel.facts
2884 full = [] # (before, after, path, name, backward, args)
2885 t = goal[0]
2886 for _, (path, name, backward, args) in lefts:
2887 after = self._step_term(t, path, name, backward, args)
2888 full.append((t, after, path, name, backward, args))
2889 t = after
2890 for before, (path, name, backward, args) in reversed(rights):
2891 after = before # a reversed step of the right side
2892 full.append((t, after, path, name, not backward, args))
2893 t = after
2894 chain = [goal[0]] + [k[1] for k in full]
2895 sizes = [term_size(c) for c in chain]
2896 k = max(i for i, n in enumerate(sizes) if n == min(sizes))
2897 lefts2 = [(p[2], p[3], p[4], p[5]) for p in full[:k]]
2898 rights2 = [(p[2], p[3], not p[4], p[5]) for p in reversed(full[k:])]
2899 L, R = goal
2900 result = []
2901 for side, steps in ((0, lefts2), (1, rights2)):
2902 for path, name, backward, args in steps:
2903 vs, l, r = facts[name]
2904 a, b = (r, l) if backward else (l, r)
2905 s = dict(zip(vs, args))
2906 u, v = subst(a, s), subst(b, s)
2907 if side == 0:
2908 target = (replace_at(L, path, v), R)
2909 else:
2910 target = (L, replace_at(R, path, v))
2911 line = None
2912 for k in range(len(vs) + 1):
2913 rule = Rule(name, backward, args[:k])
2914 try:
2915 new, _ = rewrite(self.kernel, (L, R), rule)
2916 except TacticError:
2917 continue
2918 if new == target:
2919 line = ("rw", rule)
2920 break
2921 if line is None:
2922 places = [(0, p) for p in occurrences(L, u)] + \
2923 [(1, p) for p in occurrences(R, u)]
2924 num = places.index((side, path)) + 1
2925 line = (num, Rule(name, backward, args))
2926 result.append(line)
2927 if limit is not None and len(result) >= limit:
2928 return result
2929 L, R = target
2930 return result
2931
2932 def _step_term(self, t, path, name, backward, args):
2933 vs, l, r = self.kernel.facts[name]
2934 b = l if backward else r
2935 return replace_at(t, path, subst(b, dict(zip(vs, args))))
2936
2937 @staticmethod
2938 def lines_from_rules(steps):
2939 """Joins consecutive rw rules into one rw [ … ]; nth_rw separately."""
2940 lines, batch = [], []
2941 for tag, rule in steps:
2942 if tag == "rw":
2943 batch.append(rule.text())
2944 continue
2945 if batch:
2946 lines.append(f"rw [{', '.join(batch)}]")
2947 batch = []
2948 lines.append(f"nth_rw {tag} [{rule.text()}]")
2949 if batch:
2950 lines.append(f"rw [{', '.join(batch)}]")
2951 return lines
2952
2953 def auto(self, proof, goal, budget, lemmas):
2954 seconds = None if budget is None else float("inf") # explicit
2955 budget = budget or 30000
2956 t0 = time.perf_counter()
2957 method = "search"
2958 if lemmas is not None: # only these facts: breadth-first search
2959 for n in lemmas:
2960 self.check_rule(proof, Rule(n))
2961 result, visited = self.bfs_solver(lemmas).search(
2962 *goal, budget=budget)
2963 if result is not None:
2964 result = [k for _, k in result[0]] + \
2965 sv.reverse_steps([k for _, k in result[1]])
2966 elif self.theory is not None:
2967 found = self.model_cex(*goal)
2968 if found is not None:
2969 raise TacticError("auto: " + self.theory_falsity_text(
2970 goal, found, bool(proof.history)))
2971 result, visited = self.theory_steps(
2972 proof, goal, budget, None if seconds else 5.0)
2973 else:
2974 cex = counterexample(*goal)
2975 if cex is not None:
2976 raise TacticError("auto: " + self.falsity_text(
2977 goal, cex, bool(proof.history)))
2978 result, method, visited = self.solver_proof(
2979 proof, goal, seconds, budget)
2980 seconds = time.perf_counter() - t0
2981 if result is None:
2982 raise TacticError(self.tr(
2983 f"auto: nie znalazłem dowodu (odwiedzone: "
2984 f"{self.counted(visited, 'term')}, budżet "
2985 f"{fmt_number(budget, self.lang)}, "
2986 f"{self.fmt_seconds(seconds)}); "
2987 "spróbuj auto 100000, auto bez listy faktów albo podziel "
2988 "cel: trans t",
2989 f"auto: no proof found (visited "
2990 f"{self.counted(visited, 'term')}, budget "
2991 f"{fmt_number(budget, self.lang)}, "
2992 f"{self.fmt_seconds(seconds)}); "
2993 "try auto 100000, auto without a list of facts or split "
2994 "the goal: trans t"))
2995 steps = self.steps_to_rules(goal, [(None, k) for k in result], [])
2996 lines = self.lines_from_rules(steps) or ["rfl"]
2997 # the same lines through the ordinary tactics — on a copy
2998 trial = ProofState(proof.name, goal, proof.available, proof.exercise,
2999 constants=proof.constants)
3000 for line in lines:
3001 self.run_line(trial, line)
3002 if trial.goals:
3003 raise TacticError("auto: " + self.tr("wewnętrzny błąd",
3004 "internal error"))
3005 self._auto_info = (len(steps), visited, seconds, method)
3006 return [], lambda: trial.build(), lines
3007
3008 # -- the solver: several strategies, the shortest chain --
3009
3010 @property
3011 def expander(self):
3012 """Expanding theorems into their proofs (solver.py). Facts in a
3013 session are only ever added, so one for the whole session."""
3014 if self._expander is None:
3015 self._expander = sv.Expander(self.kernel, self.proofs)
3016 return self._expander
3017
3018 @property
3019 def normal_form(self):
3020 if self._normal_form is None:
3021 self._normal_form = sv.NormalForm(self.kernel, self.names)
3022 return self._normal_form
3023
3024 def method_text(self, p):
3025 """Where the solver took the proof from (empty: plain search)."""
3026 t, method = p.get("theorem") or "", p.get("method")
3027 if method == "undo":
3028 m = p.get("undo_count", 1)
3029 span = self.tr("kroku" if m == 1 else f"{m} kroków",
3030 "the step" if m == 1 else f"{m} steps")
3031 return self.tr(
3032 f"solver: wróć poleceniem undo — cel sprzed {span} leży na "
3033 f"dowodzie {t} z biblioteki, a stąd droga byłaby dłuższa",
3034 f"solver: go back with undo — the goal before {span} lies on "
3035 f"the library proof of {t}; from here the way would be "
3036 "longer")
3037 if method == "variant":
3038 k = p.get("solver", 1)
3039 return self.tr(
3040 f"skrypt wzorcowy ({t}) — do końca "
3041 f"{self.counted(k, 'step')}",
3042 f"the reference script ({t}): "
3043 f"{self.counted(k, 'step')} to go")
3044 if method == "reference":
3045 return self.tr(
3046 f"solver prowadzi dowodem {t} z biblioteki (tylko faktami "
3047 "dozwolonymi w ćwiczeniu)",
3048 f"the solver follows the library proof of {t} (only with "
3049 "the facts allowed in the exercise)")
3050 if method == "library" and t:
3051 return self.tr(
3052 f"cel to twierdzenie {t} z biblioteki — solver prowadzi jego "
3053 "dowodem, rozwiniętym do faktów dozwolonych w ćwiczeniu",
3054 f"the goal is the library theorem {t} — the solver follows "
3055 "its proof, expanded to the facts allowed in the exercise")
3056 if method == "normal_form":
3057 return self.tr(
3058 "solver: dowód przez postać normalną — obie strony stają się "
3059 "sumą mintermów; istnieje dla każdej prawdziwej równości",
3060 "solver: a proof via the normal form — both sides become a "
3061 "sum of minterms; it exists for every true equation")
3062 return ""
3063
3064 def falsity_text(self, goal, cex, undo=True):
3065 vals = ", ".join(f"{k} = {v}" for k, v in cex.items()) or "—"
3066 return self.tr(
3067 f"ten cel jest fałszywy w algebrze {{0, 1}} ({vals}: lewa "
3068 f"{value(goal[0], cex)}, prawa {value(goal[1], cex)}), więc "
3069 "nie ma dowodu" + (" — cofnij krok (undo)" if undo else ""),
3070 f"this goal is false in the algebra {{0, 1}} ({vals}: left "
3071 f"{value(goal[0], cex)}, right {value(goal[1], cex)}), so it "
3072 "has no proof" + (" — undo the step (undo)" if undo else ""))
3073
3074 def reference_rest(self, proof, goal, allowed):
3075 """The rest of the library proof in an exercise: when both sides
3076 of the goal lie on the (flattened) reference proof of the
3077 statement, returns the piece of the chain between them."""
3078 name = proof.exercise
3079 if not name or name not in self.proofs:
3080 return None
3081 vs, l, r = self.kernel.facts[name]
3082 ren = {x: "?" + x for x in vs}
3083 free = tuple(ren.values())
3084 s = tac.match_pattern(subst(l, ren), proof.statement[0], free, {})
3085 if s is not None:
3086 s = tac.match_pattern(subst(r, ren), proof.statement[1], free, s)
3087 if s is None or len(s) != len(free):
3088 return None
3089 args = tuple(s["?" + x] for x in vs)
3090 steps = self.expander.expand([((), name, False, args)],
3091 allowed)
3092 terms = sv.replay(self.kernel, proof.statement[0], steps)
3093 return sv.segment(terms, steps, goal)
3094
3095 def solver_proof(self, proof, goal, seconds=0.25, budget=4000):
3096 """The shortest chain l → r: (steps, method, visited) or
3097 (None, None, visited)."""
3098 candidates, visited = self.solver_proofs(proof, goal, seconds, budget)
3099 if not candidates:
3100 return None, None, visited
3101 return candidates[0][0], candidates[0][1], visited
3102
3103 def solver_proofs(self, proof, goal, seconds=0.25, budget=4000):
3104 """Chains l → r from several strategies, the shortest first:
3105 ([(steps, method), …], visited).
3106
3107 Methods: "search" (breadth-first, the allowed facts — short,
3108 natural proofs), "reference" (the rest of the library proof in an
3109 exercise), "library" (the goal is an instance of a theorem),
3110 "normal_form" (the normal form: a proof of every true equation).
3111 Steps with theorems that may not yet be used in the exercise are
3112 already expanded into their proofs, and the chain has no loops.
3113
3114 The plan, i.e. the chain chosen at the previous hint (proof.plans),
3115 wins ties: whoever follows the hints follows one proof, and the
3116 length of the rest of the proof drops with every step — the hints
3117 cannot go round in circles."""
3118 allowed = frozenset(proof.available)
3119 candidates = []
3120 order = ("plan", "search", "reference", "library", "normal_form")
3121 deadline = sv.Deadline(None if seconds is None
3122 else max(0.5, 2 * seconds))
3123 # in an exercise, expanded theorems may lead through huge
3124 # terms; library proofs grow at most 3 times
3125 goal_size = term_size(goal[0]) + term_size(goal[1])
3126 bound = 3 * goal_size + 40 if proof.exercise else sv.SIZE_LIMIT
3127
3128 def consider(steps, method, thm="", tag=None):
3129 if steps is None:
3130 return
3131 try:
3132 steps = self.expander.expand(steps, allowed, deadline)
3133 terms = sv.replay(self.kernel, goal[0], steps)
3134 except (sv.TooBig, KeyError, ValueError):
3135 return
3136 if terms[-1] == goal[1]:
3137 steps = sv.without_loops(terms, steps)
3138 if proof.exercise and max(map(term_size, sv.replay(
3139 self.kernel, goal[0], steps))) > bound:
3140 return
3141 candidates.append((len(steps),
3142 order.index(tag or method),
3143 len(candidates), steps, method, thm))
3144
3145 # first the fast and sure strategies…
3146 for steps, terms, method, thm in proof.plans:
3147 consider(sv.segment(terms, steps, goal), method, thm, "plan")
3148 try:
3149 consider(self.reference_rest(proof, goal, allowed), "reference",
3150 proof.exercise)
3151 except (sv.TooBig, KeyError, ValueError):
3152 pass
3153 for step in sv.instances(self.kernel, goal):
3154 consider([step], "library",
3155 "" if step[1] in allowed else step[1])
3156 try:
3157 consider(self.normal_form.proof(*goal, deadline), "normal_form")
3158 except (sv.TooBig, RecursionError):
3159 pass
3160 # …then breadth-first search for a shorter, natural proof; when
3161 # there is a proof already, at most a second (unless timed)
3162 if seconds is None and candidates:
3163 seconds = 1.0
3164 forbidden = ({c[0] for c in proof.seen} - {goal[0]},
3165 {c[1] for c in proof.seen} - {goal[1]})
3166 result, visited = self.bfs_solver(proof.available).search(
3167 *goal, budget=budget, seconds=seconds, forbidden=forbidden)
3168 if result is not None:
3169 consider([k for _, k in result[0]] +
3170 sv.reverse_steps([k for _, k in result[1]]), "search")
3171 candidates.sort() # ties: the order of the strategies
3172 seen_keys, result = set(), []
3173 for _, _, _, steps, method, thm in candidates:
3174 key = tuple(steps)
3175 if key not in seen_keys:
3176 seen_keys.add(key)
3177 result.append((steps, method, thm))
3178 return result, visited
3179
3180 # -- suggestions --
3181
3182 def kind(self, goal, new):
3183 if new[0] == new[1]:
3184 return "closes"
3185 before = term_size(goal[0]) + term_size(goal[1])
3186 after = term_size(new[0]) + term_size(new[1])
3187 return "shrinks" if after < before else "same" if after == before \
3188 else "grows"
3189
3190 def suggestions(self, proof, goal):
3191 """All rewrites of the goal by the facts available in the proof.
3192
3193 Returns (sorted suggestions, {fact: {"forward": what rw [h] does,
3194 "backward": what rw [← h] does, "best": the best rewrite by the
3195 fact}}). Every instance of a pattern in the goal gives a suggestion
3196 of its own: the first is rw [h], the others need explicit
3197 arguments; a repeated atom (a variable, 0, 1) gets nth_rw k."""
3198 key = (goal, tuple(proof.available))
3199 if self._hint_cache[0] == key:
3200 return self._hint_cache[1]
3201 if term_size(goal[0]) + term_size(goal[1]) > MAX_HINT_SIZE:
3202 return [], {}
3203 L, R = goal
3204 pool = list(proof.variables) or ["0", "1"]
3205 subterms = []
3206 for t in (L, R):
3207 for _, u in positions(t):
3208 if u not in subterms:
3209 subterms.append(u)
3210 collected, facts = [], {}
3211 if L == R:
3212 collected.append(self._hint_entry("rfl", None, "closes", None,
3213 [], "tactic", 0, -1))
3214 # in a Robbins theory the order of summands is the job of ac_rfl,
3215 # rw_ac and ac_simp: rewrites by A1 and A2 would only be noise
3216 skip = set(theories.THEORIES[self.theory].get("ac", ())) \
3217 if self.theory is not None else set()
3218 for idx, name in enumerate(proof.available):
3219 if name in skip:
3220 continue
3221 vs, l, r = self.kernel.facts[name]
3222 ren = {x: "?" + x for x in vs}
3223 free = tuple(ren.values())
3224 found = tac.match_pattern(subst(l, ren), L, free, {})
3225 if found is not None:
3226 found = tac.match_pattern(subst(r, ren), R, free, found)
3227 if found is not None:
3228 rule = Rule(name, False, tuple(found[x] for x in free))
3229 collected.append(self._hint_entry(
3230 f"exact {rule.text()}", rule, "closes", None, [],
3231 self.source(name), len(vs), idx))
3232 info = {}
3233 for backward, (a, b) in ((False, (l, r)), (True, (r, l))):
3234 p = self._hint_plain(goal, name, backward, idx)
3235 if p is not None:
3236 info["backward" if backward else "forward"] = p
3237 pat, repl = subst(a, ren), subst(b, ren)
3238 extra = [v for v in free if v not in leaves(pat)]
3239 if pat in free: # a bare variable: every subterm,
3240 candidates = [{pat: u} for u in sorted( # sides first
3241 subterms,
3242 key=lambda u: (u not in goal, -term_size(u)))]
3243 else:
3244 candidates = []
3245 for u in subterms:
3246 s = tac.match_pattern(pat, u, free, {})
3247 if s is not None:
3248 candidates.append(s)
3249 seen_keys, growing = set(), 0
3250 for s in candidates:
3251 choices = list(product(pool, repeat=len(extra)))[:4]
3252 for choice in choices:
3253 s2 = dict(s)
3254 s2.update(zip(extra, choice))
3255 u = subst(pat, s2)
3256 args = tuple(s2[x] for x in free)
3257 if (u, args) in seen_keys or growing >= 3:
3258 continue
3259 seen_keys.add((u, args))
3260 for p in self._hint_instance(
3261 goal, name, backward, args, u,
3262 subst(repl, s2), idx):
3263 if p["kind"] == "grows":
3264 if growing >= 3:
3265 continue
3266 growing += 1
3267 collected.append(p)
3268 old = info.get("best")
3269 if old is None or KINDS.index(p["kind"]) < \
3270 KINDS.index(old["kind"]):
3271 info["best"] = p
3272 if info:
3273 facts[name] = info
3274 result = (self._rank_hints(collected), facts)
3275 self._hint_cache = (key, result)
3276 return result
3277
3278 def _hint_plain(self, goal, name, backward, idx):
3279 """What rw [h] (or rw [← h]) does without arguments — or None."""
3280 rule = Rule(name, backward)
3281 try:
3282 new, _ = rewrite(self.kernel, goal, rule)
3283 u = find_match(self.kernel, goal, rule)[2]
3284 except TacticError:
3285 return None
3286 if new == goal:
3287 return None
3288 return self._hint_entry(f"rw [{rule.text()}]", rule,
3289 self.kind(goal, new), new,
3290 self._paths(goal, u), self.source(name), 0,
3291 idx)
3292
3293 @staticmethod
3294 def _paths(goal, u):
3295 return [path_id(0, p) for p in occurrences(goal[0], u)] + \
3296 [path_id(1, p) for p in occurrences(goal[1], u)]
3297
3298 def _hint_instance(self, goal, name, backward, args, u, v, idx):
3299 """Suggestions for one instance u → v: rw (all occurrences) with
3300 the shortest arguments, or nth_rw k for a repeated atom."""
3301 L, R = goal
3302 paths = self._paths(goal, u)
3303 if isinstance(u, str) and len(paths) > 1:
3304 result = []
3305 for k, sc in enumerate(paths[:3], start=1):
3306 rule = Rule(name, backward, args)
3307 try:
3308 new, _ = rewrite(self.kernel, goal, rule, k)
3309 except TacticError:
3310 continue
3311 result.append(self._hint_entry(
3312 f"nth_rw {k} [{rule.text()}]", rule, self.kind(goal, new),
3313 new, [sc], self.source(name), len(args) + 1, idx))
3314 return result
3315 new = (replace_all(L, u, v), replace_all(R, u, v))
3316 if new == goal:
3317 return []
3318 for k in range(len(args) + 1):
3319 rule = Rule(name, backward, args[:k])
3320 try:
3321 result, _ = rewrite(self.kernel, goal, rule)
3322 except TacticError:
3323 continue
3324 if result == new:
3325 return [self._hint_entry(
3326 f"rw [{rule.text()}]", rule, self.kind(goal, new), new,
3327 paths, self.source(name), len(rule.args), idx)]
3328 return []
3329
3330 @staticmethod
3331 def _hint_entry(tactic, rule, kind, new, paths, source, nargs, idx):
3332 return {"tactic": tactic, "kind": kind,
3333 "rule": rule.text() if rule else "",
3334 "fact": rule.name if rule else "",
3335 "backward": bool(rule and rule.backward),
3336 "result": show_equation(new) if new and kind != "closes"
3337 else "",
3338 "size_after": term_size(new[0]) + term_size(new[1])
3339 if new else 0,
3340 "paths": paths, "source": source, "nargs": nargs,
3341 "index": idx}
3342
3343 @staticmethod
3344 def _rank_hints(entries):
3345 def rank(p):
3346 k = p["kind"]
3347 if k == "closes":
3348 g = 0
3349 elif p.get("solver"):
3350 g = 1
3351 elif k == "shrinks":
3352 g = 3 if p["source"] == "axiom" else 2
3353 else:
3354 g = 4 if k == "same" else 5
3355 after = 0 if k == "closes" else p["size_after"]
3356 return (g, p["tactic"].startswith("exact"), p["nargs"], after,
3357 p["backward"], p["index"])
3358 result, seen_keys, closing = [], set(), 0
3359 for p in sorted(entries, key=rank):
3360 if p["kind"] == "closes":
3361 if closing >= 3 or ("z", p["fact"]) in seen_keys:
3362 continue
3363 closing += 1
3364 seen_keys.add(("z", p["fact"]))
3365 else:
3366 if p["result"] in seen_keys:
3367 continue
3368 seen_keys.add(p["result"])
3369 result.append(p)
3370 return result
3371
3372 def solver_suggestion(self, proof, goal, seconds=0.25, budget=4000):
3373 """The first step of the shortest proof the solver found:
3374 (suggestion or None, visited). The suggestion has the fields
3375 "solver" (the number of steps), "method" and "theorem" (where the
3376 proof comes from). A step that takes a side of the goal back to an
3377 earlier form is taken only when no other proof avoids it."""
3378 if term_size(goal[0]) + term_size(goal[1]) > MAX_HINT_SIZE:
3379 return None, 0
3380 if self.theory is not None:
3381 return self.theory_suggestion(proof, goal, seconds, budget)
3382 undo_hint = self._hint_undo(proof)
3383 if undo_hint is not None:
3384 return undo_hint, 0
3385 candidates, visited = self.solver_proofs(proof, goal, seconds, budget)
3386 choice = None # the shortest; on a tie, not reverting
3387 for steps, method, thm in candidates:
3388 if choice is not None and len(steps) > len(choice[1]):
3389 break
3390 p = self._first_step(proof, goal, steps, method, thm)
3391 if p is None:
3392 continue
3393 if choice is None or (choice[0]["reverts"] and not p["reverts"]):
3394 choice = (p, steps, method, thm)
3395 if not p["reverts"]:
3396 break
3397 undo_hint = self.undo_suggestion(
3398 proof, len(choice[1]) if choice else float("inf"))
3399 if undo_hint is not None:
3400 return undo_hint, visited
3401 if choice is None:
3402 return None, visited
3403 p, steps, method, thm = choice
3404 terms = sv.replay(self.kernel, goal[0], steps)
3405 proof.plans = (proof.plans + [(steps, terms, method, thm)])[-8:]
3406 return p, visited
3407
3408 def theory_steps(self, proof, goal, budget, seconds=None):
3409 """Breadth-first search with the facts of the proof: (steps or
3410 None, visited) — the only strategy in another theory."""
3411 result, visited = self.bfs_solver(proof.available).search(
3412 *goal, budget=budget, seconds=seconds)
3413 if result is None:
3414 return None, visited
3415 return [k for _, k in result[0]] + \
3416 sv.reverse_steps([k for _, k in result[1]]), visited
3417
3418 def theory_suggestion(self, proof, goal, seconds=0.25, budget=4000):
3419 entry = self.variant_suggestion(proof, goal)
3420 if entry is not None:
3421 return entry, 0
3422 if self.theory is not None and "ac" in theories.THEORIES[self.theory]:
3423 return None, 0 # breadth-first search is hopeless here
3424 steps, visited = self.theory_steps(proof, goal, budget, seconds)
3425 if not steps:
3426 return None, visited
3427 return self._first_step(proof, goal, steps, "search", ""), visited
3428
3429 def undo_suggestion(self, proof, length):
3430 """An exercise in which the student left the path: when after m
3431 undos the first goal lies on the reference proof and m + the rest
3432 of that proof < length (the shortest proof from here), the hint is
3433 undo."""
3434 if not proof.exercise or not proof.history:
3435 return None
3436 allowed = frozenset(proof.available)
3437 for m, state in enumerate(reversed(proof.history), start=1):
3438 if m >= length or not state[0]:
3439 break
3440 c = state[0][0][1]
3441 try:
3442 k = self.reference_rest(proof, c, allowed)
3443 except (sv.TooBig, KeyError, ValueError):
3444 continue
3445 if k is not None and m + len(k) < length:
3446 proof.undo_target = (len(proof.history) - m, c, len(k))
3447 return self._hint_undo(proof)
3448 return None
3449
3450 def _hint_undo(self, proof):
3451 """The undo hint from the remembered goal to go back to
3452 (proof.undo_target: the length of the history, the goal there and
3453 the length of the proof from there) — as long as the student
3454 follows it, the solver keeps going back to that goal."""
3455 if proof.undo_target is None:
3456 return None
3457 T, c, rest = proof.undo_target
3458 h = proof.history
3459 if not (T < len(h) and h[T][0] and h[T][0][0][1] == c):
3460 proof.undo_target = None
3461 return None
3462 m = len(h) - T
3463 next_goal = h[-1][0][0][1] if h[-1][0] else ("", "")
3464 return {"tactic": "undo", "kind": "same", "rule": "",
3465 "fact": "", "backward": False,
3466 "result": show_equation(next_goal) if h[-1][0] else "",
3467 "size_after":
3468 term_size(next_goal[0]) + term_size(next_goal[1]),
3469 "paths": [], "source": "", "nargs": 0,
3470 "index": -1, "solver": m + rest, "method": "undo",
3471 "theorem": proof.exercise, "undo_count": m,
3472 "reverts": False}
3473
3474 def _first_step(self, proof, goal, steps, method, thm):
3475 lines = self.steps_to_rules(goal, [(None, k) for k in steps], [],
3476 limit=1)
3477 if not lines:
3478 return None
3479 tag, rule = lines[0]
3480 which = None if tag == "rw" else tag
3481 tactic_text = f"rw [{rule.text()}]" if which is None else \
3482 f"nth_rw {which} [{rule.text()}]"
3483 new, _ = rewrite(self.kernel, goal, rule, which)
3484 side, path, u, _, _ = find_match(self.kernel, goal, rule, which)
3485 paths = self._paths(goal, u) if which is None else \
3486 [path_id(side, path)]
3487 p = self._hint_entry(tactic_text, rule, self.kind(goal, new), new,
3488 paths, self.source(rule.name), len(rule.args),
3489 -1)
3490 p["solver"] = len(steps)
3491 p["method"], p["theorem"] = method, thm
3492 (p,), _ = self.mark_reverting(goal, [p], proof.seen)
3493 return p
3494
3495 # -- the library --
3496
3497 def _replay_library(self):
3498 """Every library theorem through the kernel, in the language of the
3499 session (names, descriptions, section titles, scripts)."""
3500 errors = []
3501 pl = self.lang == "pl"
3502 for section in library.SECTIONS:
3503 record = {"title": section["title_pl" if pl else "title"]}
3504 for thm in section["theorems"]:
3505 name = self.names[thm["name"]]
3506 l, r = equation(thm["equation"])
3507 proof = ProofState(name, (l, r), self.all_facts())
3508 script = localize_script(thm["script"], self.lang, self.names)
3509 t0 = time.perf_counter()
3510 try:
3511 for line in script:
3512 self.run_line(proof, line)
3513 if proof.goals:
3514 raise TacticError(self.tr(
3515 f"zostały cele: {proof.goals}",
3516 f"goals remain: {proof.goals}"))
3517 d = proof.build()
3518 self.kernel.theorem(name, proof.variables, l, r, d)
3519 except (TacticError, ProofError) as e:
3520 errors.append((name, self.error_text(e)))
3521 continue
3522 self.proofs[name] = d
3523 self.order.append(name)
3524 self.lib[name] = {
3525 "section": record, "id": thm["name"],
3526 "statement": (l, r), "script": script,
3527 "short": " ".join(thm["equation"].split())
3528 if has_abbreviations(thm["equation"]) else "",
3529 "variables": proof.variables,
3530 "description": thm["desc_pl" if pl else "desc_en"],
3531 "time": time.perf_counter() - t0,
3532 "steps": self.count_steps(proof.script)}
3533 self.lib_index.setdefault(canonical(l, r), name)
3534 return errors
3535
3536 @staticmethod
3537 def count_steps(script):
3538 n = 0
3539 for line in script:
3540 try:
3541 tag, data = parse_line(line)
3542 except TacticError: # a tactic expression: one step
3543 n += 1
3544 continue
3545 if tag == "rw":
3546 n += len(data[1])
3547 elif tag != "nothing":
3548 n += 1
3549 return n
3550
3551 def trace(self, name):
3552 """The trace of a proof: (step, goals after it), rule by rule."""
3553 info = self.lib.get(name) or self.own.get(name)
3554 available = self.all_facts()
3555 available = available[:available.index(name)]
3556 proof = ProofState(name, info["statement"], available)
3557 result = []
3558 for line in info["script"]:
3559 log = []
3560 try:
3561 if self.run_line(proof, line, log) is None:
3562 continue
3563 except TacticError as e:
3564 result.append((strip_comment(line) + " ✗ " +
3565 self.error_text(e), []))
3566 break
3567 if self.compound(line) is not None:
3568 result.append((strip_comment(line),
3569 [c for _, c in proof.goals]))
3570 continue
3571 tag, data = parse_line(line)
3572 goals = [c for _, c in proof.goals]
3573 if tag == "rw":
3574 prefix = f"nth_rw {data[0]} " if data[0] else ""
3575 for i, (desc, goal) in enumerate(log):
3576 last = i == len(log) - 1
3577 result.append((prefix + desc, goals if last else [goal]))
3578 else:
3579 result.append((strip_comment(line), goals))
3580 return result
3581
3582 # -- commands --
3583
3584 def run(self, line):
3585 """Runs one command or tactic; returns an Output."""
3586 s = " ".join(line.strip().split()) if "\n" not in line else \
3587 line.strip()
3588 if not s:
3589 return Output()
3590 words = s.split(" ")
3591 if words[0] == "bl":
3592 if len(words) == 1:
3593 return self.p_help()
3594 command, rest = words[1], " ".join(words[2:])
3595 method = {
3596 "help": self.p_help, "axioms": self.p_axioms,
3597 "lib": self.p_lib, "prove": self.p_prove,
3598 "lean": self.p_lean, "model": self.p_model,
3599 "tactic": self.p_tactic, "kernel": self.p_kernel,
3600 "forget": self.p_forget, "theory": self.p_theory,
3601 "replay": self.p_replay,
3602 "trace": self.p_trace}.get(command)
3603 if method is None:
3604 similar = difflib.get_close_matches(command, COMMANDS, 1)
3605 return self.error(self.tr(
3606 f"nie ma polecenia bl {command}",
3607 f"there is no command bl {command}") + (
3608 f" — bl {similar[0]}?" if similar else " (bl help)"))
3609 return method(rest) if command != "help" else method()
3610 if s in ("help", "?"):
3611 return self.p_help()
3612 if s == "qed":
3613 return self.p_qed()
3614 if s == "undo":
3615 return self.p_undo()
3616 if s == "restart":
3617 return self.p_restart()
3618 if s == "abort":
3619 return self.p_abort()
3620 if s == "script":
3621 return self.p_script()
3622 if s == "hint":
3623 return self.p_hint()
3624 if s in ("clear", "cls"):
3625 return Output()
3626 if self.proof is None:
3627 if words[0] in TACTICS or words[0] in TACTICALS or \
3628 words[0] in self.tactics or \
3629 words[0].startswith(("rw[", "(", tc.HOLE)):
3630 return self.error(self.tr(
3631 "nie ma dowodu w toku — zacznij od bl prove …",
3632 "no proof in progress — start with bl prove …"))
3633 similar = difflib.get_close_matches(
3634 words[0], list(TACTICS) + list(TACTICALS) +
3635 list(self.tactics) + ["qed", "undo", "hint", "bl"], 1)
3636 return self.error(self.tr(
3637 f"nie znam polecenia {words[0]!r}",
3638 f"unknown command {words[0]!r}") + (
3639 f" — {similar[0]}?" if similar else " (bl help)"))
3640 return self.p_tactic_step(s)
3641
3642 def show_goals(self, w, proof):
3643 if not proof.goals:
3644 w.add((" ✓ ", "ok"), (self.tr(
3645 "brak celów — wpisz qed, a jądro sprawdzi cały dowód",
3646 "no goals — type qed and the kernel checks the whole proof"),
3647 "ok"))
3648 return
3649 n = len(proof.goals)
3650 if n > 1:
3651 w.add((f" {self.counted(n, 'goal')}", "dim"))
3652 for i, (_, goal) in enumerate(proof.goals):
3653 w.add((" ⊢ ", "code" if i == 0 else "dim"),
3654 (show_equation(goal), "goal" if i == 0 else "dim"))
3655
3656 def p_tactic_step(self, s):
3657 proof = self.proof
3658 log = []
3659 self._auto_info = None
3660 self._compound = None
3661 try:
3662 lines = self.run_line(proof, s, log)
3663 except (TacticError, ProofError) as e:
3664 w = self.error(self.error_text(e))
3665 if getattr(e, "trace", None) is not None:
3666 w.add((" ", ""), (self.tr("gdzie zawiodła: ",
3667 "where it failed: "), "dim"),
3668 (f"bl trace {s}", "code", {"insert": f"bl trace {s}"}))
3669 return w
3670 w = Output()
3671 if lines is None:
3672 return w
3673 if self._compound is not None:
3674 _, _, runner, end = self._compound
3675 self.compound_summary(w, runner, end)
3676 elif self._auto_info:
3677 k, visited, seconds, method = self._auto_info
3678 origin = {"reference": self.tr("dowód z biblioteki",
3679 "a library proof"),
3680 "library": self.tr("dowód z biblioteki",
3681 "a library proof"),
3682 "normal_form": self.tr("postać normalna",
3683 "the normal form")}.get(method)
3684 w.add((" auto: ", "solver"), (self.tr(
3685 f"dowód w {self.in_steps(k)} (odwiedzone: "
3686 f"{self.counted(visited, 'term')}, "
3687 f"{self.fmt_seconds(seconds)}",
3688 f"proof in {self.counted(k, 'step')} (visited "
3689 f"{self.counted(visited, 'term')}, "
3690 f"{self.fmt_seconds(seconds)}") +
3691 (f"; {origin})" if origin else ")"), "solver"))
3692 for line in lines:
3693 w.add((" ", ""), (line, "code", {"insert": line}))
3694 elif len(log) > 1:
3695 for desc, goal in log[:-1]:
3696 w.add((" · ", "dim"), (desc, "dim"), (" ", ""),
3697 (show_equation(goal), "dim"))
3698 self.show_goals(w, proof)
3699 return w
3700
3701 def p_help(self, *_):
3702 w = Output()
3703 t = self.tr
3704 w.add((t("Boole Lab — algebra Boole'a w jądrze z wykładu 3",
3705 "Boole Lab — Boolean algebra in the kernel of Lecture 3"),
3706 "heading"))
3707 w.add((t("Polecenia", "Commands"), "heading"))
3708 rows = [
3709 ("bl prove nazwa : równość", "bl prove name : equation",
3710 "zacznij dowód, np. bl prove moje : x * x = x",
3711 "start a proof, e.g. bl prove mine : x * x = x", "bl prove "),
3712 ("bl prove równość", "bl prove equation",
3713 "to samo, nazwa nadana automatycznie",
3714 "the same, with an automatic name", "bl prove "),
3715 ("bl prove nazwa", "bl prove name",
3716 "ćwiczenie: twierdzenie z biblioteki od nowa",
3717 "exercise: re-prove a library theorem", "bl prove "),
3718 ("bl axioms", "bl axioms", "aksjomaty Huntingtona H1–H8",
3719 "Huntington's axioms H1–H8", "bl axioms"),
3720 ("bl lib [nazwa]", "bl lib [name]",
3721 "biblioteka twierdzeń / jedno twierdzenie z dowodem",
3722 "the theorem library / one theorem with its proof", "bl lib "),
3723 ("bl lean nazwa [full]", "bl lean name [full]",
3724 "ten sam dowód w Leanie 4 (full: cały plik)",
3725 "the same proof in Lean 4 (full: a whole file)", "bl lean "),
3726 ("bl model równość", "bl model equation",
3727 "czy równość zachodzi w algebrze {0, 1}?",
3728 "does the equation hold in the algebra {0, 1}?", "bl model "),
3729 ("bl tactic [nazwa]", "bl tactic [name]", "opis taktyki",
3730 "how a tactic works", "bl tactic "),
3731 ("bl kernel", "bl kernel", "co sprawdza jądro, gdzie jest kod",
3732 "what the kernel checks, where its code is", "bl kernel"),
3733 ("bl forget nazwa", "bl forget name",
3734 "usuń własne twierdzenie", "delete your own theorem",
3735 "bl forget "),
3736 ("bl theory [nazwa]", "bl theory [name]",
3737 "inne aksjomaty: DN1, Sh1, mediana; modele skończone",
3738 "other axioms: DN1, Sh1, the median; finite models",
3739 "bl theory "),
3740 ("bl tactic nazwa := t", "bl tactic name := t",
3741 "własna taktyka (w Leanie: macro); budowa i analiza",
3742 "your own tactic (in Lean: a macro); structure and analysis",
3743 "bl tactic "),
3744 ("bl trace taktyka", "bl trace tactic",
3745 "próba na bieżącym celu, przebieg krok po kroku",
3746 "a dry run on the current goal, step by step", "bl trace "),
3747 ("bl replay mann | mccune", "bl replay mann | mccune",
3748 "dowód Robbinsa krok po kroku (wariant Manna / McCune'a)",
3749 "the Robbins proof step by step (Mann's / McCune's variant)",
3750 "bl replay "),
3751 ]
3752 for pl, en, desc_pl, desc_en, insert in rows:
3753 w.add((" ", ""),
3754 (t(pl, en).ljust(28), "code", {"insert": insert}),
3755 (t(desc_pl, desc_en), "dim"))
3756 w.add((t("Taktyki (działają na pierwszym celu; zapis jak w Leanie 4)",
3757 "Tactics (act on the first goal; written as in Lean 4)"),
3758 "heading"))
3759 tactics = [
3760 ("rw [H6, ← H7 x, H2 n(x) y]", "rw [",
3761 "przepisywanie, na końcu rfl", "rewriting, then rfl"),
3762 ("nth_rw k [h]", "nth_rw ", "przepisz tylko k-te dopasowanie",
3763 "rewrite only the k-th match"),
3764 ("rfl · symm · trans t", "trans ",
3765 "zwrotność, symetria, przechodniość",
3766 "reflexivity, symmetry, transitivity"),
3767 ("exact h args", "exact ", "cel jest instancją faktu h",
3768 "the goal is an instance of the fact h"),
3769 (t("auto [budżet] [[h, …]]", "auto [budget] [[h, …]]"), "auto",
3770 "solver: dowód każdej prawdziwej równości",
3771 "solver: a proof of every true equation"),
3772 ("first | t₁ | t₂ · try t", "first | ",
3773 "pierwsza, która się uda · próba bez ryzyka",
3774 "the first that succeeds · a safe attempt"),
3775 ("repeat t · iterate n t", "repeat ",
3776 "powtarzaj, dopóki się udaje · n razy",
3777 "again while it succeeds · n times"),
3778 ("t₁; t₂ · t₁ <;> t₂ · all_goals t", "all_goals ",
3779 "po kolei · na każdym nowym celu · na wszystkich",
3780 "in turn · on every new goal · on all goals"),
3781 ("ac_rfl · rw_ac [h] · ac_simp [h]", "rw_ac [",
3782 "modulo A1, A2 (bl theory robbins)",
3783 "modulo A1, A2 (bl theory robbins)"),
3784 ]
3785 for cmd, insert, desc_pl, desc_en in tactics:
3786 w.add((" ", ""), (cmd.ljust(28), "code", {"insert": insert}),
3787 (t(desc_pl, desc_en), "dim"))
3788 w.add((t("Dowód", "Proof"), "heading"))
3789 w.add((" ", ""), ("qed", "code"),
3790 t(" jądro sprawdza dowód · ", " the kernel checks the proof · "),
3791 ("undo", "code"), " · ", ("restart", "code"), " · ",
3792 ("abort", "code"), " · ", ("script", "code"), " · ",
3793 ("hint", "code"), " · ", ("clear", "code"))
3794 w.add((t(" TAB albo → przyjmuje podpowiedź · ↑/↓ historia · "
3795 "kolory: zielony zamyka cel, niebieski go zmniejsza, "
3796 "bursztynowy nie zmienia rozmiaru, szary powiększa",
3797 " TAB or → accepts the suggestion · ↑/↓ history · colors: "
3798 "green closes the goal, blue shrinks it, amber keeps its "
3799 "size, grey grows it"), "dim"))
3800 return w
3801
3802 def p_axioms(self, *_):
3803 if self.theory is not None:
3804 return self.theory_card()
3805 w = Output()
3806 w.add((self.tr("Aksjomaty Huntingtona (1904): algebra Boole'a jako "
3807 "teoria równościowa",
3808 "Huntington's axioms (1904): Boolean algebra as an "
3809 "equational theory"), "heading"))
3810 for name in self.axioms:
3811 w.add((" ", ""), (name.ljust(4), "name",
3812 {"insert": f"rw [{name}]"}),
3813 (self.fact_text(name), "goal"))
3814 w.add((self.tr(" W Leanie: pola klasy AlgebraBoolea "
3815 "(lean/Wyklad03.lean).",
3816 " In Lean: fields of the class HuntingtonAlgebra "
3817 "(lean/Lecture03.lean)."), "dim"))
3818 return w
3819
3820 def p_lib(self, rest=""):
3821 rest = rest.strip()
3822 if rest:
3823 return self.lib_one(rest)
3824 w = Output()
3825 n = len(self.order)
3826 w.add((self.tr(f"Biblioteka: {self.counted(n, 'theorem')}, każde "
3827 "przyjęte przez jądro przy starcie",
3828 f"Library: {self.counted(n, 'theorem')}, each "
3829 "accepted by the kernel at startup"), "heading"))
3830 sections = []
3831 for name in self.order:
3832 s = self.lib[name]["section"]
3833 if s not in sections:
3834 sections.append(s)
3835 for s in sections:
3836 w.add((s["title"], "heading"))
3837 for name in self.order:
3838 info = self.lib[name]
3839 if info["section"] is not s:
3840 continue
3841 self._lib_row(w, name, info)
3842 if self.own:
3843 w.add((self.tr("Twoje twierdzenia", "Your theorems"), "heading"))
3844 for name, info in self.own.items():
3845 self._lib_row(w, name, info)
3846 w.add((self.tr(" bl lib nazwa — dowód i ślad; kliknij nazwę",
3847 " bl lib name — the proof and its trace; click a "
3848 "name"), "dim"))
3849 return w
3850
3851 def _lib_row(self, w, name, info):
3852 assumed = sorted(self.kernel.assumptions[name],
3853 key=lambda a: self.axioms.index(a))
3854 name_width = max(map(len, self.order + list(self.own))) + 2
3855 text = info.get("short") or show_equation(info["statement"])
3856 w.add((" ✓ ", "ok"), (name.ljust(name_width), "name",
3857 {"run": f"bl lib {name}"}),
3858 (text.ljust(max(42, len(text) + 2)), "goal"),
3859 (self.counted(info["steps"], "step").ljust(11), "dim"),
3860 (" ".join(assumed), "dim"))
3861
3862 def lib_one(self, name):
3863 if name in self.axioms:
3864 w = Output()
3865 w.add((name, "name"), " : ", (self.fact_text(name), "goal"),
3866 (self.tr(" aksjomat", " axiom"), "dim"))
3867 return w
3868 info = self.lib.get(name) or self.own.get(name)
3869 if info is None:
3870 similar = difflib.get_close_matches(name, self.all_facts(), 3)
3871 return self.error(self.tr(f"nie ma twierdzenia {name}",
3872 f"there is no theorem {name}") + (
3873 " — " + ", ".join(similar) + "?" if similar else ""))
3874 w = Output()
3875 t = self.tr
3876 w.add((name, "name"), " : ",
3877 (info.get("short") or show_equation(info["statement"]), "goal"),
3878 (" ✓ " + t("przyjęte przez jądro", "accepted by the kernel"),
3879 "ok"))
3880 if info.get("short"):
3881 w.add((t(" po rozwinięciu skrótów: ",
3882 " with the abbreviations expanded: "), "dim"),
3883 (show_equation(info["statement"]), "dim"))
3884 if name in self.lib:
3885 s = info["section"]
3886 w.add((t(" sekcja: ", " section: ") + s["title"] + " — "
3887 + info["description"], "dim"))
3888 w.add((t(f" skrypt ({self.counted(info['steps'], 'step')}):",
3889 f" script ({self.counted(info['steps'], 'step')}):"),
3890 "heading"))
3891 for line in info["script"]:
3892 style = "dim" if line.startswith("--") else "code"
3893 w.add((" ", ""), (line, style))
3894 w.add((t(" przebieg:", " trace:"), "heading"))
3895 trace_rows = self.trace(name)
3896 width = max([len(o) for o, _ in trace_rows] + [0]) + 2
3897 w.add((" " + " " * (width + 2), ""),
3898 (show_equation(info["statement"]), "goal"))
3899 for desc, goals in trace_rows:
3900 goals_text = " | ".join(show_equation(c) for c in goals) or \
3901 t("✓ brak celów", "✓ no goals")
3902 w.add((" ", ""), (desc.ljust(width), "code"), ("⟶ ", "dim"),
3903 (goals_text, "goal" if goals else "ok"))
3904 d = self.proofs[name]
3905 assumed = sorted(self.kernel.assumptions[name],
3906 key=lambda a: self.axioms.index(a))
3907 used = sorted(used_facts(d), key=self.all_facts().index)
3908 w.add((t(" założenia (jak #print axioms): ",
3909 " assumptions (like #print axioms): "), "dim"),
3910 (", ".join(assumed), "code"))
3911 w.add((t(" korzysta z: ", " uses: "), "dim"),
3912 *self._name_list(used))
3913 w.add((t(f" drzewo dowodu dla jądra: {self.counted(size(d), 'node')}",
3914 f" proof tree for the kernel: "
3915 f"{self.counted(size(d), 'node')}"), "dim"))
3916 w.add((" ", ""), (f"bl lean {name}", "code",
3917 {"run": f"bl lean {name}"}),
3918 (t(" — ten sam dowód w Leanie · ",
3919 " — the same proof in Lean · "), "dim"),
3920 (f"bl prove {name}", "code", {"run": f"bl prove {name}"}),
3921 (t(" — udowodnij sam", " — prove it yourself"), "dim"))
3922 return w
3923
3924 def _name_list(self, names):
3925 result = []
3926 for i, n in enumerate(names):
3927 if i:
3928 result.append((", ", "dim"))
3929 action = {"run": f"bl lib {n}"} if n not in self.axioms \
3930 else None
3931 result.append((n, "name", action) if action else (n, "name"))
3932 return result
3933
3934 def p_prove(self, rest):
3935 rest = rest.strip()
3936 t = self.tr
3937 m = re.fullmatch(r"([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+)", rest)
3938 exercise = None
3939 if m:
3940 name, text = m.group(1), m.group(2)
3941 elif NAME.fullmatch(rest) and rest in self.lib:
3942 name, text = rest, show_equation(self.lib[rest]["statement"])
3943 elif NAME.fullmatch(rest) and self.variant_step(rest):
3944 name, text = rest, self.variant_step(rest)[2]["statement"]
3945 elif "=" in rest:
3946 name, text = None, rest
3947 else:
3948 return self.error(t(
3949 "użycie: bl prove nazwa : równość (np. bl prove moje : "
3950 "x * x = x) albo bl prove nazwa_z_biblioteki",
3951 "usage: bl prove name : equation (e.g. bl prove mine : "
3952 "x * x = x) or bl prove library_name"))
3953 try:
3954 l, r = self.parse_equation(text)
3955 if self.theory is not None:
3956 self.kernel.term(l), self.kernel.term(r)
3957 except (SyntaxError, ValueError, IndexError, ProofError):
3958 return self.error(t(
3959 f"nie rozumiem równości {text!r} — zapis: "
3960 f"{self.notation_text()}, nawiasy",
3961 f"cannot parse the equation {text!r} — notation: "
3962 f"{self.notation_text()}, parentheses"))
3963 if term_size(l) + term_size(r) > MAX_STATEMENT:
3964 return self.error(t(
3965 f"równość jest za długa (najwyżej {MAX_STATEMENT} węzłów) — "
3966 "podziel ją na lematy",
3967 f"the equation is too long (at most {MAX_STATEMENT} nodes) — "
3968 "split it into lemmas"))
3969 vs = equation_vars(l, r)
3970 bad = [v for v in vs if not VARIABLE.fullmatch(v)]
3971 if bad:
3972 return self.error(t(
3973 f"zmienne to litery z ewentualnym numerem (x, y, a1); "
3974 f"popraw: {', '.join(bad)}",
3975 f"variables are letters with an optional number (x, y, a1); "
3976 f"fix: {', '.join(bad)}"))
3977 taken = False
3978 ex = self.lib_index.get(canonical(l, r)) or \
3979 self.lib_index.get(canonical(r, l))
3980 if name is None:
3981 i = 1
3982 while f"{t('tw', 'thm')}{i}" in self.kernel.facts or \
3983 f"{t('tw', 'thm')}{i}" in self.tactics:
3984 i += 1
3985 name = f"{t('tw', 'thm')}{i}"
3986 elif name in self.kernel.facts:
3987 if name in self.lib and ex == name:
3988 taken = True
3989 else:
3990 return self.error(t(
3991 f"nazwa {name} jest już zajęta — wybierz inną",
3992 f"the name {name} is taken — choose another"))
3993 elif name in self.tactics:
3994 return self.error(t(
3995 f"{name} to nazwa taktyki — twierdzenie musi się nazywać "
3996 "inaczej",
3997 f"{name} is the name of a tactic — a theorem needs another "
3998 "name"))
3999 elif (name in FORBIDDEN and not (self._replaying and
4000 name in LEGACY_NAMES)) or \
4001 VARIABLE.fullmatch(name):
4002 return self.error(t(
4003 f"{name} nie może być nazwą twierdzenia (słowo Leana, "
4004 "polecenie albo nazwa zmiennej)",
4005 f"{name} cannot be a theorem name (a Lean keyword, a "
4006 "command or a variable name)"))
4007 available = self.all_facts()
4008 if ex:
4009 available = self.axioms + \
4010 self.order[:self.order.index(ex)]
4011 w = Output()
4012 if self.proof is not None:
4013 w.add((t(f" (porzucam dowód {self.proof.name})",
4014 f" (abandoning the proof of {self.proof.name})"),
4015 "dim"))
4016 command = f"bl prove {name} : {show(l)} = {show(r)}"
4017 self.proof = ProofState(name, (l, r), available, ex, taken, command,
4018 self.constants())
4019 self.last = None
4020 w.add((t("Dowód ", "Proof of "), "heading"), (name, "name"),
4021 " : ", (show_equation((l, r)), "goal"))
4022 if ex:
4023 n_earlier = len(available) - len(self.axioms)
4024 if n_earlier == 0:
4025 scope = t("dostępne są tylko aksjomaty",
4026 "you may use only the axioms")
4027 else:
4028 scope = t(
4029 f"dostępne są aksjomaty i "
4030 f"{self.counted(n_earlier, 'theorem')}"
4031 f" {word_form(n_earlier, 'earlier', 'pl')}",
4032 f"you may use the axioms and the "
4033 f"{self.counted(n_earlier, 'theorem')} before it")
4034 w.add((t(f" ćwiczenie: to twierdzenie {ex} z biblioteki — ",
4035 f" exercise: this is the library theorem {ex} — ")
4036 + scope, "warning"))
4037 if self.lib[ex].get("short"):
4038 w.add((t(" w skrócie: ", " in short: "), "dim"),
4039 (self.lib[ex]["short"], "dim"))
4040 elif self.theory is None and has_abbreviations(text):
4041 w.add((t(" w skrócie: ", " in short: "), "dim"),
4042 (" ".join(text.split()), "dim"))
4043 found = self.variant_step(name, (l, r))
4044 if found is not None:
4045 key, stage, step = found
4046 variant = rl.VARIANTS[key]
4047 w.add((t(f" {variant['title_pl']}, etap {stage}: "
4048 f"{step['source_pl']} — hint i TAB prowadzą skryptem "
4049 "wzorcowym",
4050 f" {variant['title_en']}, stage {stage}: "
4051 f"{step['source_en']} — hint and TAB follow the "
4052 "reference script"), "dim"))
4053 if self.theory is not None:
4054 w.add((t(f" teoria {self.theory_name(self.theory)}: "
4055 f"aksjomaty {', '.join(self.axioms)}",
4056 f" theory {self.theory_name(self.theory)}: axioms "
4057 f"{', '.join(self.axioms)}"), "dim"))
4058 found = self.model_cex(l, r)
4059 if found is not None:
4060 w.add((" " + t("uwaga: ", "warning: ")
4061 + self.theory_falsity_text((l, r), found), "warning"))
4062 cex = counterexample(l, r) if self.theory is None else None
4063 if cex is not None:
4064 vals = ", ".join(f"{k} = {v}" for k, v in cex.items()) or "—"
4065 w.add((t(f" uwaga: ta równość jest fałszywa w algebrze {{0, 1}} "
4066 f"({vals}: lewa {value(l, cex)}, prawa "
4067 f"{value(r, cex)}) — jądro nie przyjmie żadnego dowodu",
4068 f" warning: this equation is false in the algebra "
4069 f"{{0, 1}} ({vals}: left {value(l, cex)}, right "
4070 f"{value(r, cex)}) — the kernel will accept no proof"),
4071 "warning"))
4072 self.show_goals(w, self.proof)
4073 return w
4074
4075 def p_qed(self):
4076 t = self.tr
4077 proof = self.proof
4078 if proof is None:
4079 return self.error(t("nie ma dowodu w toku",
4080 "no proof in progress"))
4081 if proof.goals:
4082 return self.error(t(
4083 f"otwarte cele: {len(proof.goals)} — jądro dostaje tylko "
4084 "pełny dowód",
4085 f"open goals: {len(proof.goals)} — the kernel takes only a "
4086 "complete proof"))
4087 d = proof.build()
4088 l, r = proof.statement
4089 if proof.taken:
4090 # an exercise under a library name: a fresh kernel checks it,
4091 # knowing only the facts available in the exercise
4092 kernel = Kernel(boolean.SIGNATURE)
4093 for n in proof.available:
4094 kernel.facts[n] = self.kernel.facts[n]
4095 kernel.assumptions[n] = self.kernel.assumptions[n]
4096 else:
4097 kernel = self.kernel
4098 try:
4099 kernel.theorem(proof.name, proof.variables, l, r, d)
4100 except ProofError as e:
4101 return self.error(t("jądro odrzuciło dowód: ",
4102 "the kernel rejected the proof: ") + str(e))
4103 w = Output()
4104 w.add(("✓ ", "ok"), (t("jądro przyjęło ", "the kernel accepted "),
4105 "ok"), (proof.name, "name"), " : ",
4106 (show_equation(proof.statement), "goal"))
4107 assumed = sorted(kernel.assumptions[proof.name],
4108 key=lambda a: self.axioms.index(a))
4109 w.add((t(f" drzewo dowodu: {self.counted(size(d), 'node')} · "
4110 "założenia (jak #print axioms): ",
4111 f" proof tree: {self.counted(size(d), 'node')} · "
4112 "assumptions (like #print axioms): "), "dim"),
4113 (", ".join(assumed), "code"))
4114 self.last = (proof.command, list(proof.script))
4115 if proof.taken:
4116 w.add((t(f" {proof.name} jest już w bibliotece — Twój dowód "
4117 "sprawdziło osobne jądro z faktami z ćwiczenia",
4118 f" {proof.name} is already in the library — your proof "
4119 "was checked by a separate kernel holding the facts of "
4120 "the exercise"), "dim"))
4121 else:
4122 self.proofs[proof.name] = d
4123 script = list(proof.script)
4124 self.own[proof.name] = {
4125 "statement": (l, r), "script": script,
4126 "variables": proof.variables,
4127 "steps": self.count_steps(script),
4128 "command": proof.command}
4129 if self.theory is None: # the page keeps only Boolean ones
4130 w.extras["new"] = {"name": proof.name,
4131 "equation": show_equation((l, r)),
4132 "script": script}
4133 w.add((t(" od teraz możesz go używać: ",
4134 " from now on you can use it: "), "dim"),
4135 (f"rw [{proof.name}]", "code"), " · ",
4136 (f"bl lean {proof.name}", "code",
4137 {"run": f"bl lean {proof.name}"}))
4138 self.proof = None
4139 return w
4140
4141 def p_undo(self):
4142 if self.proof is None:
4143 return self.error(self.tr("nie ma dowodu w toku",
4144 "no proof in progress"))
4145 if not self.proof.history:
4146 return self.error(self.tr("nie ma czego cofać",
4147 "nothing to undo"))
4148 self.proof.undo()
4149 w = Output().add((self.tr(" cofnięte", " undone"), "dim"))
4150 self.show_goals(w, self.proof)
4151 return w
4152
4153 def p_restart(self):
4154 d = self.proof
4155 if d is None:
4156 return self.error(self.tr("nie ma dowodu w toku",
4157 "no proof in progress"))
4158 self.proof = ProofState(d.name, d.statement, d.available, d.exercise,
4159 d.taken, d.command, d.constants)
4160 w = Output().add((self.tr(" od początku: ", " from the start: "),
4161 "dim"), (d.name, "name"))
4162 self.show_goals(w, self.proof)
4163 return w
4164
4165 def p_abort(self):
4166 if self.proof is None:
4167 return self.error(self.tr("nie ma dowodu w toku",
4168 "no proof in progress"))
4169 name, self.proof = self.proof.name, None
4170 return Output().add((self.tr(f" porzucony dowód {name}",
4171 f" abandoned the proof of {name}"),
4172 "dim"))
4173
4174 def p_script(self):
4175 w = Output()
4176 if self.proof is not None:
4177 w.add((self.tr("-- dowód w toku (jądro jeszcze go nie sprawdziło)",
4178 "-- proof in progress (not yet checked by the "
4179 "kernel)"), "dim"))
4180 command, script, end = (self.proof.command,
4181 self.proof.script, [])
4182 elif self.last is not None:
4183 w.add((self.tr("-- sprawdzone przez jądro (qed)",
4184 "-- checked by the kernel (qed)"), "ok"))
4185 command, script = self.last
4186 end = ["qed"]
4187 else:
4188 return self.error(self.tr("nie ma skryptu do pokazania",
4189 "there is no script to show"))
4190 for line in [command] + script + end:
4191 w.add((line, "code"))
4192 return w
4193
4194 def p_hint(self):
4195 proof = self.proof
4196 if proof is None:
4197 return self.error(self.tr(
4198 "nie ma dowodu w toku — np. bl prove idem_plus",
4199 "no proof in progress — e.g. bl prove add_idem"))
4200 w = Output()
4201 if not proof.goals:
4202 return w.add((" qed", "code", {"insert": "qed"}), (self.tr(
4203 " — wszystkie cele zamknięte", " — all goals are closed"),
4204 "dim"))
4205 goal = proof.goals[0][1]
4206 self.variant_hint(w, proof, goal)
4207 entries, _ = self.suggestions(proof, goal)
4208 sol = None
4209 found = self.model_cex(*goal) if self.theory is not None else None
4210 if found is not None:
4211 return w.add((self.tr("Podpowiedzi dla ", "Suggestions for "),
4212 "heading"), (show_equation(goal), "goal")).add(
4213 (" ✗ ", "error"), (self.theory_falsity_text(
4214 goal, found, bool(proof.history)), "warning"))
4215 cex = counterexample(*goal) if self.theory is None else None
4216 if cex is not None:
4217 falsity = self.falsity_text(goal, cex, bool(proof.history))
4218 return w.add((self.tr("Podpowiedzi dla ", "Suggestions for "),
4219 "heading"), (show_equation(goal), "goal")).add(
4220 (" ✗ ", "error"), (falsity, "warning"))
4221 if not entries or entries[0]["kind"] != "closes":
4222 sol, visited = self.solver_suggestion(proof, goal)
4223 if sol:
4224 entries = self._rank_hints([sol] + [
4225 p for p in entries if p["tactic"] != sol["tactic"]])
4226 w.add((self.tr("Podpowiedzi dla ", "Suggestions for "), "heading"),
4227 (show_equation(goal), "goal"))
4228 descs = {"closes": self.tr("zamyka cel", "closes the goal"),
4229 "shrinks": self.tr("zmniejsza", "shrinks"),
4230 "same": self.tr("ten sam rozmiar", "same size"),
4231 "grows": self.tr("powiększa", "grows")}
4232 width = max([len(p["tactic"]) for p in entries[:10]] + [0]) + 2
4233 for p in entries[:10]:
4234 desc = descs[p["kind"]]
4235 if p.get("solver"):
4236 k = p["solver"]
4237 desc = self.tr(f"solver: dowód w {self.in_steps(k)}",
4238 f"solver: proof in {self.counted(k, 'step')}")
4239 w.add((" ● ", p["kind"]),
4240 (p["tactic"].ljust(width), "code", {"insert": p["tactic"]}),
4241 (desc.ljust(28), p["kind"]),
4242 (p["result"], "dim"))
4243 if len(entries) > 10:
4244 w.add((self.tr(f" … i {fmt_number(len(entries) - 10, 'pl')}"
4245 " innych "
4246 "(panel Podpowiedzi)",
4247 f" … and {len(entries) - 10} more (Suggestions "
4248 "panel)"), "dim"))
4249 if sol is not None and self.method_text(sol):
4250 w.add((" " + self.method_text(sol), "dim"))
4251 if sol is None and entries and entries[0]["kind"] != "closes":
4252 if self.theory is not None and \
4253 "ac" in theories.THEORIES[self.theory]:
4254 w.add((self.tr(
4255 " tu nie ma przeszukiwania wszerz (dowody są za "
4256 "długie) — skorzystaj z wariantów dowodu (bl replay) albo "
4257 "z auto [reguły, instancje]",
4258 " there is no breadth-first search here (the proofs are "
4259 "too long) — follow a variant of the proof (bl replay) or "
4260 "use auto [rules, instances]"), "dim"))
4261 elif self.theory is not None:
4262 w.add((self.tr(
4263 " przeszukiwanie wszerz nie znalazło dowodu w limicie — "
4264 "w tej teorii dowody bywają bardzo długie; spróbuj auto "
4265 "100000 albo podziel cel: trans t",
4266 " breadth-first search found no proof within the limit "
4267 "— proofs in this theory can be very long; try auto "
4268 "100000 or split the goal: trans t"), "dim"))
4269 else:
4270 w.add((self.tr(
4271 " solver nie zmieścił się w limicie (za duży cel)"
4272 " — spróbuj auto albo podziel cel: trans t",
4273 " the solver hit its limit (the goal is too big) "
4274 "— try auto or split the goal: trans t"), "dim"))
4275 return w
4276
4277 def p_model(self, rest):
4278 t = self.tr
4279 if self.theory is not None:
4280 return self.theory_model(rest)
4281 try:
4282 l, r = equation(rest)
4283 except (SyntaxError, ValueError, IndexError):
4284 return self.error(t("użycie: bl model x + y = y + x",
4285 "usage: bl model x + y = y + x"))
4286 vs = equation_vars(l, r)
4287 if len(vs) > 10:
4288 return self.error(t("za dużo zmiennych (najwyżej 10)",
4289 "too many variables (at most 10)"))
4290 cex = counterexample(l, r)
4291 w = Output()
4292 n = 2 ** len(vs)
4293 if cex is None:
4294 w.add(("✓ ", "ok"), (show_equation((l, r)), "goal"), (t(
4295 f" zachodzi dla wszystkich {fmt_number(n, 'pl')} "
4296 "wartościowań "
4297 "w {0, 1}",
4298 f" holds for all {fmt_number(n, 'en')} valuations in "
4299 "{0, 1}"),
4300 "ok"))
4301 w.add((t(" Równość prawdziwa w {0, 1} zachodzi w każdej "
4302 "algebrze Boole'a (twierdzenie Stone'a), więc da się ją "
4303 "wyprowadzić z H1–H8 (twierdzenie Birkhoffa o pełności "
4304 "logiki równościowej).",
4305 " An equation true in {0, 1} holds in every Boolean "
4306 "algebra (Stone's theorem), so it can be derived from "
4307 "H1–H8 (Birkhoff's completeness theorem for equational "
4308 "logic)."), "dim"))
4309 else:
4310 vals = ", ".join(f"{k} = {v}" for k, v in cex.items())
4311 w.add(("✗ ", "error"), (show_equation((l, r)), "goal"), (t(
4312 f" fałszywa dla {vals}: lewa {value(l, cex)}, prawa "
4313 f"{value(r, cex)}",
4314 f" false for {vals}: left {value(l, cex)}, right "
4315 f"{value(r, cex)}"), "error"))
4316 return w
4317
4318 def theory_model(self, rest):
4319 """bl model in another theory: the equation in every finite model
4320 of the theory (also in those where some axiom fails)."""
4321 t = self.tr
4322 try:
4323 l, r = self.parse_equation(rest)
4324 self.kernel.term(l), self.kernel.term(r)
4325 except (SyntaxError, ValueError, IndexError, ProofError):
4326 return self.error(t(f"użycie: bl model równość — zapis: "
4327 f"{self.notation_text()}",
4328 f"usage: bl model equation — notation: "
4329 f"{self.notation_text()}"))
4330 names = theories.variables_of(r, theories.variables_of(l))
4331 if len(names) > 6:
4332 return self.error(t("za dużo zmiennych (najwyżej 6)",
4333 "too many variables (at most 6)"))
4334 w = Output()
4335 w.add((show_equation((l, r)), "goal"))
4336 for model, bad in theories.models(self.theory):
4337 v = theories.counterexample(l, r, model, names)
4338 role = t("model aksjomatów", "a model of the axioms") if not bad \
4339 else t(f"nie spełnia {', '.join(bad)}",
4340 f"fails {', '.join(bad)}")
4341 if v is None:
4342 w.add((" ✓ ", "ok"), (self.model_text(model), "code"),
4343 (t(f" — {role}: zachodzi", f" — {role}: holds"), "ok"))
4344 else:
4345 vals = ", ".join(f"{k} = {x}" for k, x in v.items())
4346 w.add((" ✗ ", "error"), (self.model_text(model), "code"),
4347 (t(f" — {role}: fałsz dla {vals}: lewa "
4348 f"{theories.value(l, model, v)}, prawa "
4349 f"{theories.value(r, model, v)}",
4350 f" — {role}: false for {vals}: left "
4351 f"{theories.value(l, model, v)}, right "
4352 f"{theories.value(r, model, v)}"), "error"))
4353 w.add((t(" Fałsz w modelu aksjomatów = brak dowodu (twierdzenie "
4354 "o poprawności). Prawda we wszystkich tych modelach jeszcze "
4355 "niczego nie dowodzi.",
4356 " False in a model of the axioms = no proof (the soundness "
4357 "theorem). True in all these models proves nothing yet."),
4358 "dim"))
4359 return w
4360
4361 def p_tactic(self, rest=""):
4362 t = self.tr
4363 rest = rest.strip()
4364 if ":=" in rest:
4365 name, _, body = rest.partition(":=")
4366 return self.define_tactic(name.strip(), body.strip())
4367 words = rest.split()
4368 if len(words) == 2 and words[0] == "forget":
4369 return self.forget_tactic(words[1])
4370 if rest in self.tactics:
4371 return self.describe_tactic(rest)
4372 cards = {
4373 "rw": (
4374 "rw [r₁, …, rₖ] — przepisywanie (w Leanie: rw)",
4375 "rw [r₁, …, rₖ] — rewriting (in Lean: rw)",
4376 ["r to H6, ← H6 albo H2 n(x) y: fakt, kierunek i "
4377 "argumenty (złożone w nawiasach: ← H6 (x + x)).",
4378 "Każda reguła szuka pierwszego dopasowania wzorca: najpierw "
4379 "lewa strona celu, potem prawa, od korzenia w głąb. To "
4380 "dopasowanie ustala instancję; rw zamienia WSZYSTKIE jej "
4381 "wystąpienia. Na końcu rw próbuje rfl.",
4382 "Wzorzec będący samą zmienną (← H6) pasowałby wszędzie — "
4383 "Lean go odrzuca, więc trzeba podać argument.",
4384 "Jądro dostaje z każdej reguły: Inst (fakt dla argumentów), "
4385 "CongrArg (kontekst z dziurą), Symm, Trans."],
4386 ["r is H6, ← H6 or H2 n(x) y: a fact, a direction and "
4387 "arguments (compound ones in parentheses: ← H6 (x + x)).",
4388 "Each rule looks for the first match of its pattern: the "
4389 "left side of the goal first, then the right side, from the "
4390 "root down. That match fixes the instance; rw replaces ALL "
4391 "its occurrences. At the end rw tries rfl.",
4392 "A pattern that is a bare variable (← H6) would match "
4393 "anywhere — Lean rejects it, so give an argument.",
4394 "From each rule the kernel gets: Inst (the fact for the "
4395 "arguments), CongrArg (a context with a hole), Symm, "
4396 "Trans."],
4397 "bl prove x + x = x\nrw [← H6 (x + x), ← H7 x, ← H3, H8, "
4398 "H5]\nqed"),
4399 "nth_rw": (
4400 "nth_rw k [h] — przepisz tylko k-te dopasowanie",
4401 "nth_rw k [h] — rewrite only the k-th match",
4402 ["Dopasowania liczymy od 1, w tej samej kolejności co rw "
4403 "(także zagnieżdżone). W Leanie 4 bez Mathliba: "
4404 "rw (occs := .pos [k]) [h]."],
4405 ["Matches are counted from 1, in the same order as rw "
4406 "(nested ones too). In Lean 4 without Mathlib: "
4407 "rw (occs := .pos [k]) [h]."],
4408 "bl prove x * y = y * x\nnth_rw 2 [H2]"),
4409 "rfl": (
4410 "rfl — zamyka cel t = t", "rfl — closes a goal t = t",
4411 ["Jądro: Refl(t)."], ["Kernel: Refl(t)."], ""),
4412 "symm": (
4413 "symm — zamienia strony celu", "symm — swaps the sides",
4414 ["Cel a = b zamienia się w b = a. Jądro: Symm."],
4415 ["The goal a = b becomes b = a. Kernel: Symm."],
4416 "bl prove x = x + 0\nsymm\nrw [H5]"),
4417 "trans": (
4418 "trans t — rozbija a = b na a = t i t = b",
4419 "trans t — splits a = b into a = t and t = b",
4420 ["Dwa cele, najpierw a = t. Jądro: Trans. W Leanie 4 bez "
4421 "Mathliba: refine Eq.trans (b := t) ?_ ?_."],
4422 ["Two goals, a = t first. Kernel: Trans. In Lean 4 without "
4423 "Mathlib: refine Eq.trans (b := t) ?_ ?_."],
4424 "bl prove x + x = x\ntrans (x + x) * 1"),
4425 "exact": (
4426 "exact h args — cel jest instancją faktu h",
4427 "exact h args — the goal is an instance of the fact h",
4428 ["Brakujące argumenty dopasuje laboratorium; skrypt "
4429 "zapisuje wszystkie (Lean ich wymaga). Jądro: Inst."],
4430 ["The lab fills in missing arguments; the script records "
4431 "all of them (Lean needs them). Kernel: Inst."],
4432 "bl prove y + x = x + y\nexact H1"),
4433 "auto": (
4434 "auto [budżet] [[h, …]] — solver",
4435 "auto [budget] [[h, …]] — solver",
4436 ["Ten sam solver co w podpowiedziach (solver.py) bierze "
4437 "najkrótszy dowód z kilku strategii: przeszukiwanie wszerz "
4438 "z obu stron celu (jak taktyki.szukaj z wykładu), dowód "
4439 "twierdzenia z biblioteki (w ćwiczeniu rozwinięty do "
4440 "dozwolonych faktów) i postać normalna — obie strony stają "
4441 "się sumą mintermów, więc auto dowodzi każdej prawdziwej "
4442 "równości. Fałszywą rozpoznaje po kontrprzykładzie "
4443 "w {0, 1}.",
4444 "Dowód trafia do skryptu jako jawne rw / nth_rw, więc "
4445 "script i bl lean pokazują zwykłe kroki. Budżet: liczba "
4446 "termów przeszukiwania wszerz (domyślnie 30 000); "
4447 "z listą faktów w nawiasach auto tylko przeszukuje wszerz "
4448 "tymi faktami. Długie szukanie przerywa przycisk Stop."],
4449 ["The same solver as in the hints (solver.py) takes the "
4450 "shortest proof from several strategies: breadth-first "
4451 "search from both sides of the goal (like tactics.search "
4452 "from the lecture), the proof of a library theorem "
4453 "(expanded to the allowed facts in an exercise) and the "
4454 "normal form — both sides become a sum of minterms, so "
4455 "auto proves every true equation. It recognises a false "
4456 "one by a counterexample in {0, 1}.",
4457 "The proof goes into the script as explicit rw / nth_rw "
4458 "lines, so script and bl lean show ordinary steps. "
4459 "Budget: the number of terms of the breadth-first search "
4460 "(30,000 by default); with a list of facts in brackets "
4461 "auto only searches breadth-first with those facts. The "
4462 "Stop button interrupts a long search."],
4463 "bl prove x + x * y = x\nauto"),
4464 }
4465 basic = list(cards)
4466 cards.update(TACTICAL_CARDS)
4467 w = Output()
4468 if rest not in cards:
4469 return self.tactic_list(basic)
4470 title_pl, title_en, paras_pl, paras_en, example = cards[rest]
4471 w.add((t(title_pl, title_en), "heading"))
4472 for paragraph in (paras_pl if self.lang == "pl" else paras_en):
4473 w.add((" " + paragraph, ""))
4474 if example:
4475 w.add((t(" przykład:", " example:"), "dim"))
4476 for line in example.split("\n"):
4477 w.add((" ", ""), (line, "code", {"insert": line}))
4478 return w
4479
4480 def tactic_list(self, basic):
4481 t = self.tr
4482 w = Output()
4483
4484 def links(names):
4485 pieces = []
4486 for i, k in enumerate(names):
4487 if i:
4488 pieces.append((" · ", "dim"))
4489 pieces.append((k, "code", {"run": f"bl tactic {k}"}))
4490 return pieces
4491 w.add((t("Taktyki podstawowe (bl tactic nazwa)",
4492 "Basic tactics (bl tactic name)"), "heading"))
4493 w.add((" ", ""), *links(basic))
4494 w.add((t("Taktyki z taktyk — tacticals (bl tactic nazwa)",
4495 "Tactics from tactics — tacticals (bl tactic name)"),
4496 "heading"))
4497 w.add((" ", ""), *links([k for k in TACTICAL_CARDS
4498 if k != "design"]))
4499 w.add((" ", ""), ("bl tactic design", "code",
4500 {"run": "bl tactic design"}),
4501 (t(" — jak projektować dobre taktyki",
4502 " — how to design good tactics"), "dim"))
4503 own = [n for n, i in self.tactics.items() if not i.get("example")]
4504 examples = [n for n, i in self.tactics.items() if i.get("example")]
4505 if own:
4506 w.add((t("Twoje taktyki", "Your tactics"), "heading"))
4507 for n in own:
4508 w.add((" ", ""), (n, "name", {"run": f"bl tactic {n}"}),
4509 " := ", (self.tactics[n]["text"], "code"))
4510 if examples and self.theory is None:
4511 w.add((t("Przykłady — dobre (✓) i złe (✗)",
4512 "Examples — good (✓) and bad (✗)"), "heading"))
4513 for n in examples:
4514 info = self.tactics[n]
4515 w.add((" ", ""), ("✓ " if info["good"] else "✗ ",
4516 "ok" if info["good"] else "error"),
4517 (n.ljust(22), "name", {"run": f"bl tactic {n}"}),
4518 (info["description"], "dim"))
4519 w.add((t(" Własna taktyka: bl tactic nazwa := taktyka · próba: "
4520 "bl trace taktyka · usunięcie: bl tactic forget nazwa · "
4521 "warsztat taktyk: przycisk pod terminalem",
4522 " Your own tactic: bl tactic name := tactic · dry run: "
4523 "bl trace tactic · deleting: bl tactic forget name · the "
4524 "tactic workshop: the button below the terminal"), "dim"))
4525 return w
4526
4527 def p_kernel(self, *_):
4528 t = self.tr
4529 w = Output()
4530 w.add((t("Jądro (kernel.py) — jedyny kod, któremu trzeba ufać",
4531 "The kernel (kernel.py) — the only code you must trust"),
4532 "heading"))
4533 try:
4534 with open(__file__.replace("lab.py", "kernel.py"),
4535 encoding="utf-8") as f:
4536 n_lines = sum(1 for _ in f)
4537 except OSError:
4538 n_lines = None
4539 if n_lines:
4540 w.add((t(f" kernel.py: {self.counted(n_lines, 'line')}; "
4541 "reguły: ",
4542 f" kernel.py: {self.counted(n_lines, 'line')}; "
4543 "rules: "),
4544 "dim"), ("Refl, Symm, Trans, CongrArg, Inst", "code"))
4545 w.add((t(" Taktyki, podpowiedzi i solver tylko budują drzewo z tych "
4546 "reguł. qed oddaje je jądru razem z pierwotną tezą: "
4547 "Jadro.twierdzenie liczy, co drzewo dowodzi, i dopisuje "
4548 "twierdzenie tylko wtedy, gdy to dokładnie teza.",
4549 " Tactics, suggestions and the solver only build a tree of "
4550 "these rules. qed hands it to the kernel with the original "
4551 "statement: Kernel.theorem computes what the tree proves "
4552 "and adds the theorem only if it is exactly the "
4553 "statement."), ""))
4554 w.add((t(" Trzy prawa: każde qed sprawdza jądro · nieudana taktyka "
4555 "nie zmienia stanu · jądro nie importuje niczego z "
4556 "laboratorium.",
4557 " Three laws: every qed is checked by the kernel · a "
4558 "failing tactic leaves the state unchanged · the kernel "
4559 "imports nothing from the lab."), "dim"))
4560 w.add((" ", ""), (t("kod jądra: ", "kernel code: "), "dim"),
4561 (self.base_url + "kernel.py", "code",
4562 {"href": self.base_url + "kernel.py.html"}), " · ",
4563 (self.base_url + "lab.py", "code",
4564 {"href": self.base_url + "lab.py.html"}))
4565 return w
4566
4567 def p_forget(self, rest):
4568 name = rest.strip()
4569 if name not in self.own:
4570 return self.error(self.tr(
4571 f"{name or '?'} nie jest Twoim twierdzeniem",
4572 f"{name or '?'} is not one of your theorems"))
4573 dependents = [n for n in self.own if n != name and
4574 name in used_facts(self.proofs[n])]
4575 if dependents:
4576 return self.error(self.tr(
4577 f"z {name} korzystają: {', '.join(dependents)} — usuń je "
4578 "najpierw",
4579 f"{name} is used by: {', '.join(dependents)} — delete them "
4580 "first"))
4581 w = Output().add((self.tr(f" usuwam {name} i uruchamiam jądro od "
4582 "nowa…",
4583 f" deleting {name} and restarting the "
4584 "kernel…"), "dim"))
4585 w.extras["forget"] = name
4586 return w
4587
4588 def p_lean(self, rest):
4589 parts = rest.split()
4590 if not parts:
4591 return self.error(self.tr("użycie: bl lean nazwa [full]",
4592 "usage: bl lean name [full]"))
4593 name = parts[0]
4594 full_file = len(parts) > 1 and parts[1] == "full"
4595 if name not in self.lib and name not in self.own:
4596 return self.error(self.tr(f"nie ma twierdzenia {name}",
4597 f"there is no theorem {name}"))
4598 if self.own[name].get("given") if name in self.own else False:
4599 return Output().add((self.tr(
4600 f" {name} to fakt dany: w Leanie jest polem klasy "
4601 f"{self.lean_class_name()} (bl lean z dowolnym twierdzeniem "
4602 "tej teorii i full pokazuje klasę)",
4603 f" {name} is a given fact: in Lean it is a field of the "
4604 f"class {self.lean_class_name()} (bl lean with any theorem "
4605 "of this theory and full shows the class)"), "dim"))
4606 w = Output()
4607 if full_file:
4608 text = self.lean_file(self.closure(name))
4609 else:
4610 assumed = [n for n in sorted(used_facts(self.proofs[name]),
4611 key=self.all_facts().index)
4612 if n not in self.axioms]
4613 header = [self.tr(
4614 "-- klasa AlgebraBoolea: lean/Wyklad03.lean; otwórz ją "
4615 "(open AlgebraBoolea)",
4616 "-- class HuntingtonAlgebra: lean/Lecture03.lean; open it "
4617 "(open HuntingtonAlgebra)") if self.theory is None else
4618 self.tr(f"-- klasa {self.lean_class_name()}: bl lean "
4619 f"{name} full (cały plik)",
4620 f"-- class {self.lean_class_name()}: bl lean {name} "
4621 "full (a whole file)"),
4622 f"-- variable {{α : Type}} [{self.lean_class_name()} α]"]
4623 if assumed:
4624 header.append(self.tr("-- korzysta z: ", "-- uses: ")
4625 + ", ".join(assumed))
4626 header += self.lean_macros([name])
4627 text = "\n".join(header) + "\n" + self.lean_theorem(name)
4628 for line in text.split("\n"):
4629 w.add((line, "lean"))
4630 if not full_file:
4631 w.add((self.tr(" cały plik do skompilowania: ",
4632 " a whole file ready to compile: "), "dim"),
4633 (f"bl lean {name} full", "code",
4634 {"run": f"bl lean {name} full"}))
4635 w.extras["lean"] = text
4636 return w
4637
4638 # -- Lean --
4639
4640 def lean_line(self, line):
4641 """A script line in Lean 4 (a comment -- … stays)."""
4642 tactic_text = self._lean_tactic(line)
4643 _, _, comment = line.partition("--")
4644 if comment and strip_comment(line):
4645 return f"{tactic_text} --{comment.rstrip()}"
4646 return tactic_text
4647
4648 def _lean_tactic(self, line):
4649 node = self.compound(line)
4650 if node is not None:
4651 return tc.show(node, lambda x: self._lean_basic(x, True))
4652 return self._lean_basic(line)
4653
4654 def _lean_basic(self, line, inside=False):
4655 """One basic tactic in Lean 4. exact gets _ for each argument it
4656 leaves out (Lean needs all of them; the lab finds them). A line
4657 this session cannot read (the notation of another theory) stays
4658 as it is."""
4659 try:
4660 tag, data = parse_line(line, self.notation)
4661 except TacticError:
4662 return line.strip()
4663 if tag == "nothing":
4664 return line.strip()
4665 if tag == "rw":
4666 which, rules = data
4667 rules_text = ", ".join(
4668 r.lean(lambda a: self.lean_term(a, 3)) for r in rules)
4669 if which:
4670 return f"rw (occs := .pos [{which}]) [{rules_text}]"
4671 return f"rw [{rules_text}]"
4672 if tag in ("rfl", "symm"):
4673 return tag
4674 if tag == "ac_rfl":
4675 # Lean's ac_rfl does not look under n(...): a macro of the class
4676 # file repeats ac_nf (theories.lean_class)
4677 return "ac_rfl_deep"
4678 if tag in ("rw_ac", "ac_simp") or (tag == "auto" and
4679 self.theory is not None):
4680 raise NotInLean(line)
4681 if tag == "exact":
4682 text = data.lean(lambda a: self.lean_term(a, 3))
4683 fact = self.kernel.facts.get(data.name)
4684 missing = len(fact[0]) - len(data.args) if fact else 0
4685 return f"exact {text}" + " _" * max(missing, 0)
4686 if tag == "trans":
4687 return (f"refine Eq.trans (b := ({self.lean_term(data)} : α)) "
4688 "?_ ?_")
4689 raise ValueError(line)
4690
4691 def lean_theorem(self, name):
4692 info = self.lib.get(name) or self.own[name]
4693 l, r = info["statement"]
4694 vs = info["variables"]
4695 if vs:
4696 statement = f"({' '.join(vs)} : α) : " \
4697 f"{self.lean_term(l)} = {self.lean_term(r)}"
4698 else:
4699 statement = f": ({self.lean_term(l)} : α) = {self.lean_term(r)}"
4700 lines = [f"-- {info['short']}"] if info.get("short") else []
4701 try:
4702 body = [" " + self.lean_line(x) for x in info["script"]]
4703 except NotInLean: # rw_ac, ac_simp, auto: the kernel's proof
4704 lines += [self.tr(
4705 "-- taktyki modulo AC nie mają odpowiednika w Leanie: "
4706 "dowód jądra jako term",
4707 "-- the tactics modulo AC have no Lean counterpart: the "
4708 "kernel's proof as a term"),
4709 f"theorem {name} {statement} :=",
4710 " " + lean_proof_term(self.proofs[name])]
4711 return "\n".join(lines)
4712 lines += [f"theorem {name} {statement} := by"] + body
4713 return "\n".join(lines)
4714
4715 def closure(self, name):
4716 """The theorems needed for the proof of `name` (in order)."""
4717 needed, stack = set(), [name]
4718 while stack:
4719 n = stack.pop()
4720 if n in needed or n in self.axioms:
4721 continue
4722 needed.add(n)
4723 stack.extend(used_facts(self.proofs[n]))
4724 return [n for n in self.all_facts() if n in needed]
4725
4726 def lean_file(self, names, header=None):
4727 if header is None:
4728 header = self.tr(
4729 "/- Boole Lab: dowody z laboratorium w Leanie 4 (bez "
4730 "Mathliba).\n Sprawdzenie: lean Plik.lean -/",
4731 "/- Boole Lab: proofs from the lab in Lean 4 (no Mathlib)."
4732 "\n Check: lean File.lean -/")
4733 cls = self.lean_class_name()
4734 parts = [header, "", self.lean_class_text().rstrip(), "",
4735 f"open {cls}", "", f"variable {{α : Type}} [{cls} α]", ""]
4736 parts += self.lean_macros(names)
4737 for n in names:
4738 if not self.own.get(n, {}).get("given"): # a class field
4739 parts += [self.lean_theorem(n), ""]
4740 return "\n".join(parts)
4741
4742 def lean_macros(self, names):
4743 """The user tactics that the proofs of `names` call, as Lean
4744 macros (each after those it calls), with a blank line after
4745 each."""
4746 scripts = []
4747 for n in names:
4748 info = self.lib.get(n) or self.own.get(n)
4749 if info:
4750 scripts += info["script"]
4751 result = []
4752 for c in self.tactics_called(self.script_nodes(scripts)):
4753 result += [self.lean_macro_text(c, self.tactics[c]["node"]), ""]
4754 return result
4755
4756 # -- the browser interface (JSON) --
4757
4758 def replay_own(self, entries):
4759 """Replays the user's theorems (localStorage) through the kernel.
4760 Entries saved by the first version of the page have Polish keys
4761 (LEGACY_KEYS)."""
4762 accepted, rejected = [], []
4763 for entry in entries:
4764 try:
4765 entry = {LEGACY_KEYS.get(k, k): v for k, v in entry.items()}
4766 name, text = entry["name"], entry["equation"]
4767 script = list(entry["script"])
4768 except (AttributeError, KeyError, TypeError):
4769 continue
4770 self.drop_example(name)
4771 old = self.proof
4772 self._replaying = True
4773 try:
4774 result = self.run(f"bl prove {name} : {text}")
4775 finally:
4776 self._replaying = False
4777 ok = not result.error
4778 if ok:
4779 for line in script:
4780 if self.run(line).error:
4781 ok = False
4782 break
4783 if ok:
4784 ok = not self.p_qed().error
4785 (accepted if ok else rejected).append(name)
4786 self.proof = old
4787 self.last = None
4788 return accepted, rejected
4789
4790 def library_json(self):
4791 sections = []
4792 for name in self.order:
4793 info = self.lib[name]
4794 s = info["section"]
4795 if not sections or sections[-1]["source"] is not s:
4796 sections.append({"source": s, "title": s["title"],
4797 "theorems": []})
4798 sections[-1]["theorems"].append(self._thm_json(name, info))
4799 result = [{"title": s["title"], "theorems": s["theorems"]}
4800 for s in sections]
4801 if self.own:
4802 result.append({"title": self.tr("Twoje twierdzenia",
4803 "Your theorems"),
4804 "own": True,
4805 "theorems": [self._thm_json(n, i) for n, i in
4806 self.own.items()]})
4807 lib = {"axioms": [{"name": n, "text": self.fact_text(n)}
4808 for n in self.axioms],
4809 "sections": result}
4810 if self.theory is not None: # bl theory: its name and challenges
4811 lib["theory"] = self.theory_name(self.theory)
4812 lib["challenges"] = self.challenges_json()
4813 lib["tactics"] = [
4814 {"name": n, "text": i["text"], "example": i["example"],
4815 "good": i.get("good"), "description": i.get("description", ""),
4816 "doc": i.get("doc", "")}
4817 for n, i in self.tactics.items()
4818 if not (i["example"] and self.theory is not None)]
4819 return lib
4820
4821 def challenges_json(self):
4822 """The equations to try in the current theory (as on its card):
4823 the text and the model in which it fails ("" if none does)."""
4824 entries = []
4825 steps = {} # a Robbins theory: the next steps
4826 robbins = "ac" in theories.THEORIES[self.theory]
4827 for key, stage, step in (rl.steps_of(self.theory) if robbins
4828 else ()):
4829 if step["name"] not in self.kernel.facts and \
4830 len(steps.setdefault(key, [])) < 3:
4831 steps[key].append({
4832 "text": step["name"], "false_in": "",
4833 "note": self.tr(step["source_pl"], step["source_en"])})
4834 for found in steps.values():
4835 entries += found
4836 for text in theories.THEORIES[self.theory]["challenges"]:
4837 l, r = self.parse_equation(text)
4838 found = self.model_cex(l, r)
4839 entries.append({"text": show_equation((l, r)),
4840 "false_in": found[0] if found else ""})
4841 return entries
4842
4843 def _thm_json(self, name, info):
4844 """A theorem for the interface; "id" is its English name (the same
4845 on both pages; for the user's theorems: the name)."""
4846 return {"name": name, "id": info.get("id", name),
4847 "text": show_equation(info["statement"]),
4848 "short": info.get("short") or "",
4849 "steps": info["steps"],
4850 "description": info.get("description") or "",
4851 "assumptions": sorted(self.kernel.assumptions[name],
4852 key=lambda a: self.axioms.index(a))}
4853
4854 def state(self):
4855 d = self.proof
4856 if d is None:
4857 return {"proof": None}
4858 goals = []
4859 for i, (_, c) in enumerate(d.goals):
4860 entry = {"text": show_equation(c)}
4861 if i == 0:
4862 entry["tree"] = [tree(c[0], "0"), tree(c[1], "1")]
4863 goals.append(entry)
4864 suggested, facts = [], {}
4865 if d.goals:
4866 suggested, facts = self.suggestions(d, d.goals[0][1])
4867 suggested, facts = self.mark_reverting(
4868 d.goals[0][1], suggested, d.seen, facts)
4869 else:
4870 suggested = [{"tactic": "qed", "kind": "closes", "rule": "",
4871 "fact": "", "result": "", "paths": [],
4872 "source": "tactic", "nargs": 0, "size_after": 0,
4873 "index": -1}]
4874 too_big = bool(d.goals) and term_size(d.goals[0][1][0]) + \
4875 term_size(d.goals[0][1][1]) > MAX_HINT_SIZE
4876 return {"too_big": too_big,
4877 "proof": {"name": d.name,
4878 "statement": show_equation(d.statement),
4879 "exercise": d.exercise,
4880 "command": d.command,
4881 "script": list(d.script),
4882 "available": list(d.available)},
4883 "goals": goals, "suggestions": suggested[:60], "facts": facts}
4884
4885 @staticmethod
4886 def mark_reverting(goal, suggested, seen, facts=None):
4887 """A step that takes a side of the goal back to an earlier form
4888 (the left one to an earlier left side, the right one to an earlier
4889 right side) goes to the end of the list — otherwise suggestions
4890 could go round in circles. Returns (suggestions, facts) with the
4891 field "reverts"."""
4892 L, R = map(show, goal)
4893 lefts = {show(c[0]) for c in seen}
4894 rights = {show(c[1]) for c in seen}
4895
4896 def mark(p):
4897 reverts = False
4898 if p["result"]:
4899 l2, r2 = p["result"].split(" = ")
4900 reverts = (l2 != L and l2 in lefts) or \
4901 (r2 != R and r2 in rights)
4902 return dict(p, reverts=reverts)
4903 result = sorted(map(mark, suggested), key=lambda p: p["reverts"])
4904 facts = {n: {k: mark(p) for k, p in info.items()}
4905 for n, info in (facts or {}).items()}
4906 return result, facts
4907
4908 def json_run(self, line):
4909 t0 = time.perf_counter()
4910 before = (self.theory, tuple(self.own))
4911 try:
4912 result = self.run(line)
4913 except RecursionError:
4914 result = self.error(self.tr("za głęboka rekursja",
4915 "recursion too deep"))
4916 reply = {"lines": result.rows, "error": result.error,
4917 "state": self.state(), "time": time.perf_counter() - t0}
4918 reply.update(result.extras)
4919 # the page redraws its library after a new theorem and after
4920 # bl theory (other axioms, no library, the theory's challenges)
4921 if "new" in result.extras or "tactic_new" in result.extras or \
4922 "tactic_forget" in result.extras or \
4923 (self.theory, tuple(self.own)) != before:
4924 reply["library"] = self.library_json()
4925 return json.dumps(reply, ensure_ascii=False)
4926
4927 def json_preview(self, line):
4928 """The goal after the leading rules of the line being typed."""
4929 d = self.proof
4930 if d is None or not d.goals:
4931 return json.dumps({"goal": None})
4932 m = re.fullmatch(r"\s*(rw|nth_rw\s+(\d+))\s*\[(.*)", line)
4933 if not m:
4934 return json.dumps({"goal": None})
4935 which = int(m.group(2)) if m.group(2) else None
4936 parts = split_top(m.group(3), ",")[:-1]
4937 goal = d.goals[0][1]
4938 seen = list(d.seen)
4939 try:
4940 for c in parts:
4941 rule = parse_rule(c, self.notation)
4942 self.check_rule(d, rule)
4943 seen.append(goal)
4944 goal, _ = rewrite(self.kernel, goal, rule, which)
4945 except (TacticError, ProofError) as e:
4946 return json.dumps({"goal": None, "error": self.error_text(e)},
4947 ensure_ascii=False)
4948 suggested, facts = self.suggestions(d, goal)
4949 suggested, facts = self.mark_reverting(goal, suggested, seen, facts)
4950 return json.dumps({"goal": show_equation(goal),
4951 "tree": [tree(goal[0], "0"),
4952 tree(goal[1], "1")],
4953 "suggestions": suggested[:60], "facts": facts,
4954 "rules": len(parts)}, ensure_ascii=False)
4955
4956 def json_solver(self, seconds=0.4):
4957 d = self.proof
4958 if d is None or not d.goals:
4959 return json.dumps({"suggestion": None})
4960 goal = d.goals[0][1]
4961 found = self.model_cex(*goal) if self.theory is not None else None
4962 if found is not None:
4963 return json.dumps({"suggestion": None, "goal": show_equation(goal),
4964 "falsity": self.theory_falsity_text(
4965 goal, found, bool(d.history))},
4966 ensure_ascii=False)
4967 cex = counterexample(*goal) if self.theory is None else None
4968 if cex is not None:
4969 return json.dumps({"suggestion": None, "goal": show_equation(goal),
4970 "falsity": self.falsity_text(goal, cex,
4971 bool(d.history))},
4972 ensure_ascii=False)
4973 entries, _ = self.suggestions(d, goal)
4974 if entries and entries[0]["kind"] == "closes":
4975 return json.dumps({"suggestion": None,
4976 "goal": show_equation(goal)})
4977 p, visited = self.solver_suggestion(d, goal, seconds=seconds)
4978 if p is not None:
4979 p["description"] = self.method_text(p)
4980 return json.dumps({"suggestion": p, "visited": visited,
4981 "goal": show_equation(goal)}, ensure_ascii=False)
4982
4983 def json_start(self, own_json="[]", tactics_json="[]"):
4984 try:
4985 entries = json.loads(own_json)
4986 except ValueError:
4987 entries = []
4988 try:
4989 saved_tactics = json.loads(tactics_json)
4990 except ValueError:
4991 saved_tactics = []
4992 t0 = time.perf_counter()
4993 tactics_ok, tactics_bad = self.load_tactics(saved_tactics)
4994 accepted, rejected = self.replay_own(
4995 entries if isinstance(entries, list) else [])
4996 own_time = time.perf_counter() - t0
4997 return json.dumps({
4998 "library": self.library_json(),
4999 "count": len(self.order),
5000 "errors": self.library_errors,
5001 "time": self.library_time,
5002 "own": accepted, "rejected": rejected,
5003 "own_time": own_time,
5004 "tactics": tactics_ok, "tactics_rejected": tactics_bad,
5005 "banner": self.banner(accepted, rejected, tactics_ok,
5006 tactics_bad).rows,
5007 "state": self.state()}, ensure_ascii=False)
5008
5009 def banner(self, accepted=(), rejected=(), tactics_ok=(),
5010 tactics_bad=()):
5011 t = self.tr
5012 seconds = self.fmt_seconds(self.library_time)
5013 example = f"bl prove {self.names['add_idem']}"
5014 w = Output()
5015 w.add(("Boole Lab", "heading"), (t(
5016 " — algebra Boole'a w jądrze z wykładu 3",
5017 " — Boolean algebra in the kernel of Lecture 3"), "dim"))
5018 w.add((f"Python {sys.version.split()[0]}", "dim"),
5019 (t(" · aksjomaty Huntingtona H1–H8 · biblioteka: ",
5020 " · Huntington's axioms H1–H8 · library: "), "dim"),
5021 (self.counted(len(self.order), "theorem"), "ok"),
5022 (t(f" przyjętych przez jądro ({seconds})",
5023 f" accepted by the kernel ({seconds})"), "dim"))
5024 if self.library_errors:
5025 for name, desc in self.library_errors:
5026 w.add(("✗ ", "error"), (f"{name}: {desc}", "error"))
5027 if accepted:
5028 w.add((t(f"Twoje twierdzenia: {len(accepted)} — odtworzone i "
5029 "ponownie sprawdzone przez jądro",
5030 f"Your theorems: {len(accepted)} — replayed and checked "
5031 "again by the kernel"), "ok"))
5032 if rejected:
5033 w.add((t("Nie przeszły ponownego sprawdzenia: ",
5034 "Failed the new check: ") + ", ".join(rejected),
5035 "warning"))
5036 if tactics_ok:
5037 w.add((t(f"Twoje taktyki: {', '.join(tactics_ok)}",
5038 f"Your tactics: {', '.join(tactics_ok)}"), "ok"))
5039 if tactics_bad:
5040 w.add((t("Taktyki odrzucone przy starcie: ",
5041 "Tactics rejected at the start: ")
5042 + ", ".join(tactics_bad), "warning"))
5043 w.add((t("Wpisz ", "Type "), "dim"), ("bl help", "code",
5044 {"run": "bl help"}),
5045 (t(" albo zacznij od ", " or start with "), "dim"),
5046 (example, "code", {"run": example}),
5047 (t(". TAB albo → przyjmuje podpowiedź.",
5048 ". TAB or → accepts the suggestion."), "dim"))
5049 return w
5050
5051
5052# --- terminal ----------------------------------------------------------------
5053
5054def main(argv):
5055 lang = "pl" if "--pl" in argv else "en"
5056 commands = [argv[i + 1] for i, a in enumerate(argv[:-1]) if a == "-c"]
5057 session = Session(lang)
5058 print(session.banner().text())
5059 if commands:
5060 for p in commands:
5061 print(f"bl> {p}")
5062 result = session.run(p)
5063 print(result.text())
5064 if result.error:
5065 return 1
5066 return 0
5067 while True:
5068 try:
5069 line = input("bl> ")
5070 except EOFError:
5071 return 0
5072 if line.strip() in ("exit", "quit"):
5073 return 0
5074 try:
5075 print(session.run(line).text())
5076 except RecursionError:
5077 print("✗ recursion too deep")
5078
5079
5080if __name__ == "__main__":
5081 sys.exit(main(sys.argv[1:]))