"""Boole Lab: interactive proofs in Boolean algebra (lecture 3). The driver of the lab (in the browser and in the terminal), modelled on Peano Lab: the proof state, tactics written as in Lean 4, suggestions, a solver (its strategies are in solver.py: a proof of every true equation) and the export to Lean. All of this lies OUTSIDE the kernel. Tactics build a tree of the rules Refl, Symm, Trans, CongrArg and Inst, and qed hands it to the kernel (kernel.py) together with the ORIGINAL statement. Three laws: 1. every qed is checked by the kernel (Kernel.theorem) against the original statement; 2. a failing tactic leaves the proof state unchanged; 3. the kernel imports nothing from the tactics or the lab. The semantics of rw is that of Lean (kabstract): the first match of the pattern in prefix order (the left side of the goal first, then the right one) fixes the instance, and ALL its occurrences are rewritten; at the end rw tries rfl. That is why the scripts carry over to Lean unchanged (scripts/lean_biblioteka.py checks this with the compiler). The code is English; the messages are in two languages. The library (library.py) gives every theorem an English and a Polish name: a session in English uses the English names, a session in Polish ("pl") registers the theorems under their Polish names, with Polish descriptions and with the scripts translated (theorem names and library.COMMENTS_PL). In the terminal: python3 lab.py [--pl] [-c command ...] """ import difflib import importlib import json import os import re import sys import time import urllib.parse from collections import deque from dataclasses import dataclass from itertools import product import boolean import library import solver as sv import tactics as tac import theories from kernel import (CongrArg, Inst, Kernel, ProofError, Refl, Symm, Trans, subst, used_facts) from syntax import show, show_equation, show_lean, size from syntax import term as core_term TacticError = tac.TacticError def _import_or_fetch(name): """import name — and in the browser, if an old copy of the page's worker (kept in the browser's cache) did not fetch this newer module of the lab, fetch it from the same server first (the worker lives in applets/js/, the code in kernel/). On a computer the module is simply next to lab.py; the browser's modules js and pyodide exist only there, hence the imports by name.""" try: return importlib.import_module(name) except ImportError: if sys.platform != "emscripten": raise where = importlib.import_module("js").location.href url = urllib.parse.urljoin(str(where), f"../../kernel/{name}.py") source = importlib.import_module("pyodide.http").open_url(url).read() here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, name + ".py"), "w", encoding="utf-8") as f: f.write(source) importlib.invalidate_caches() return importlib.import_module(name) tc = _import_or_fetch("tacticals") _ENGINE = {} def robbins_engine(): """The modules of the Robbins theories (ac, robbins, robbins_proof, robbins_lab), imported on first use from the directory of lab.py. The Polish notebooks of the book put the Polish lecture code (jadro/, which has its own ac.py and robbins.py) first on sys.path; their modules of those names are set aside for the import and put back.""" if not _ENGINE: here = os.path.dirname(os.path.abspath(__file__)) names = ("ac", "robbins", "robbins_proof", "robbins_lab") other = {n: sys.modules.pop(n) for n in names if n in sys.modules and os.path.dirname(os.path.abspath( getattr(sys.modules[n], "__file__", None) or "")) != here} sys.path.insert(0, here) try: for n in names: _ENGINE[n] = _import_or_fetch(n) finally: sys.path.remove(here) sys.modules.update(other) return _ENGINE class _Engine: """A module of robbins_engine(), imported when first used.""" def __init__(self, name): self.name = name def __getattr__(self, attribute): return getattr(robbins_engine()[self.name], attribute) acm = _Engine("ac") # the tactic ac_rfl (A1, A2) rb = _Engine("robbins") # rw_ac, ac_simp, auto modulo AC rl = _Engine("robbins_lab") # the variants of the proof VARIABLE = re.compile(r"[A-Za-z][0-9]*") # a letter and a number: x, a1 NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") FORBIDDEN = set("""at by do fun have show from then else if let in with match end open theorem lemma def example where calc rfl symm trans exact rw nth_rw sorry variable class instance namespace section import true false True False Type Prop Sort this refine auto n bl qed undo restart abort script hint clear help AlgebraBoolea HuntingtonAlgebra Eq first try repeat iterate all_goals any_goals skip done fail macro tactic syntax set_option""".split()) # tactics of core Lean 4 (and common Mathlib ones): a tactic of the user # becomes a Lean macro, so its name must not be one of them LEAN_TACTICS = set("""simp simp_all simpa dsimp ring ring_nf omega decide norm_num linarith nlinarith positivity aesop tauto apply intro intros cases rcases obtain induction constructor exists use refine refine' exfalso contradiction assumption trivial unfold change subst split by_cases injection rename_i specialize generalize revert clear congr ext funext nth_rewrite rewrite erw rwa sleep stop checkpoint save trace guard_target guard_hyp conv exacts left right focus case next calc have show let sorry admit apply_rules solve_by_elim field_simp abel group push_neg contrapose by_contra rintro choose lift set existsi all any rfl' symm_saturate with_reducible unhygienic""".split()) TACTIC_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]{1,29}") # words reserved since the tacticals (2026-12-03): a theorem saved earlier # under such a name is still replayed LEGACY_NAMES = set("""first try repeat iterate all_goals any_goals skip done fail macro tactic syntax set_option""".split()) # not names of user tactics: the lab reads these words itself LAB_WORDS = {"cls", "design", "forget", "check", "trace"} KINDS = ("closes", "shrinks", "same", "grows") MAX_STATEMENT = 150 # nodes in the statement of bl prove MAX_HINT_SIZE = 220 # a larger goal: no suggestions (the UI stays fast) # The Lean class of the axioms: lean/Lecture03.lean (English) and # lean/Wyklad03.lean (Polish); scripts/lean_biblioteka.py checks that both # files hold the same text as LEAN_CLASS. LEAN_CLASS_NAME = {"en": "HuntingtonAlgebra", "pl": "AlgebraBoolea"} _LEAN_FIELDS = """\ n : α → α H1 : ∀ x y : α, x + y = y + x H2 : ∀ x y : α, x * y = y * x H3 : ∀ x y z : α, x + y * z = (x + y) * (x + z) H4 : ∀ x y z : α, x * (y + z) = x * y + x * z H5 : ∀ x : α, x + 0 = x H6 : ∀ x : α, x * 1 = x H7 : ∀ x : α, x + n x = 1 H8 : ∀ x : α, x * n x = 0 """ LEAN_CLASS = { lang: f"class {name} (α : Type) extends Add α, Mul α, Zero α, One α " f"where\n{_LEAN_FIELDS}" for lang, name in LEAN_CLASS_NAME.items()} # --- notation: abbreviations ------------------------------------------------- # Expanded by the parser: the kernel, the solver and Lean see +, *, n, 0, 1. ABBREVIATIONS = { "med": (("a", "b", "c"), "a * b + a * c + b * c"), # majority "xor": (("a", "b"), "a * n(b) + n(a) * b"), # symm. difference "ite": (("p", "a", "b"), "p * a + n(p) * b"), # if p then a… "nand": (("a", "b"), "n(a * b)"), # Sheffer stroke } _TEMPLATES = {k: (p, core_term(s)) for k, (p, s) in ABBREVIATIONS.items()} _TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_][A-Za-z0-9_]*)|(.))") def term(text, abbrevs=None, funcs=None): """A term in the notation of the lab: like syntax.term, plus calls f(a, b, …) — abbreviations (ABBREVIATIONS by default, expanded at once) and function symbols of a theory (funcs: name -> arity).""" abbrevs = _TEMPLATES if abbrevs is None else abbrevs funcs = funcs or {} toks = [m.group(1) or m.group(2) or m.group(3) for m in _TOKEN.finditer(text) if m.group(0).strip()] pos = 0 def peek(): return toks[pos] if pos < len(toks) else None def take(expected=None): nonlocal pos z = peek() if z is None or (expected and z != expected): raise SyntaxError(f"in {text!r}: expected " f"{expected or 'an expression'}, got {z!r}") pos += 1 return z def sum_term(): t = product_term() while peek() == "+": take() t = ("+", t, product_term()) return t def product_term(): t = atom() while peek() == "*": take() t = ("*", t, atom()) return t def atom(): z = take() if z == "(": t = sum_term() take(")") return t if z.isidentifier() and peek() == "(": take("(") args = [sum_term()] while peek() == ",": take() args.append(sum_term()) take(")") if z == "n" and len(args) == 1: return ("n", args[0]) if z in abbrevs and len(abbrevs[z][0]) == len(args): params, template = abbrevs[z] return subst(template, dict(zip(params, args))) if funcs.get(z) == len(args): return (z,) + tuple(args) raise SyntaxError(f"in {text!r}: unknown function {z}" f" with {len(args)} arguments") if z in ("0", "1") or (z.isidentifier() and z != "n"): return z raise SyntaxError(f"in {text!r}: unexpected character {z!r}") t = sum_term() if peek() is not None: raise SyntaxError(f"in {text!r}: unexpected {peek()!r} at " "the end") return t def equation(text, abbrevs=None, funcs=None): """'x + x = x' -> (('+', 'x', 'x'), 'x'); abbreviations as in term.""" left, right = text.split("=") return term(left, abbrevs, funcs), term(right, abbrevs, funcs) def has_abbreviations(text): return any(re.search(rf"\b{k}\s*\(", text) for k in ABBREVIATIONS) # --- terms ------------------------------------------------------------------- def term_size(t): """The number of nodes of a term: x has 1, x + n(y) has 4.""" return 1 if isinstance(t, str) else 1 + sum(map(term_size, t[1:])) def positions(t, path=()): """Pairs (path, subterm) in prefix order.""" yield path, t if not isinstance(t, str): for i, a in enumerate(t[1:], start=1): yield from positions(a, path + (i,)) def replace_at(t, path, u): """The term t with the subterm at the path replaced by u.""" if not path: return u i = path[0] return t[:i] + (replace_at(t[i], path[1:], u),) + t[i + 1:] def replace_all(t, u, v): """Every occurrence of u in t replaced by v (without going into u).""" if t == u: return v if isinstance(t, str): return t return (t[0],) + tuple(replace_all(a, u, v) for a in t[1:]) def occurrences(t, u, path=()): """Paths of the occurrences of u in t, in prefix order.""" if t == u: return [path] if isinstance(t, str): return [] result = [] for i, a in enumerate(t[1:], start=1): result += occurrences(a, u, path + (i,)) return result def leaves(t): if isinstance(t, str): return {t} return set().union(*map(leaves, t[1:])) def head(t): return t if isinstance(t, str) else t[0] def path_id(side, path): """The id of a subterm for the interface: '0.1.2' (0 left, 1 right).""" return ".".join(map(str, (side,) + tuple(path))) def tree(t, p="0", prec=0): """A term as a tree of pieces of text with the ids of subterms. The flattened text is exactly syntax.show(t).""" if isinstance(t, str): return {"p": p, "c": [t]} f = t[0] if f == "n": c = ["n(", tree(t[1], p + ".1", 0), ")"] elif f == "+": c = [tree(t[1], p + ".1", 0), " + ", tree(t[2], p + ".2", 1)] if prec >= 1: c = ["("] + c + [")"] elif f == "*": c = [tree(t[1], p + ".1", 1), " * ", tree(t[2], p + ".2", 2)] if prec >= 2: c = ["("] + c + [")"] else: # a function symbol of another theory c = [f + "("] for i, a in enumerate(t[1:], start=1): c += ([", "] if i > 1 else []) + [tree(a, f"{p}.{i}", 0)] c.append(")") return {"p": p, "c": c} def tree_text(d): return "".join(x if isinstance(x, str) else tree_text(x) for x in d["c"]) def equation_vars(l, r): return tuple(tac.variables(r, tac.variables(l))) def canonical(l, r): """The equation with renamed variables (v0, v1, …): a key for lookups.""" ren = {v: f"v{i}" for i, v in enumerate(equation_vars(l, r))} return subst(l, ren), subst(r, ren) def value(t, v): """The value of a term in the two-element Boolean algebra {0, 1}.""" if isinstance(t, str): return {"0": 0, "1": 1}.get(t, v.get(t)) a = [value(u, v) for u in t[1:]] if t[0] == "+": return a[0] | a[1] if t[0] == "*": return a[0] & a[1] return 1 - a[0] def counterexample(l, r): """A valuation in {0, 1} with l ≠ r (or None).""" vs = equation_vars(l, r) for vals in product((0, 1), repeat=len(vs)): v = dict(zip(vs, vals)) if value(l, v) != value(r, v): return v return None # --- rw rules ---------------------------------------------------------------- def split_top(text, sep): """Splits text at the separators `sep` outside parentheses.""" parts, depth, current = [], 0, "" for c in text: if c in "([": depth += 1 elif c in ")]": depth -= 1 if c == sep and depth == 0: parts.append(current) current = "" else: current += c parts.append(current) return parts def arg_text(t): """A rule argument in the course notation: compound ones in parentheses.""" s = show(t) return f"({s})" if not isinstance(t, str) and t[0] in "+*" else s @dataclass(frozen=True) class Rule: """An rw rule: a fact, a direction (←) and explicit (leading) arguments.""" name: str backward: bool = False args: tuple = () def text(self): s = " ".join([self.name] + [arg_text(a) for a in self.args]) return ("← " if self.backward else "") + s def lean(self, show_arg=None): show_arg = show_arg or (lambda a: show_lean(a, 3)) s = " ".join([self.name] + [show_arg(a) for a in self.args]) return ("← " if self.backward else "") + s def parse_rule(text, notation=None): """'← H6 (x + x)' -> Rule('H6', True, (('+', 'x', 'x'),)). notation: (abbreviations, function symbols) of another theory.""" text = " ".join(text.split()) backward = text.startswith(("←", "<-")) if backward: text = text[1 if text.startswith("←") else 2:].strip() parts = [c for c in split_top(text, " ") if c] if not parts or not NAME.fullmatch(parts[0]): raise TacticError(("rule", "rule", text)) args = [] for c in parts[1:]: try: args.append(term(c, *(notation or ()))) except (SyntaxError, ValueError, IndexError): raise TacticError(("argument", "argument", c)) from None return Rule(parts[0], backward, tuple(args)) def pattern(kernel, rule): """(free, pattern, replacement): fact variables not given as '?x'.""" vs, l, r = kernel.facts[rule.name] if len(rule.args) > len(vs): raise TacticError(("too_many_args", rule.name, len(vs))) if rule.backward: l, r = r, l s = dict(zip(vs, rule.args)) s.update({x: "?" + x for x in vs[len(rule.args):]}) free = tuple("?" + x for x in vs[len(rule.args):]) return free, subst(l, s), subst(r, s) def check_pattern(rule, free, pat): if pat in free: raise TacticError(("metavariable", rule, pat)) missing = [v for v in free if v not in leaves(pat)] if missing: raise TacticError(("undetermined", rule, pat, missing)) def find_match(kernel, goal, rule, which=None): """The match that rw [rule] (which=None) or nth_rw which picks: (side, path, instance u, replacement v, full arguments). As kabstract in Lean: prefix order, the left side of the goal first; nth_rw counts nested matches too.""" free, pat, repl = pattern(kernel, rule) check_pattern(rule, free, pat) counter = 0 for side, t in enumerate(goal): for path, u in positions(t): s = tac.match_pattern(pat, u, free, {}) if s is None: continue counter += 1 if which is None or counter == which: args = rule.args + tuple(s[x] for x in free) return side, path, subst(pat, s), subst(repl, s), args if which is not None and counter: raise TacticError(("no_such_match", rule, which, counter)) raise TacticError(("no_pattern", rule, pat, goal)) def rewrite(kernel, goal, rule, which=None): """One step of rw (which=None) or nth_rw (which=k), Lean's semantics. Returns (new goal, compose), where compose(q) turns a proof q of the new goal into a proof of the old one — from the kernel's rules (CongrArg, Inst, Symm, Trans).""" side, path, u, v, args = find_match(kernel, goal, rule, which) L, R = goal z = tac.fresh(L, R, u, v) if which is None: # every occurrence of u CL, CR = tac.abstract(L, u, z), tac.abstract(R, u, z) elif side == 0: # only the chosen occurrence CL, CR = replace_at(L, path, z), R else: CL, CR = L, replace_at(R, path, z) pe = Inst(rule.name, args) if rule.backward: pe = Symm(pe) new = (subst(CL, {z: v}), subst(CR, {z: v})) def compose(q): # L = L' (q: L' = R') R' = R return tac.trans(tac.congr(z, CL, pe), q, tac.symm(tac.congr(z, CR, pe))) return new, compose def balance(d, statement): """The same proof as a balanced tree: depth log n instead of n. A long script gives a chain Trans(step, Trans(step, …)) as deep as the number of steps — and the kernel checks a proof recursively. We flatten the chain (without recursion; Symm is pushed down to the pieces, since Symm(Trans(a, b)) proves the same as Trans(Symm(b), Symm(a)), and Refl is dropped) and compose it in pairs. The kernel checks the result like any other proof, so this rearrangement needs no trust.""" pieces, stack = [], [(d, False)] while stack: x, flipped = stack.pop() if isinstance(x, Trans): if flipped: stack += [(x.p, True), (x.q, True)] else: stack += [(x.q, False), (x.p, False)] elif isinstance(x, Symm): stack.append((x.p, not flipped)) elif not isinstance(x, Refl): pieces.append(Symm(x) if flipped else x) if not pieces: return Refl(statement[0]) while len(pieces) > 1: pieces = [Trans(pieces[i], pieces[i + 1]) if i + 1 < len(pieces) else pieces[i] for i in range(0, len(pieces), 2)] return pieces[0] class NotInLean(Exception): """A script line that Lean has no tactic for (rw_ac, ac_simp, auto modulo AC): bl lean gives the kernel's proof as a term instead.""" def lean_proof_term(d): """The kernel's proof in Lean: Eq.refl, Eq.symm, Eq.trans, congrArg and the facts applied to their arguments.""" def arg(t): return theories.lean_term(t, 3) match d: case Refl(t): return f"Eq.refl {arg(t)}" case Symm(p): return f"Eq.symm ({lean_proof_term(p)})" case Trans(p, q): return f"Eq.trans ({lean_proof_term(p)}) ({lean_proof_term(q)})" case CongrArg(z, C, p): return (f"congrArg (fun {z} => {theories.lean_term(C)}) " f"({lean_proof_term(p)})") case Inst(name, args): return " ".join([name] + [arg(a) for a in args]) raise ValueError(d) # --- script lines ------------------------------------------------------------ def strip_comment(line): return line.split("--", 1)[0].strip() def parse_line(line, notation=None): """A tactic line -> (tag, data). Tags: rw, rfl, symm, exact, trans, auto. A comment (-- …) and an empty line: ('nothing', None). notation: (abbreviations, function symbols) of another theory.""" s = strip_comment(line) if not s: return "nothing", None m = re.fullmatch(r"(rw|nth_rw\s+(\d+))\s*\[(.*)\]", s, re.S) if m: which = int(m.group(2)) if m.group(2) else None if which == 0: raise TacticError(("nth_zero",)) rules = [c.strip() for c in split_top(m.group(3), ",")] if not any(rules): raise TacticError(("empty_rw",)) if not all(rules): raise TacticError(("empty_rule",)) return "rw", (which, [parse_rule(c, notation) for c in rules]) word, _, rest = s.partition(" ") rest = rest.strip() if word in ("rfl", "symm") and not rest: return word, None if word == "exact" and rest: rule = parse_rule(rest, notation) if rule.backward: raise TacticError(("exact_backward",)) return "exact", rule if word == "trans" and rest: try: return "trans", term(rest, *(notation or ())) except (SyntaxError, ValueError, IndexError): raise TacticError(("argument", "argument", rest)) from None if word == "ac_rfl" and not rest: return "ac_rfl", None m = re.fullmatch(r"(rw_ac|ac_simp)\s*\[(.*)\]", s, re.S) if m: rules = [c.strip() for c in split_top(m.group(2), ",")] if not any(rules): raise TacticError(("empty_rw",)) if not all(rules): raise TacticError(("empty_rule",)) return m.group(1), [parse_rule(c, notation) for c in rules] if word == "auto": m = re.fullmatch(r"(\d+)?\s*(?:\[(.*)\])?", rest, re.S) if m: budget = int(m.group(1)) if m.group(1) else None lemmas = None if m.group(2) is not None: lemmas = [c.strip() for c in m.group(2).split(",") if c.strip()] return "auto", (budget, lemmas) raise TacticError(("unknown_tactic", s)) # --- proof state ------------------------------------------------------------- class ProofState: """The proof state: a list of goals; a tactic acts on the first one. Every tactic stores in its node a function compose, which builds a proof of the goal from proofs of the new goals — the tree for the kernel comes into being only at qed.""" def __init__(self, name, statement, available, exercise=None, taken=False, command="", constants=()): self.name, self.statement = name, statement self.variables = tuple(v for v in equation_vars(*statement) if v not in constants) self.constants = tuple(constants) self.available = list(available) self.available_set = set(available) self.exercise, self.taken = exercise, taken self.command = command self.goals = [(0, statement)] self.nodes = {} self.script = [] self.next_id = 1 self.history = [] self.seen = [] # goals seen before (also inside an rw) self.plans = [] # (steps, terms, method, thm) of recent hints self.undo_target = None # the goal the hints lead back to def apply(self, new_goals, compose, lines, intermediate=()): self.history.append((list(self.goals), dict(self.nodes), list(self.script), self.next_id, list(self.seen))) gid = self.goals[0][0] self.seen += [self.goals[0][1]] + list(intermediate) ids = list(range(self.next_id, self.next_id + len(new_goals))) self.next_id += len(new_goals) self.nodes[gid] = (ids, compose) self.goals = list(zip(ids, new_goals)) + self.goals[1:] self.script.extend(lines) def undo(self): (self.goals, self.nodes, self.script, self.next_id, self.seen) = self.history.pop() def build(self): """A proof of the statement from the nodes (no recursion), balanced.""" done, stack = {}, [(0, False)] while stack: gid, expanded = stack.pop() children, compose = self.nodes[gid] if expanded: done[gid] = compose(*[done.pop(c) for c in children]) else: stack.append((gid, True)) stack += [(c, False) for c in reversed(children)] return balance(done[0], self.statement) class _Focus: """The proof seen with one goal: a basic tactic inside a tactic expression acts on that goal (the rest is the proof's: the facts and variables it may use).""" def __init__(self, proof, goal): self.goals = [(0, goal)] self._proof = proof def __getattr__(self, name): return getattr(self._proof, name) def goal_size(goal): return term_size(goal[0]) + term_size(goal[1]) def term_depth(t): """The nesting of a term, without recursion.""" best, stack = 0, [(t, 1)] while stack: u, d = stack.pop() best = max(best, d) if not isinstance(u, str): stack.extend((a, d + 1) for a in u[1:]) return best def goal_depth(goal): return max(term_depth(goal[0]), term_depth(goal[1])) # --- solver: breadth-first search from both ends ----------------------------- class BfsSolver: """Like tactics.search, but every step is one rewrite at one place, remembered so that it can be written as an rw rule.""" def __init__(self, kernel, facts): self.by_head, self.anywhere = {}, [] for name in facts: vs, l, r = kernel.facts[name] ren = {x: "?" + x for x in vs} free = tuple(ren.values()) for backward, (a, b) in ((False, (l, r)), (True, (r, l))): pat, repl = subst(a, ren), subst(b, ren) extra = tuple(v for v in free if v not in leaves(pat)) entry = (name, backward, free, pat, repl, extra) if pat in free: self.anywhere.append(entry) else: self.by_head.setdefault(head(pat), []).append(entry) def neighbours(self, t, pool, bound): size_t = term_size(t) for path, u in positions(t): size_u = term_size(u) for entry in self.by_head.get(head(u), []) + self.anywhere: name, backward, free, pat, repl, extra = entry s = tac.match_pattern(pat, u, free, {}) if s is None: continue for choice in product(pool, repeat=len(extra)): s2 = dict(s) s2.update(zip(extra, choice)) v = subst(repl, s2) if size_t - size_u + term_size(v) > bound: continue args = tuple(s2[x] for x in free) yield replace_at(t, path, v), (path, name, backward, args) def search(self, l, r, budget=20000, seconds=None, bound=None, forbidden=(frozenset(), frozenset())): """((steps from the left, steps from the right) or None, visited). A step: (term before, (path, fact, backward, arguments)). Terms in `forbidden` (left, right) are skipped on their side — so a hint never sends us back to a side of the goal we already had.""" if l == r: return ([], []), 1 pool = tac.variables(r, tac.variables(l)) or ["0", "1"] if bound is None: bound = max(term_size(l), term_size(r)) + 5 parent = ({l: None}, {r: None}) queues = (deque([l]), deque([r])) start = time.perf_counter() while queues[0] or queues[1]: if len(parent[0]) + len(parent[1]) >= budget: break if seconds is not None and time.perf_counter() - start > seconds: break side = 0 if queues[0] and ( not queues[1] or len(queues[0]) <= len(queues[1])) else 1 t = queues[side].popleft() for new, step in self.neighbours(t, pool, bound): if new in parent[side] or new in forbidden[side]: continue parent[side][new] = (t, step) if new in parent[1 - side]: visited = len(parent[0]) + len(parent[1]) return (self._path(parent[0], new), self._path(parent[1], new)), visited queues[side].append(new) return None, len(parent[0]) + len(parent[1]) @staticmethod def _path(parent, t): steps = [] while parent[t] is not None: previous, step = parent[t] steps.append((previous, step)) t = previous return steps[::-1] # --- texts ------------------------------------------------------------------- FORMS = { "theorem": (("twierdzenie", "twierdzenia", "twierdzeń"), ("theorem", "theorems")), "step": (("krok", "kroki", "kroków"), ("step", "steps")), "goal": (("cel", "cele", "celów"), ("goal", "goals")), "node": (("węzeł", "węzły", "węzłów"), ("node", "nodes")), "term": (("term", "termy", "termów"), ("term", "terms")), "line": (("wiersz", "wiersze", "wierszy"), ("line", "lines")), "command": (("polecenie", "polecenia", "poleceń"), ("command", "commands")), "match": (("dopasowanie", "dopasowania", "dopasowań"), ("match", "matches")), "argument": (("argument", "argumenty", "argumentów"), ("argument", "arguments")), "earlier": (("wcześniejsze", "wcześniejsze", "wcześniejszych"), ("earlier", "earlier")), "turn": (("obrót", "obroty", "obrotów"), ("turn", "turns")), "alternative": (("alternatywa", "alternatywy", "alternatyw"), ("alternative", "alternatives")), } # what each part of a tactic expression does (bl tactic name, the # structure in the workshop) KIND_LABELS = { "seq": ("; — po kolei: każda część na tym, co zostawiła poprzednia", "; — in turn: each part on what the previous one left"), "then": ("<;> — druga część na każdym celu, który zrobiła pierwsza", "<;> — the second part on every goal the first one made"), "first": ("first — pierwsza alternatywa, która się uda", "first — the first alternative that succeeds"), "try": ("try — spróbuj; porażka niczego nie zmienia", "try — attempt it; a failure changes nothing"), "repeat": ("repeat — powtarzaj, dopóki się udaje", "repeat — again and again, while it succeeds"), "iterate": ("iterate {n} — dokładnie {n} razy", "iterate {n} — exactly {n} times"), "all_goals": ("all_goals — na każdym celu; porażka na jednym to " "porażka całości", "all_goals — on every goal; failing on one fails all"), "any_goals": ("any_goals — na każdym celu; wystarczy jeden sukces", "any_goals — on every goal; one success is enough"), "skip": ("skip — nic nie robi", "skip — does nothing"), "done": ("done — udaje się tylko, gdy nie ma celów", "done — succeeds only when no goal is left"), "fail": ("fail — zawsze zawodzi", "fail — always fails"), "hole": ("□ — do uzupełnienia", "□ — to fill in"), } MAX_TRACE_ROWS = 250 # rows of bl trace in the terminal # bl tactic first, …: the tacticals (tacticals.py) and how to design a # tactic; the same structure as the cards of the basic tactics in p_tactic TACTICAL_CARDS = { "first": ( "first | t₁ | t₂ | … — pierwsza alternatywa, która się uda", "first | t₁ | t₂ | … — the first alternative that succeeds", ["Próbuje t₁; jeśli zawiedzie, stan wraca do poprzedniego i próbuje " "t₂ itd. Zawodzi, gdy zawiodą wszystkie. Kolejność to priorytet: " "najpierw reguły konkretne i tanie.", "Alternatywa, która nigdy nie zawodzi (try, skip, symm), zasłania " "wszystkie następne — analiza to wskazuje. LCF: ORELSE."], ["Tries t₁; if it fails, the state goes back and t₂ is tried, and " "so on. Fails when all fail. The order is the priority: specific, " "cheap rules first.", "An alternative that never fails (try, skip, symm) hides all the " "later ones — the analysis points this out. LCF: ORELSE."], "bl prove x * 1 = x\nfirst | rw [H5] | rw [H6]"), "try": ( "try t — spróbuj; porażka nic nie zmienia", "try t — attempt it; a failure changes nothing", ["try t to first | t | skip: nigdy nie zawodzi. Wygodne na końcu " "(try rfl), groźne w repeat: repeat (try t) nie ma kiedy przestać."], ["try t is first | t | skip: it never fails. Handy at the end " "(try rfl), dangerous inside repeat: repeat (try t) never gets a " "reason to stop."], "bl prove x + 0 = x\ntry rw [H6]\nrw [H5]"), "repeat": ( "repeat t — powtarzaj, dopóki się udaje", "repeat t — again and again, while it succeeds", ["Kończy się przy pierwszej porażce t (to nie błąd: repeat sam nigdy " "nie zawodzi). Zatrzyma się na pewno, jeśli każdy obrót zmniejsza " "miarę — tu: sumę rozmiarów celów. Reguły skracające (x + 0 → x) " "ją zmniejszają, przemienność (x + y → y + x) nie, a reguła " "wydłużająca ją zwiększa.", "Gdy cele po obrocie są takie same jak wcześniej, laboratorium " "przerywa całą taktykę: ta pętla nie skończyłaby się nigdy (w " "Leanie: aż do limitu czasu). LCF: REPEAT."], ["It ends at the first failure of t (that is no error: repeat itself " "never fails). It surely stops if every turn decreases a measure — " "here: the sum of the sizes of the goals. Shortening rules " "(x + 0 → x) decrease it, commutativity (x + y → y + x) does not, " "and a lengthening rule increases it.", "When the goals after a turn are the same as before, the lab stops " "the whole tactic: this loop would never end (in Lean: until the " "time runs out). LCF: REPEAT."], "bl prove (x + 0) * 1 = x\nrepeat (first | rw [H5] | rw [H6])"), "iterate": ( "iterate n t — dokładnie n razy", "iterate n t — exactly n times", ["Zawodzi, jeśli t zawiedzie przy którymkolwiek z n razy."], ["Fails if t fails at any of the n times."], "bl prove x + 0 + 0 = x\niterate 2 rw [H5]"), "<;>": ( "t₁ <;> t₂ — t₂ na każdym celu, który zrobiła t₁", "t₁ <;> t₂ — t₂ on every goal that t₁ made", ["Jak w Leanie: t₁ działa na pierwszym celu, potem t₂ na każdym " "celu, który z niego powstał; porażka na jednym to porażka " "całości. Ma sens po taktyce, która robi kilka celów (trans t)."], ["As in Lean: t₁ acts on the first goal, then t₂ on every goal that " "came from it; failing on one fails it all. It makes sense after a " "tactic that makes several goals (trans t)."], "bl prove x + 0 = x * 1\ntrans x <;> first | rw [H5] | rw [H6]"), ";": ( "t₁; t₂ — po kolei", "t₁; t₂ — in turn", ["t₂ działa na tym, co zostawiła t₁ (na pierwszym celu). Porażka " "którejkolwiek to porażka całości. LCF: THEN."], ["t₂ acts on what t₁ left (on the first goal). Failing either " "fails it all. LCF: THEN."], "bl prove x + 0 = x\nrw [H5]; done"), "all_goals": ( "all_goals t · any_goals t — na wszystkich celach", "all_goals t · any_goals t — on all goals", ["all_goals t: t na każdym celu osobno; zawodzi, jeśli zawiedzie " "na którymkolwiek. any_goals t: wystarczy, że uda się na jednym; " "cele, na których zawiodła, zostają."], ["all_goals t: t on every goal on its own; fails if it fails on any " "of them. any_goals t: one success is enough; the goals where it " "failed stay."], "bl prove x + 0 = x * 1\ntrans x\nall_goals first | rw [H5] | " "rw [H6]"), "skip": ( "skip · done · fail — klocki kontrolne", "skip · done · fail — control blocks", ["skip nic nie robi i nigdy nie zawodzi. done udaje się tylko wtedy, " "gdy nie ma celów (sprawdza, że taktyka coś domknęła). fail " "\"komunikat\" zawsze zawodzi."], ["skip does nothing and never fails. done succeeds only when no " "goals are left (it checks that a tactic finished the job). fail " "\"message\" always fails."], "bl prove x + 0 = x\nrw [H5]; done"), "design": ( "Jak projektować taktyki", "How to design tactics", ["1. Taktyka to funkcja: cele → nowe cele i przepis, jak z ich " "dowodów złożyć dowód starego celu. qed oddaje całe drzewo jądru, " "więc zła taktyka nie udowodni fałszu — może tylko zawieść albo " "się nie skończyć.", "2. Ma się kończyć: każdy obrót repeat musi zmniejszać miarę " "(sumę rozmiarów celów). Reguły skracające — tak; przemienność — " "pętla; reguły wydłużające — rozrost.", "3. Ma zawodzić wyraźnie: taktyka, która nie może pomóc, zawodzi " "(wtedy first próbuje następnej). try i skip nie zawodzą nigdy — " "w repeat to pętla bez końca.", "4. Kolejność to priorytet: first próbuje od lewej — najpierw " "reguły konkretne i tanie.", "5. Zamknij albo zawiedź: taktyka kończąca (rfl, exact, done) nie " "zostawia celu w połowie.", "6. Buduj z małych części i sprawdzaj: nazwane taktyki wywołują " "inne jak lematy; bl tactic nazwa pokazuje budowę i analizę, " "bl trace — przebieg krok po kroku."], ["1. A tactic is a function: goals → new goals plus a recipe for " "building a proof of the old goal from their proofs. qed hands " "the whole tree to the kernel, so a bad tactic cannot prove a " "falsehood — it can only fail or never finish.", "2. It must stop: every turn of repeat must decrease a measure " "(the sum of the sizes of the goals). Shortening rules — yes; " "commutativity — a loop; lengthening rules — growth.", "3. It must fail clearly: a tactic that cannot help fails (then " "first tries the next one). try and skip never fail — inside " "repeat they make an endless loop.", "4. The order is the priority: first tries from the left — " "specific, cheap rules first.", "5. Close or fail: a finishing tactic (rfl, exact, done) does not " "leave a goal half done.", "6. Build from small parts and check: named tactics call others " "like lemmas; bl tactic name shows the structure and the " "analysis, bl trace the run step by step."], "bl tactic units := repeat (first | rw [H5] | rw [H6])\n" "bl trace units"), } def short_text(s, limit=240): return s if len(s) <= limit else s[:limit - 1] + "…" TACTICS = ("rw", "nth_rw", "rfl", "symm", "trans", "exact", "auto", "ac_rfl", "rw_ac", "ac_simp") TACTICALS = ("first", "try", "repeat", "iterate", "all_goals", "any_goals", "skip", "done", "fail") COMMANDS = ("help", "axioms", "lib", "prove", "lean", "model", "tactic", "kernel", "forget", "theory", "trace", "replay") # Example tactics of the workshop (English names of the theorems; a Polish # session translates them): (name, Polish name, body, good?, what it # teaches in Polish and in English). EXAMPLE_TACTICS = [ ("units", "jednostki", "repeat (first | rw [H5] | rw [H6] | rw [zero_add] | rw [one_mul])", True, "usuwa + 0, * 1, 0 + i 1 *; każda reguła skraca cel, więc repeat " "się zatrzyma", "removes + 0, * 1, 0 + and 1 *; every rule shortens the goal, so " "repeat stops"), ("simp_basic", "upraszczaj", "repeat (first | rw [H5] | rw [H6] | rw [zero_add] | rw [one_mul] | " "rw [H7] | rw [H8] | rw [compl_add] | rw [compl_mul] | rw [add_idem] | " "rw [mul_idem] | rw [add_one] | rw [one_add] | rw [mul_zero] | " "rw [zero_mul] | rw [absorb] | rw [absorb_mul] | rw [compl_compl] | " "rw [compl_zero] | rw [compl_one])", True, "własny „simp”: same reguły skracające cel — kolejność alternatyw to " "priorytet", "a home-made “simp”: only rules that shorten the goal — the order of " "the alternatives is the priority"), ("close", "zamknij", "first | rfl | exact H1 | exact H2", True, "zamyka cel albo zawodzi — nigdy nie zostawia go w połowie", "closes the goal or fails — never leaves it half done"), ("simp_close", "upraszczaj_zamknij", "simp_basic; try close", True, "taktyka z taktyk: najpierw upraszczanie, potem próba zamknięcia", "a tactic made of tactics: simplify first, then try to close"), ("simp_every", "upraszczaj_wszystkie", "all_goals simp_basic", True, "upraszcza każdy cel, nie tylko pierwszy (np. po trans t)", "simplifies every goal, not only the first one (e.g. after trans t)"), ("comm_loop", "petla_przem", "repeat rw [H1]", False, "zła: H1 tylko zamienia składniki, więc repeat kręciłby się w kółko", "bad: H1 only swaps the summands, so repeat would go round forever"), ("try_forever", "wieczne_try", "repeat (try rw [H5])", False, "zła: try nigdy nie zawodzi, więc repeat nie ma kiedy przestać", "bad: try never fails, so repeat never gets a reason to stop"), ] def fmt_number(n, lang): s = f"{n:,}" if lang == "pl": return s.replace(",", " ") if n >= 10000 else s.replace(",", "") return s def word_form(n, word, lang): pl, en = FORMS[word] if lang == "en": return en[0] if n == 1 else en[1] if n == 1: return pl[0] if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14: return pl[1] return pl[2] class Output: """The answer to a command: lines made of pieces (text, style[, action]); an action is {'insert': …}, {'run': …} or {'href': …}.""" def __init__(self): self.rows, self.error, self.extras = [], False, {} def add(self, *pieces): row = [] for k in pieces: row.append([k, ""] if isinstance(k, str) else list(k)) self.rows.append(row) return self def text(self): return "\n".join("".join(k[0] for k in w) for w in self.rows) # --- the library in two languages -------------------------------------------- def library_names(lang): """English theorem name -> its name in a session in `lang` (the Polish edition keeps the Polish names).""" return {t["name"]: t["name_pl"] if lang == "pl" else t["name"] for s in library.SECTIONS for t in s["theorems"]} def localize_script(script, lang, names): """The lines of a library script for a session in `lang`. In Polish the theorem names in the tactics (whole words) become the session's names and each comment goes through library.COMMENTS_PL (a comment without words stays as it is).""" lines = [x.strip() for x in script.strip().split("\n")] if lang != "pl": return lines word = re.compile(r"\b(" + "|".join(sorted( map(re.escape, names), key=len, reverse=True)) + r")\b") result = [] for line in lines: code, sep, comment = line.partition("--") code = word.sub(lambda m: names[m.group(1)], code) if sep: comment = library.COMMENTS_PL.get(sep + comment, sep + comment) result.append(code + comment) return result # keys of the theorems saved by the first (Polish) version of the page LEGACY_KEYS = {"nazwa": "name", "rownosc": "equation", "skrypt": "script"} # --- session ----------------------------------------------------------------- class Session: """One session of the lab: a kernel with the axioms H1–H8, the library (replayed by the kernel at the start), the user's theorems and at most one proof in progress.""" def __init__(self, lang="en", base_url="../kernel/"): self.lang = lang if lang in ("pl", "en") else "en" self.base_url = base_url self.kernel = boolean.theory() self.axioms = [n for n, _ in boolean.AXIOMS] self.names = library_names(self.lang) # English -> session's name self.lib = {} # name -> a library theorem self.order = [] # library names in order self.own = {} # name -> the user's theorem self.proofs = {} # name -> tree accepted by the kernel self.proof = None # the proof in progress self.last = None # the last checked script self.lib_index = {} # canonical equation -> library name self._bfs_cache = None # solver for the last set of facts self._expander = None # solver.Expander (proofs of theorems) self._normal_form = None # solver.NormalForm self._hint_cache = (None,) # suggestions for the last goal self._auto_info = None # (steps, visited, time) of last auto self._intermediate = [] # goals inside the last rw self.theory = None # another axiom system (bl theory) self.notation = None # its (abbreviations, function symbols) self.models = [] # finite models of its axioms self._saved = None # the Boolean state while in a theory self.tactics = {} # name -> a tactic expression (below) self._replaying = False # replaying the user's saved theorems self._compound = None # (node, trace, runner, end) of the last self._runner = None # the runner of the last expression t0 = time.perf_counter() self.library_errors = self._replay_library() self.library_time = time.perf_counter() - t0 self._define_examples() # -- other axiom systems (bl theory; theories.py) -- def parse_equation(self, text): """An equation in the notation of the session: with the lab's abbreviations, or with the function symbols of the theory.""" if self.theory is None: return equation(text) return equation(text, *self.notation) def theory_name(self, key): """The name of a theory as the session shows it.""" if key is None: return "boole" return self.tr(theories.THEORIES[key]["name_pl"], key) def model_cex(self, l, r): """(model, valuation) for the first model of the theory's axioms in which l = r fails, or None.""" for model in self.models: v = theories.counterexample(l, r, model) if v is not None: return model, v return None def model_text(self, model): info = theories.MODELS[model] return f"{model}, {self.tr(info['desc_pl'], info['desc_en'])}" def theory_falsity_text(self, goal, found, undo=False): model, v = found vals = ", ".join(f"{k} = {x}" for k, x in v.items()) or "—" lv = theories.value(goal[0], model, v) rv = theories.value(goal[1], model, v) return self.tr( f"fałsz w modelu {self.model_text(model)} — dla {vals}: lewa " f"{lv}, prawa {rv}; w tym modelu zachodzą wszystkie aksjomaty, " "więc to nie wynika z aksjomatów i nie ma dowodu" + (" — cofnij krok (undo)" if undo else ""), f"false in the model {self.model_text(model)} — for {vals}: " f"left {lv}, right {rv}; all the axioms hold in that model, so " "it does not follow from the axioms and has no proof" + (" — undo the step (undo)" if undo else "")) def notation_text(self): if self.theory is None: return "x + y, x * y, n(x), 0, 1" parts = [] for s, k in theories.THEORIES[self.theory]["signature"].items(): if s in ("+", "*"): parts.append(f"x {s} y") elif k == 0: parts.append(s) else: parts.append(f"{s}({', '.join('xyz'[:k])})") return ", ".join(parts) def lean_term(self, t, prec=0): if self.theory is None: return show_lean(t, prec) return theories.lean_term(t, prec) def lean_class_name(self): if self.theory is None: return LEAN_CLASS_NAME[self.lang] return theories.THEORIES[self.theory]["lean_class"] def lean_class_text(self): if self.theory is None: return LEAN_CLASS[self.lang] given = [(n, i["statement"]) for n, i in self.own.items() if i.get("given")] text = theories.lean_class(self.theory, theories.axioms(self.theory) + given) if given: first = text.index(f" {given[0][0]} :") text = text[:first] + self.tr( " -- fakty dane: lematy Manna z założeniami, dowiedzione " "przez silnik\n -- (ich termy mają tysiące węzłów; jądro " "sprawdza je w bl replay mann)\n", " -- given facts: Mann's lemmas with hypotheses, proved by " "the engine\n -- (their terms have thousands of nodes; the " "kernel checks them in bl replay mann)\n") + text[first:] return text def _reset_caches(self): self.proof, self.last = None, None self._bfs_cache = self._expander = self._normal_form = None self._hint_cache = (None,) self._auto_info = None def enter_theory(self, key): info = theories.THEORIES[key] if self._saved is None: self._saved = (self.kernel, self.axioms, self.lib, self.order, self.own, self.proofs, self.lib_index) k = Kernel(info["signature"]) axioms = theories.axioms(key) for name, (l, r) in axioms: k.axiom(name, [v for v in theories.variables_of( r, theories.variables_of(l)) if v not in info["signature"]], l, r) self.kernel, self.axioms = k, [n for n, _ in axioms] self.lib, self.order, self.own = {}, [], {} self.proofs, self.lib_index = {}, {} self.theory, self.notation = key, ({}, dict(info["functions"])) self.models = [m for m, bad in theories.models(key) if not bad] self._reset_caches() for name, l, r, d, note_pl, note_en in ( rl.given(key, k) if "ac" in info else ()): k.theorem(name, (), l, r, d) self.proofs[name] = d self.own[name] = {"statement": (l, r), "script": [], "variables": (), "steps": 0, "command": "", "given": True, "description": self.tr(note_pl, note_en)} return self.theory_card() def leave_theory(self): t = self.tr if self.theory is None: return Output().add((t( " już pracujesz z aksjomatami Huntingtona H1–H8", " you are already working with Huntington's axioms H1–H8"), "dim")) (self.kernel, self.axioms, self.lib, self.order, self.own, self.proofs, self.lib_index) = self._saved self._saved, self.theory, self.notation, self.models = \ None, None, None, [] self._reset_caches() return Output().add(("✓ ", "ok"), (t( "z powrotem: aksjomaty Huntingtona H1–H8, biblioteka i Twoje " "twierdzenia", "back to Huntington's axioms H1–H8, the library " "and your theorems"), "ok")) def theory_card(self): """What the current theory is: axioms, models, how to work.""" t = self.tr info = theories.THEORIES[self.theory] w = Output() w.add((t("Teoria ", "Theory "), "heading"), (self.theory_name(self.theory), "name"), " — ", (t(info["title_pl"], info["title_en"]), "heading")) for name in self.axioms: w.add((" ", ""), (name.ljust(6), "name", {"insert": f"rw [{name}]"}), (self.fact_text(name), "goal")) w.add((t("Modele skończone", "Finite models"), "heading")) for model, bad in theories.models(self.theory): if bad: note = t(f"nie spełnia: {', '.join(bad)}", f"fails: {', '.join(bad)}") else: note = t("spełnia wszystkie aksjomaty — w nim sprawdzam cele", "satisfies all the axioms — goals are checked in it") w.add((" ", ""), (self.model_text(model), "code"), " — ", (note, "dim")) if "ac" in info and rl.steps_of(self.theory): self.variants_card(w) return w w.add((t("Do udowodnienia (spróbuj)", "To prove (try it)"), "heading")) for text in info["challenges"]: l, r = self.parse_equation(text) found = self.model_cex(l, r) mark = "✗ " if found else " " note = t(f" (fałsz w {found[0]})", f" (false in {found[0]})") \ if found else "" w.add((" " + mark, "error" if found else ""), (f"bl prove {show_equation((l, r))}", "code", {"insert": f"bl prove {show_equation((l, r))}"}), (note, "dim")) w.add((t( " Jądro jest nowe: zna tylko te aksjomaty (biblioteka " "i ćwiczenia są wyłączone). Podpowiedzi i auto szukają dowodu " "wszerz — " "postać normalna działa tylko w algebrze Boole'a. Cel fałszywy " "w modelu aksjomatów nie ma dowodu. bl lean nazwa — dowód " "w Leanie; bl theory boole — powrót.", " The kernel is new: it knows only these axioms (the library and " "the exercises are off). Hints and auto search breadth-first — " "the normal form works only in Boolean algebra. A goal that is " "false in a model of the axioms has no proof. bl lean name — the " "proof in Lean; bl theory boole — back."), "dim")) return w def variants_card(self, w): """The part of the card of a Robbins theory: the given facts, the stages of both variants proved here, the other stages.""" t = self.tr given = [n for n, i in self.own.items() if i.get("given")] if given: w.add((t("Fakty dane (lematy z założeniami, dowiedzione przez " "silnik — jądro je sprawdziło)", "Given facts (lemmas with hypotheses, proved by the " "engine — checked by the kernel)"), "heading")) for name in given: w.add((" ", ""), (name.ljust(6), "name", {"insert": f"rw_ac [{name}]"}), (self.fact_text(name), "goal")) w.add((" " + self.own[name]["description"], "dim")) w.add((t("Warianty dowodu twierdzenia Robbinsa", "Variants of the proof of the Robbins theorem"), "heading")) for key, variant in rl.VARIANTS.items(): for i, stage in enumerate(variant["stages"], 1): if stage["theory"] != self.theory: continue first = stage["steps"][0]["name"] w.add((" ", ""), (t(variant["title_pl"], variant["title_en"]) + t(f", etap {i}: ", f", stage {i}: "), "name"), (t(stage["title_pl"], stage["title_en"]), ""), (f" ({self.counted(len(stage['steps']), 'step')})", "dim")) w.add((" ", ""), (f"bl prove {first}", "code", {"insert": f"bl prove {first}"}), t(" — pierwszy krok (hint pokazuje skrypt wzorcowy) · ", " — the first step (hint shows the reference " "script) · "), (f"bl replay {key} {i}", "code", {"run": f"bl replay {key} {i}"}), t(" — cały etap", " — the whole stage")) w.add((t("Wszystkie etapy", "All the stages"), "heading")) for key, variant in rl.VARIANTS.items(): parts = [] for i, stage in enumerate(variant["stages"], 1): where = stage["theory"] or t("silnik", "engine") parts.append(f"{i}. {where}") w.add((" ", ""), (t(variant["title_pl"], variant["title_en"]), "name"), (": " + " · ".join(parts), "dim"), (" ", ""), (f"bl replay {key}", "code", {"run": f"bl replay {key}"})) w.add((t( " Taktyki modulo przemienność i łączność (A1, A2): ac_rfl, " "rw_ac [h] (wzorzec dopasowany do części sumy), ac_simp [h, …] " "(przepisuje, dopóki się da) i auto [h, …] (szuka przepisań z obu " "stron celu; bez listy: tylko R). Jądro jest nowe: zna aksjomaty " "teorii i fakty dane. bl theory boole — powrót.", " Tactics modulo commutativity and associativity (A1, A2): " "ac_rfl, rw_ac [h] (the pattern matched to a part of a sum), " "ac_simp [h, …] (rewrites while it can) and auto [h, …] (looks " "for rewrites on both sides of the goal; without a list: R " "only). The kernel is new: it knows the axioms of the theory and " "the given facts. bl theory boole — back."), "dim")) def variant_step(self, name=None, statement=None): """(variant, stage, step) of the current theory with this name (and the same statement) or with this statement; None otherwise.""" if self.theory is None or "ac" not in theories.THEORIES[self.theory]: return None for key, i, step in rl.steps_of(self.theory): l, r = self.parse_equation(step["statement"]) same = statement is not None and \ canonical(*statement) == canonical(l, r) if (name == step["name"] and (statement is None or same)) or \ (name is None and same): return key, i, step return None def variant_plan(self, proof, step): """The goals before each line of the reference script, run from the statement in a trial proof: ([goal before line 1, ...], error or None) — an error stops the plan (e.g. a fact not proved yet).""" key = (self.theory, step["name"], tuple(proof.available)) cache = getattr(self, "_plans", {}) if key in cache: return cache[key] goal = self.parse_equation(step["statement"]) trial = ProofState(step["name"], goal, proof.available, constants=proof.constants) goals, error = [], None for line in step["script"]: if not trial.goals: break goals.append(trial.goals[0][1]) try: self.run_line(trial, line) except (TacticError, ProofError) as e: error = (line, self.error_text(e)) break self._plans = {**cache, key: (goals, error)} return goals, error def variant_suggestion(self, proof, goal): """The next line of the reference script when the goal lies on it (the hint and the ghost of TAB); None otherwise.""" found = self.variant_step(proof.name, proof.statement) or \ self.variant_step(None, proof.statement) if found is None: return None key, stage, step = found goals, _ = self.variant_plan(proof, step) k = max((i for i, g in enumerate(goals) if g == goal), default=None) if k is None: return None line = step["script"][k] trial = ProofState(proof.name, goal, proof.available, constants=proof.constants) try: new_goals, _, _ = self.tactic(trial, line) except (TacticError, ProofError): return None new = new_goals[0] if new_goals else None before = term_size(goal[0]) + term_size(goal[1]) after = term_size(new[0]) + term_size(new[1]) if new else 0 kind = "closes" if new is None else "shrinks" if after < before \ else "same" if after == before else "grows" entry = self._hint_entry(line, None, kind, new, [], "variant", 0, -1) entry.update({"solver": len(step["script"]) - k, "method": "variant", "theorem": self.tr(step["source_pl"], step["source_en"]), "variant": key, "reverts": False}) return entry def variant_hint(self, w, proof, goal): """For a step of a variant: its reference script, the lines done (✓), the next one (▸), and what it still needs.""" t = self.tr found = self.variant_step(proof.name, proof.statement) or \ self.variant_step(None, proof.statement) if found is None: return key, stage, step = found goals, error = self.variant_plan(proof, step) k = max((i for i, g in enumerate(goals) if g == goal), default=None) w.add((t("Skrypt wzorcowy ", "The reference script "), "heading"), (f"({t(step['source_pl'], step['source_en'])})", "heading")) for i, line in enumerate(step["script"]): mark = "✓ " if k is not None and i < k else \ "▸ " if i == k else " " w.add((" " + mark, "ok" if mark == "✓ " else ""), (line, "code", {"insert": line})) if k is None: w.add((t(" cel zszedł ze skryptu wzorcowego — cofnij (undo) " "albo zacznij od nowa (restart)", " the goal left the reference script — go back (undo) " "or start again (restart)"), "warning")) elif error is not None and k == len(goals) - 1: line, why = error missing = [n for n in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", line) if n not in proof.available and self.variant_step(n) is not None] if missing: w.add((t(" ten krok korzysta z wcześniejszych — " "najpierw: ", " this step uses earlier ones — " "first: "), "warning"), *[piece for n in dict.fromkeys(missing) for piece in ((f"bl prove {n}", "code", {"insert": f"bl prove {n}"}), (" ", ""))]) else: w.add((" " + why, "warning")) def p_replay(self, rest=""): """bl replay mann | mccune [stage ...]: the steps of a variant proved by their reference scripts, theory by theory; without stages also the assembly of the whole proof in one kernel.""" t = self.tr words = rest.split() if not words or words[0] not in rl.VARIANTS: w = Output().add((t("Warianty dowodu twierdzenia Robbinsa " "(bl replay wariant [etap])", "Variants of the proof of the Robbins " "theorem (bl replay variant [stage])"), "heading")) for key, variant in rl.VARIANTS.items(): w.add((" ", ""), (f"bl replay {key}".ljust(18), "code", {"run": f"bl replay {key}"}), (t(variant["title_pl"], variant["title_en"]), "name")) for i, stage in enumerate(variant["stages"], 1): where = stage["theory"] or t("silnik", "engine") w.add((" ", ""), (f"{i}. ", "dim"), (f"{where}: ".ljust(13), "code"), (t(stage["title_pl"], stage["title_en"]), "dim")) return w if not words else w.add((t( f" nie znam wariantu {words[0]!r}", f" unknown variant {words[0]!r}"), "error")) key = words[0] variant = rl.VARIANTS[key] n = len(variant["stages"]) if any(not x.isdigit() or not 1 <= int(x) <= n for x in words[1:]): return self.error(t(f"etapy to liczby 1–{n}", f"the stages are the numbers 1–{n}")) chosen = [int(x) for x in words[1:]] or list(range(1, n + 1)) w = Output() if self.proof is not None: w.add((t(f" (porzucam dowód {self.proof.name})", f" (abandoning the proof of {self.proof.name})"), "dim")) self.proof = None t0 = time.perf_counter() for i in chosen: stage = variant["stages"][i - 1] w.add((t(f"{t(variant['title_pl'], variant['title_en'])}, " f"etap {i}: ", f"{variant['title_en']}, stage {i}: "), "heading"), (t(stage["title_pl"], stage["title_en"]), "heading")) if stage["theory"] is None: w.add((t( " Lematy 33–40 Manna mają założenia, a jądro nie ma " "implikacji: silnik dowodzi każdego raz, ze stałymi " "zamiast zmiennych (robbins_proof.hypothetical_lemmas), " "i podstawia go tam, gdzie jest potrzebny. W teorii " "robbins_ab trzy takie podstawienia są faktami danymi: " "m38, m40a, m40b.", " Mann's lemmas 33–40 have hypotheses, and the kernel " "has no implication: the engine proves each once, with " "constants instead of variables " "(robbins_proof.hypothetical_lemmas), and substitutes " "it where it is needed. In the theory robbins_ab three " "such substitutions are given facts: m38, m40a, m40b."), "dim")) continue if stage["theory"] != self.theory: self.enter_theory(stage["theory"]) w.add((" → ", "dim"), (f"bl theory {stage['theory']}", "code")) for step in stage["steps"]: if not self.replay_step(w, step): return w if not words[1:]: K, name = rl.assemble(key) _, l, r = K.facts[name] w.add((t("Złożenie etapów w jednym jądrze", "The stages joined in one kernel"), "heading")) w.add(("✓ ", "ok"), (name, "name"), " : ", (show_equation((l, r)), "goal")) w.add((t(" założenia (jak #print axioms): ", " assumptions (like #print axioms): "), "dim"), (", ".join(sorted(K.assumptions[name])), "code"), (t(" — stałe etapów zastąpione termami, każdy dowód " "sprawdzony od nowa", " — the constants of the stages replaced by terms, " "every proof checked again"), "dim")) w.add((t(" czas: ", " time: ") + self.fmt_seconds(time.perf_counter() - t0), "dim")) return w def replay_step(self, w, step): """Proves one step by its reference script; a line of the report (False when the script fails).""" t = self.tr name = step["name"] if name in self.kernel.facts: w.add((" · ", "dim"), (name, "name"), (t(" — już udowodnione", " — already proved"), "dim")) return True start = self.p_prove(name) if start.error: w.rows += start.rows return False for line in step["script"]: try: self.run_line(self.proof, line) except (TacticError, ProofError) as e: w.add((" ✗ ", "error"), (name, "name"), (f" {line}: ", "code"), (self.error_text(e), "error")) self.proof = None return False done = self.p_qed() if done.error: w.rows += done.rows return False d = self.proofs[name] w.add((" ✓ ", "ok"), (name, "name", {"run": f"bl lean {name}"}), " : ", (show_equation(self.own[name]["statement"]), "goal"), (f" {t(step['source_pl'], step['source_en'])}", "dim")) w.add((" ", ""), (" · ".join(step["script"]), "code"), (t(f" ({self.counted(size(d), 'node')})", f" ({self.counted(size(d), 'node')})"), "dim")) return True def p_theory(self, rest=""): t = self.tr name = rest.strip() if not name: return self.theory_list() if name in ("boole", "boolean", "huntington", "H"): return self.leave_theory() aliases = {info["name_pl"]: key for key, info in theories.THEORIES.items()} key = name if name in theories.THEORIES else aliases.get(name) if key is None: names = ", ".join(["boole"] + [self.theory_name(k) for k in theories.THEORIES]) return self.error(t(f"nie znam teorii {name!r} — są: {names}", f"unknown theory {name!r} — there are: " f"{names}")) w = Output() if self.proof is not None: w.add((t(f" (porzucam dowód {self.proof.name})", f" (abandoning the proof of {self.proof.name})"), "dim")) w.rows += self.enter_theory(key).rows return w def theory_list(self): t = self.tr w = Output() w.add((t("Inne aksjomaty (bl theory nazwa)", "Other axioms (bl theory name)"), "heading")) rows = [("boole", t("aksjomaty Huntingtona H1–H8 i biblioteka " "(domyślnie)", "Huntington's axioms H1–H8 and " "the library (default)"), None)] for key, info in theories.THEORIES.items(): rows.append((self.theory_name(key), t(info["title_pl"], info["title_en"]), key)) for name, title, key in rows: mark = "● " if key == self.theory else " " w.add((" " + mark, "ok"), (name.ljust(10), "code", {"run": f"bl theory {name}"}), (title, "dim")) return w # -- small helpers -- def tr(self, pl, en): return pl if self.lang == "pl" else en def counted(self, n, word): return f"{fmt_number(n, self.lang)} {word_form(n, word, self.lang)}" def in_steps(self, n): """Polish locative: „w 1 kroku”, „w 5 krokach” (en: in 5 steps).""" if self.lang == "en": return self.counted(n, "step") return f"{fmt_number(n, 'pl')} {'kroku' if n == 1 else 'krokach'}" def fmt_seconds(self, t): s = f"{t:.2f}" if t < 10 else f"{t:.1f}" return (s.replace(".", ",") if self.lang == "pl" else s) + " s" def error(self, *pieces): w = Output() w.error = True return w.add(("✗ ", "error"), *pieces) def error_text(self, e): """The message of a tactic error (a key tuple or a string).""" a = e.args[0] if e.args else "" if not isinstance(a, tuple): return str(a) k = a[0] if k in ("rule", "argument"): return self.tr(f"nie rozumiem: {a[2]!r}", f"cannot parse: {a[2]!r}") if k == "too_many_args": return self.tr( f"{a[1]} ma tylko {self.counted(a[2], 'argument')}", f"{a[1]} takes only {self.counted(a[2], 'argument')}") if k == "metavariable": rule = a[1] return self.tr( f"{rule.text()}: wzorzec to sama zmienna, więc pasowałby do " "każdego podtermu (Lean: „pattern is a metavariable”); " "podaj jako argument podterm, który chcesz przepisać, np. " f"{rule.text()} (x + x)", f"{rule.text()}: the pattern is a bare variable, so it would " "match every subterm (Lean: “pattern is a metavariable”); " "give the subterm you want to rewrite as an argument, e.g. " f"{rule.text()} (x + x)") if k == "undetermined": rule, pat, missing = a[1], a[2], a[3] names = ", ".join(missing) return self.tr( f"{rule.text()}: wzorzec {show(pat)} nie wyznacza {names} — " f"podaj argumenty, np. {rule.text()} x", f"{rule.text()}: the pattern {show(pat)} does not " f"determine {names} — give arguments, e.g. " f"{rule.text()} x") if k == "no_pattern": rule, pat, goal = a[1], a[2], a[3] return self.tr( f"{rule.text()}: w celu {show_equation(goal)} nie ma wzorca " f"{show(pat)}", f"{rule.text()}: the pattern {show(pat)} does not occur " f"in the goal {show_equation(goal)}") if k == "no_such_match": rule, which, n = a[1], a[2], a[3] return self.tr( f"{rule.text()}: wzorzec ma tylko " f"{self.counted(n, 'match')}, nie ma {which}.", f"{rule.text()}: the pattern has only " f"{self.counted(n, 'match')}, there is no match {which}") if k == "nth_zero": return self.tr("nth_rw liczy dopasowania od 1", "nth_rw counts matches from 1") if k in ("empty_rw", "empty_rule"): return self.tr("rw [ … ] potrzebuje reguł, np. rw [H1]", "rw [ … ] needs rules, e.g. rw [H1]") if k == "exact_backward": return self.tr("exact nie przyjmuje ← (użyj symm albo rw)", "exact does not take ← (use symm or rw)") if k == "unknown_tactic": return self.tr( f"nieznane polecenie albo taktyka: {a[1]!r} (bl help)", f"unknown command or tactic: {a[1]!r} (bl help)") if k.startswith("tc_"): return self.tacticals_error(a) return " ".join(map(str, a)) def tacticals_error(self, a): """The messages of tacticals.py (keys tc_…).""" t, k = self.tr, a[0] if k == "tc_parse": what, pos, text = a[1], a[2], a[3] near = text[pos:pos + 12].strip() where = t(f" (znak {pos + 1}: {near!r})" if near else " (na końcu)", f" (character {pos + 1}: {near!r})" if near else " (at the end)") msg = { "empty": ("pusta taktyka", "an empty tactic"), "missing": ("tu brakuje taktyki", "a tactic is missing here"), "close": ("brakuje nawiasu )", "a ) is missing"), "stray_close": ("nawias ) bez (", "a ) without a ("), "first": ("po first piszemy alternatywy: first | t₁ | t₂", "first takes alternatives: first | t₁ | t₂"), "bar": ("| należy do first: first | t₁ | t₂", "| belongs to first: first | t₁ | t₂"), "stray_bar": ("| należy do first: first | t₁ | t₂", "| belongs to first: first | t₁ | t₂"), "count": (f"po iterate piszemy liczbę od 1 do " f"{tc.MAX_ITERATE}: iterate 3 t", f"iterate takes a number from 1 to " f"{tc.MAX_ITERATE}: iterate 3 t"), "string": ("fail \"komunikat\" — brakuje cudzysłowu", "fail \"message\" — a quote is missing"), "escape": ("w komunikacie fail nie może być znaku \\", "a fail message cannot contain \\"), "auto": ("auto nie może być częścią taktyki — Lean go nie " "zna; jego dowód zapisuje się jako zwykłe kroki", "auto cannot be part of a tactic — Lean does not " "know it; its proof is written as ordinary steps"), "ac_tactic": ("rw_ac i ac_simp nie mogą być częścią " "taktyki — Lean nie ma takich taktyk; użyj ich " "w osobnym wierszu (ac_rfl wolno)", "rw_ac and ac_simp cannot be part of a tactic " "— Lean has no such tactics; use them on a " "line of their own (ac_rfl is allowed)"), "depth": (f"za głęboko zagnieżdżone (najwyżej " f"{tc.MAX_DEPTH} poziomów)", f"nested too deeply (at most {tc.MAX_DEPTH} " "levels)"), "unexpected": ("tego tu się nie spodziewałem", "this is not expected here"), }.get(what, (what, what)) return t("taktyka: " + msg[0], "tactic: " + msg[1]) + where if k == "tc_step": return self.error_text(a[1]) if k == "tc_no_goals": return t("nie ma celu, na którym można by działać", "there is no goal to act on") if k == "tc_unknown": return t(f"nie ma taktyki {a[1]} (bl tactic {a[1]} := …)", f"there is no tactic {a[1]} (bl tactic {a[1]} := …)") if k == "tc_done": return t(f"done: zostało jeszcze {self.counted(a[1], 'goal')}", f"done: {self.counted(a[1], 'goal')} left") if k == "tc_fail": return t("fail" + (f": {a[1]}" if a[1] else ""), "fail" + (f": {a[1]}" if a[1] else "")) if k == "tc_hole": return t("□ — najpierw uzupełnij taktykę", "□ — fill in the tactic first") if k == "tc_first": return t(f"first: żadna z {a[1]} alternatyw się nie udała" if a[1] > 1 else "first: alternatywa się nie udała", f"first: none of the {a[1]} alternatives succeeded" if a[1] > 1 else "first: the alternative failed") if k == "tc_any_goals": return t("any_goals: nie udało się na żadnym celu", "any_goals: it failed on every goal") if k == "tc_loop": turn, earlier, goal = a[1], a[2], a[3] goal_text = show_equation(goal) if goal is not None else \ t("brak celów", "no goals") if turn - earlier == 1 and goal is not None and earlier == \ turn - 1 and turn == 1: return t( "repeat się zapętla: pierwszy obrót niczego nie zmienił " f"({goal_text}), a ciało się udaje — repeat nigdy by nie " "przestał. Ciało repeat musi zmieniać cel albo zawieść " "(bl tactic repeat)", "repeat loops: the first turn changed nothing " f"({goal_text}) and the body succeeds — repeat would " "never stop. The body of repeat must change the goal or " "fail (bl tactic repeat)") when = t(f"przed pierwszym obrotem" if earlier == 0 else f"po obrocie {earlier}", "before the first turn" if earlier == 0 else f"after turn {earlier}") return t( f"repeat się zapętla: po obrocie {turn} cele są takie same " f"jak {when} ({goal_text}) — kręciłby się w kółko bez końca " "(w Leanie: aż do limitu czasu). Każdy obrót musi zmniejszać " "cele (bl tactic repeat)", f"repeat loops: after turn {turn} the goals are the same as " f"{when} ({goal_text}) — it would go round forever (in " "Lean: until the time runs out). Every turn must make the " "goals smaller (bl tactic repeat)") if k == "tc_steps": return t(f"przekroczony limit {fmt_number(a[1], 'pl')} kroków — " "taktyka nie kończy się w rozsądnym czasie", f"over the limit of {fmt_number(a[1], 'en')} steps — " "the tactic does not finish in a reasonable time") if k == "tc_nodes": return t(f"przekroczony limit {fmt_number(a[1], 'pl')} wykonań " "części taktyki", f"over the limit of " f"{fmt_number(a[1], 'en')} runs of parts of the tactic") if k == "tc_time": return t(f"taktyka liczyła dłużej niż " f"{self.fmt_seconds(a[1])} — przerwana", f"the tactic ran longer than {self.fmt_seconds(a[1])} " "— stopped") if k == "tc_size": return t(f"cel urósł do {fmt_number(a[1], 'pl')} symboli (limit " f"{fmt_number(a[2], 'pl')}) — taktyka rozdmuchuje cel", f"the goal grew to {fmt_number(a[1], 'en')} symbols " f"(limit {fmt_number(a[2], 'en')}) — the tactic blows " "the goal up") if k == "tc_deep": return t(f"cel zagnieździł się głębiej niż {a[1]} poziomów — " "taktyka rozdmuchuje cel (każdy obrót go wydłuża?)", f"the goal got nested deeper than {a[1]} levels — the " "tactic blows the goal up (does every turn lengthen " "it?)") if k == "tc_depth": return t(f"za głęboko zagnieżdżone wywołania (najwyżej {a[1]})", f"calls nested too deeply (at most {a[1]})") return " ".join(map(str, a)) # -- facts -- def all_facts(self): return self.axioms + self.order + list(self.own) def source(self, name): if name in self.axioms: return "axiom" return "library" if name in self.lib else "own" def fact_text(self, name): _, l, r = self.kernel.facts[name] return f"{show(l)} = {show(r)}" def check_rule(self, proof, rule): if rule.name not in self.kernel.facts: similar = difflib.get_close_matches(rule.name, self.all_facts(), n=3) raise TacticError(self.tr( f"nie znam faktu {rule.name}", f"unknown fact {rule.name}") + (self.tr(" (może: ", " (maybe: ") + ", ".join(similar) + ")" if similar else "")) if rule.name not in proof.available_set: raise TacticError(self.tr( f"{rule.name} jest w bibliotece dalej niż ćwiczenie " f"{proof.exercise} — tu niedostępne", f"{rule.name} comes later in the library than the exercise " f"{proof.exercise} — not available here")) self.check_variables(proof, rule.args) def constants(self): """The constants of the theory written as names (A, B, e, ...).""" return tuple(s for s, k in self.kernel.signature.items() if k == 0 and s.isidentifier()) def ac_axioms(self): """The names of commutativity and associativity of + in this theory (for ac_rfl, rw_ac, ac_simp), or an error.""" if self.theory is not None and \ "ac" in theories.THEORIES[self.theory]: return theories.THEORIES[self.theory]["ac"] raise TacticError(self.tr( "ta taktyka działa w teoriach z przemiennością i łącznością " "jako aksjomatami (A1, A2): bl theory robbins", "this tactic works in theories with commutativity and " "associativity as axioms (A1, A2): bl theory robbins")) def check_variables(self, proof, terms): for t in terms: foreign = sorted(v for v in set(tac.variables(t)) - set(proof.variables) if self.kernel.is_var(v)) if foreign: raise TacticError(self.tr( f"zmienna {', '.join(foreign)} nie występuje w " "twierdzeniu (Lean: unknown identifier)", f"variable {', '.join(foreign)} does not occur in the " "theorem (Lean: unknown identifier)")) # -- tactics: each returns (new goals, compose, script lines) -- def tactic(self, proof, line, log=None): tag, data = parse_line(line, self.notation) if tag == "nothing": return None if not proof.goals: raise TacticError(self.tr("nie ma już celów — wpisz qed", "no goals left — type qed")) goal = proof.goals[0][1] if tag == "rw": which, rules = data for rule in rules: self.check_rule(proof, rule) steps = [] for rule in rules: new, compose = rewrite(self.kernel, goal, rule, which) steps.append((goal, compose)) goal = new if log is not None: log.append((rule.text(), goal)) end = goal def compose_rw(*children): d = children[0] if children else Refl(end[0]) for previous, comp in reversed(steps): d = comp(d) or Refl(previous[0]) return d new_goals = [] if end[0] == end[1] else [end] rules_text = ", ".join(r.text() for r in rules) line_text = f"nth_rw {which} [{rules_text}]" if which \ else f"rw [{rules_text}]" self._intermediate = [c for c, _ in steps[1:]] return new_goals, compose_rw, [line_text] if tag == "rfl": if goal[0] != goal[1]: raise TacticError(self.tr( f"rfl: strony są różne: {show_equation(goal)}", f"rfl: the sides differ: {show_equation(goal)}")) return [], lambda: Refl(goal[0]), ["rfl"] if tag == "symm": return ([(goal[1], goal[0])], lambda d: tac.symm(d) or Refl(goal[0]), ["symm"]) if tag == "trans": t = data self.check_variables(proof, [t]) self.kernel.term(t) return ([(goal[0], t), (t, goal[1])], lambda p, q: tac.trans(p, q) or Refl(goal[0]), [f"trans {show(t)}"]) if tag == "exact": rule = data self.check_rule(proof, rule) vs, l, r = self.kernel.facts[rule.name] if len(rule.args) > len(vs): raise TacticError(("too_many_args", rule.name, len(vs))) s = dict(zip(vs, rule.args)) s.update({x: "?" + x for x in vs[len(rule.args):]}) free = tuple("?" + x for x in vs[len(rule.args):]) found = tac.match_pattern(subst(l, s), goal[0], free, {}) if found is not None: found = tac.match_pattern(subst(r, s), goal[1], free, found) if found is None: raise TacticError(self.tr( f"exact {rule.text()}: fakt {self.fact_text(rule.name)}" f" nie pasuje do celu {show_equation(goal)}", f"exact {rule.text()}: the fact " f"{self.fact_text(rule.name)} does not match the goal " f"{show_equation(goal)}")) args = rule.args + tuple(found[x] for x in free) full_rule = Rule(rule.name, False, args) return ([], lambda: Inst(rule.name, args), [f"exact {full_rule.text()}"]) if tag == "ac_rfl": comm, assoc = self.ac_axioms() try: d = acm.ac_proof(self.kernel, goal[0], goal[1], comm, assoc) except TacticError: raise TacticError(self.tr( "ac_rfl: strony różnią się nie tylko kolejnością " f"i nawiasami w sumach: {show_equation(goal)}", "ac_rfl: the sides differ by more than the order and " f"brackets of sums: {show_equation(goal)}")) from None return [], lambda: d, ["ac_rfl"] if tag in ("rw_ac", "ac_simp"): self.ac_axioms() for rule in data: self.check_rule(proof, rule) texts = [r.text() for r in data] g = rb.Goal(self.kernel, goal) if tag == "rw_ac": g.rw_ac(*texts) else: g.ac_simp(*texts) return self.from_goal(g, f"{tag} [{', '.join(texts)}]") if tag == "auto" and self.theory is not None and \ "ac" in theories.THEORIES[self.theory]: return self.ac_auto(proof, goal, data[1]) if tag == "auto": return self.auto(proof, goal, *data) raise TacticError(("unknown_tactic", line)) def from_goal(self, g, line): """A step made by the Robbins tactics (robbins.Goal) in the form of the lab: the new goals and how to build the old proof.""" l, r = g.goal() left, right = g.sides if g.closing is not None or l == r: d = tac.trans(left.proof, g.closing, tac.symm(right.proof)) \ or Refl(left.start) return [], lambda: d, [line] def compose(p): return tac.trans(left.proof, p, tac.symm(right.proof)) or p return [(l, r)], compose, [line] def ac_auto(self, proof, goal, rules): """auto in a theory with A1, A2: robbins_lab.auto, the search of robbins.Goal.auto (one, then two rewrites on each side, modulo A1 and A2). A rule without ← may be used in both directions; without a list: R.""" texts = [] for text in rules or []: rule = parse_rule(text, self.notation) self.check_rule(proof, rule) texts.append(rule.text()) g = rb.Goal(self.kernel, goal) t0 = time.perf_counter() try: depth, _ = rl.auto(g, texts) except TacticError: raise TacticError(self.tr( "auto: nie znalazłem dowodu (do dwóch przepisań z każdej " "strony, modulo A1, A2) — podaj w liście instancje, np. " "auto [R (n(x)) y], albo podziel cel", "auto: no proof found (up to two rewrites on each side, " "modulo A1, A2) — give instances in the list, e.g. " "auto [R (n(x)) y], or split the goal")) from None self._auto_info = (depth, 0, time.perf_counter() - t0, "search") line = "auto" + (f" [{', '.join(rules)}]" if rules else "") return self.from_goal(g, line) def run_line(self, proof, line, log=None): """Applies a line to the first goal; an error changes nothing.""" self._intermediate = [] node = self.compound(line) if node is not None: return self.run_compound(proof, node) result = self.tactic(proof, line, log) if result is None: return None new_goals, compose, lines = result proof.apply(new_goals, compose, lines, self._intermediate) return lines # -- tactic expressions and the user's tactics (tacticals.py) -- def _define_examples(self): """The example tactics of the workshop, with the session's names of the theorems (and of the other examples).""" rename = dict(self.names) rename.update({en: self.tr(pl, en) for en, pl, *_ in EXAMPLE_TACTICS}) word = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") for en, pl, body, good, desc_pl, desc_en in EXAMPLE_TACTICS: text = word.sub(lambda m: rename.get(m.group(0), m.group(0)), body) node = self.parse_tactic(text) self.tactics[self.tr(pl, en)] = { "node": node, "text": tc.show(node), "example": True, "good": good, "description": self.tr(desc_pl, desc_en)} def drop_example(self, name): """A theorem saved before the examples existed keeps its name: the example of that name goes, with the examples that call it.""" if not self.tactics.get(name, {}).get("example"): return gone = {name} changed = True while changed: changed = False for n, info in self.tactics.items(): if info.get("example") and n not in gone and \ set(tc.calls(info["node"])) & gone: gone.add(n) changed = True for n in gone: del self.tactics[n] def tactic_nodes(self): return {n: info["node"] for n, info in self.tactics.items()} def check_step(self, text): """A basic tactic inside an expression: it must parse, and auto is not allowed (Lean has no auto; its proof is written out). A rule whose pattern leaves variables undetermined is refused: the lab rejects it, but Lean's rw would make a metavariable and go on — inside try or first the two would take different ways.""" tag, data = parse_line(text, self.notation) if tag not in ("rw", "rfl", "symm", "exact", "trans", "ac_rfl"): raise TacticError(("unknown_tactic", text)) if tag == "rw": for rule in data[1]: if rule.name in self.kernel.facts and \ len(rule.args) <= len(self.kernel.facts[rule.name][0]): free, pat, _ = pattern(self.kernel, rule) missing = [v for v in free if v not in leaves(pat)] if missing and pat not in free: raise TacticError(("undetermined", rule, pat, missing)) def parse_tactic(self, text): return tc.parse(tc.blank_comments(text), self.check_step) def compound(self, line): """The tactic expression of a line, or None for one basic tactic (or a comment). A line is an expression when it starts with a tactical or the name of a user tactic, with ( or □, or when it has ;, <;> or | outside brackets.""" s = tc.blank_comments(line).strip() if not s: return None m = NAME.match(s) word = m.group(0) if m else "" if word in TACTICALS or word in self.tactics or \ s.startswith(("(", tc.HOLE)) or tc.has_separator(s): return self.parse_tactic(s) return None def kernel_steps(self, goal, text): """What one basic step gives the kernel, for the trace: per rule the instance of the fact and the rules of the kernel it uses.""" tag, data = parse_line(text, self.notation) if tag == "rw": which, rules = data result = [] for rule in rules: try: side, path, u, v, args = find_match(self.kernel, goal, rule, which) except TacticError: break fact = Rule(rule.name, False, args) pieces = ["Inst"] + (["Symm"] if rule.backward else []) + \ (["CongrArg"] if path else []) + ["Trans"] result.append(f"{fact.text()}: {show(u)} = {show(v)} " f"[{', '.join(pieces)}]") goal, _ = rewrite(self.kernel, goal, rule, which) if goal[0] == goal[1]: result.append(f"rfl: {show(goal[0])} [Refl]") return result if tag == "rfl": return [f"{show(goal[0])} = {show(goal[1])} [Refl]"] if tag == "symm": return [f"{show_equation(goal)} ⟵ {show(goal[1])} = " f"{show(goal[0])} [Symm]"] if tag == "trans": return [f"{show(goal[0])} = {show(data)} = {show(goal[1])} " "[Trans]"] if tag == "exact": return [f"{data.text()} …: {show_equation(goal)} [Inst]"] return [] def runner(self, proof, seconds=tc.SECONDS): def step(goal, text): try: new_goals, compose, _ = self.tactic(_Focus(proof, goal), text) except ProofError as e: # e.g. a term outside the theory raise TacticError(str(e)) from None except TacticError as e: key = e.args[0] if e.args else None if isinstance(key, tuple) and key[:1] == ("undetermined",): raise tc.LimitError(key) from None raise try: info = self.kernel_steps(goal, text) except (TacticError, ProofError, RecursionError): info = [] return new_goals, compose, info self._runner = tc.Runner(step, self.tactic_nodes(), size=goal_size, depth=goal_depth, seconds=seconds) return self._runner def run_compound(self, proof, node, dry=False): """A tactic expression on the proof: all of it or nothing. The script gets one line and undo takes it back at once. dry: only run it (bl trace) — the proof does not change.""" runner = self.runner(proof) start = tc.State(tuple(proof.goals), (), proof.next_id) end, trace = runner.run(node, start) self._compound = (node, trace, runner, end) if dry: return None proof.history.append((list(proof.goals), dict(proof.nodes), list(proof.script), proof.next_id, list(proof.seen))) if proof.goals: proof.seen.append(proof.goals[0][1]) for gid, ids, compose, _ in tc.justifications(end): proof.nodes[gid] = (ids, compose) proof.goals, proof.next_id = list(end.goals), end.next_id line = tc.show(node) proof.script.append(line) return [line] def steps_used(self, end): """The basic steps of the run that made the end state, counted.""" counts = {} for *_, text in tc.justifications(end): counts[text] = counts.get(text, 0) + 1 return counts def compound_summary(self, w, runner, end): counts = self.steps_used(end) n = sum(counts.values()) listed = " · ".join(f"{s} ×{k}" if k > 1 else s for s, k in list(counts.items())[:8]) if len(counts) > 8: listed += " · …" w.add((" ⚙ ", "solver"), (self.tr( f"{self.counted(n, 'step')}", f"{self.counted(n, 'step')}"), "solver"), (": " if n else "", "dim"), (listed, "code"), (self.tr(f" (prób: {fmt_number(runner.steps, 'pl')})", f" (tried: {fmt_number(runner.steps, 'en')})"), "dim")) # analysis def step_info(self, text): """(effect on the measure, can it fail, rules) of a basic tactic for tacticals.analyse; rules: (text, effect, pattern, result).""" tag, data = parse_line(text, self.notation) if tag == "rw": rules = [] for rule in data[1]: self.check_known(rule.name) free, pat, repl = pattern(self.kernel, rule) check_pattern(rule, free, pat) rules.append((rule.text(), tc.rule_effect(pat, repl, term_size), pat, repl)) return tc.in_sequence(r[1] for r in rules), True, rules if tag == "exact": self.check_known(data.name) return tc.SHRINKS, True, [] if tag in ("rfl", "ac_rfl"): return tc.SHRINKS, True, [] if tag == "symm": return tc.SAME, False, [] if tag == "trans": return tc.GROWS, False, [] raise TacticError(("unknown_tactic", text)) def check_known(self, name): if name not in self.kernel.facts: similar = difflib.get_close_matches(name, self.all_facts(), n=3) raise TacticError(self.tr( f"nie znam faktu {name}", f"unknown fact {name}") + (self.tr(" (może: ", " (maybe: ") + ", ".join(similar) + ")" if similar else "")) def analyse_tactic(self, node): return tc.analyse(node, self.step_info, self.tactic_nodes()) def rules_text(self, rules, limit=6): """'H5: x + 0 → x (−2) · …' — the rules and the change of size.""" result, seen = [], set() for text, _, pat, repl in rules: if text in seen: continue seen.add(text) plain = {v: v[1:] for v in tc.metavariables(pat) | tc.metavariables(repl)} delta = term_size(repl) - term_size(pat) sign = "−" if delta < 0 else "+" result.append(f"{text}: {show(subst(pat, plain))} → " f"{show(subst(repl, plain))} ({sign}{abs(delta)})") if len(result) > limit: result = result[:limit] + ["…"] return " · ".join(result) def finding_text(self, finding): level, key, _, data = finding t = self.tr if key == "step": return f"{data[0]}: {self.error_text(data[1])}" if key == "unknown": return t(f"nie ma taktyki {data[0]} — zdefiniuj ją najpierw " f"(bl tactic {data[0]} := …)", f"there is no tactic {data[0]} — define it first " f"(bl tactic {data[0]} := …)") if key == "hole": return t("□ — tu brakuje taktyki", "□ — a tactic is missing here") if key == "repeat_stops": rules = self.rules_text(data[0]) return t("repeat się zatrzyma: każdy obrót zmniejsza cele (sumę " "ich rozmiarów), a liczba naturalna nie maleje bez końca" + (f" — {rules}" if rules else ""), "repeat stops: every turn makes the goals smaller (the " "sum of their sizes), and a natural number cannot go " "down forever" + (f" — {rules}" if rules else "")) if key == "repeat_may_loop": rules = self.rules_text(data[0]) if rules: return t(f"repeat może się zapętlić: {rules} — ta reguła nie " "zmienia rozmiaru celu, więc obroty mogą wracać do " "tych samych celów", f"repeat may loop: {rules} — this rule keeps the " "size of the goal, so turns can come back to the " "same goals") return t("repeat może się zapętlić: obrót może nie zmienić " "rozmiaru celów (np. symm)", "repeat may loop: a turn may keep the size of the goals " "(e.g. symm)") if key == "repeat_may_grow": rules = self.rules_text(data[0]) return t("repeat może się nie skończyć: obrót może powiększyć cele" + (f" — {rules}" if rules else " (np. trans)"), "repeat may never end: a turn may make the goals larger" + (f" — {rules}" if rules else " (e.g. trans)")) if key == "repeat_never_fails": return t(f"repeat nigdy się nie zatrzyma: {data[0]} nie zawodzi " "nawet bez celów (try, skip), a repeat kończy dopiero " "przy porażce", f"repeat never stops: {data[0]} does not fail even with " "no goals (try, skip), and repeat ends only at a " "failure") if key == "repeat_fails_only_empty": return t(f"repeat zatrzyma się tylko wtedy, gdy zamknie wszystkie " f"cele: {data[0]} nie zawodzi, dopóki jest cel (symm, " "trans, try…) — na celu, którego nie zamknie, kręci się " "w kółko", f"repeat stops only when it closes every goal: " f"{data[0]} does not fail while a goal is left (symm, " "trans, try…) — on a goal it cannot close it goes round " "forever") if key == "repeat_never_succeeds": return t(f"repeat nic nie zrobi: {data[0]} zawsze zawodzi", f"repeat does nothing: {data[0]} always fails") if key == "first_one": return t("first z jedną alternatywą to po prostu ta alternatywa", "first with one alternative is just that alternative") if key == "first_unreachable": return t(f"first: {data[0]} nie zawodzi, dopóki jest cel, " f"więc {', '.join(data[1])} nigdy nie będą próbowane — " "przenieś je wcześniej albo usuń", f"first: {data[0]} does not fail while a goal is left, " f"so {', '.join(data[1])} are never tried — move them " "earlier or remove them") if key == "try_useless": return t(f"try {data[0]}: {data[0]} nigdy nie zawodzi — try nic " "tu nie zmienia", f"try {data[0]}: {data[0]} never fails — try changes " "nothing here") if key == "greedy": kind, whole, first = data return t(f"{kind} bierze całą resztę sekwencji: {whole} — jeśli " f"miało działać tylko na {first}, dodaj nawiasy: " f"({kind} {first}); …", f"{kind} takes the whole rest of the sequence: {whole} " f"— if it was meant only for {first}, add brackets: " f"({kind} {first}); …") if key == "then_one": return t(f"{data[0]} zostawia najwyżej jeden cel, więc <;> działa " "tu jak ; — <;> przydaje się po taktyce, która robi " "kilka celów (trans t)", f"{data[0]} leaves at most one goal, so <;> works like ; " "here — <;> is for a tactic that makes several goals " "(trans t)") return key def structure_rows(self, w, node, depth=2, budget=None): budget = budget if budget is not None else [150] if budget[0] <= 0: return budget[0] -= 1 pad = " " * depth k = node.kind if k == "step": w.add((pad, ""), (node.text, "code")) elif k == "call": body = self.tactics.get(node.text) w.add((pad, ""), (node.text, "name"), (" := " + body["text"] if body else self.tr(" (nie ma takiej taktyki)", " (no such tactic)"), "dim")) else: pl, en = KIND_LABELS[k] label = self.tr(pl, en).replace("{n}", str(node.count)) w.add((pad, ""), (label, "heading" if node.parts else "code")) for p in node.parts: self.structure_rows(w, p, depth + 1, budget) if budget[0] == 0: budget[0] = -1 w.add((pad + "…", "dim")) def describe_body(self, w, name, node): t = self.tr w.add((t(" budowa:", " structure:"), "heading")) self.structure_rows(w, node) findings = self.analyse_tactic(node) if findings: w.add((t(" analiza:", " analysis:"), "heading")) marks = {"ok": ("✓ ", "ok"), "info": ("· ", "dim"), "warning": ("⚠ ", "warning"), "error": ("✗ ", "error")} for f in findings: icon, style = marks[f[0]] w.add((" ", ""), (icon, style), (self.finding_text(f), "dim" if f[0] == "info" else style)) w.add((t(" w Leanie 4 (bl lean dołącza ją do pliku):", " in Lean 4 (bl lean adds it to the file):"), "heading")) for line in self.lean_macro_text(name, node).split("\n"): w.add((" " + line, "lean")) # definitions def tactic_name_problem(self, name): t = self.tr if not TACTIC_NAME.fullmatch(name) or VARIABLE.fullmatch(name): return t("nazwa taktyki: od 2 do 30 liter, cyfr i _, na początku " "litera — i nie litera z numerem (tak wyglądają " "zmienne)", "a tactic name: 2 to 30 letters, digits and _, starting " "with a letter — and not a letter with a number (that " "is how variables look)") if name in FORBIDDEN or name in tc.KEYWORDS or name in LEAN_TACTICS \ or name in COMMANDS or name in TACTICS or name in LAB_WORDS: return t(f"{name} to słowo Leana albo laboratorium — wybierz inną " "nazwę", f"{name} is a word of Lean or of the lab — choose " "another name") if name in self.kernel.facts or name in self.names.values() or \ name in self.all_own() or (self._saved is not None and name in self._saved[0].facts): return t(f"{name} to nazwa twierdzenia — taktyka musi się nazywać " "inaczej (w Leanie byłyby tym samym słowem)", f"{name} is the name of a theorem — a tactic needs " "another one (in Lean they would be the same word)") if self.tactics.get(name, {}).get("example"): return t(f"{name} to przykład z warsztatu — nadaj swojej taktyce " "inną nazwę", f"{name} is an example of the workshop — give your " "tactic another name") return None def tactics_called(self, nodes): """The user tactics that the expressions call, also through other tactics; each comes after the tactics it calls (as Lean needs).""" order, state = [], {} def visit(name): if name in state or name not in self.tactics: return state[name] = "open" for c in tc.calls(self.tactics[name]["node"]): visit(c) order.append(name) for node in nodes: for c in tc.calls(node): visit(c) return order def script_nodes(self, lines): nodes = [] for line in lines: try: node = self.compound(line) except TacticError: node = None if node is not None: nodes.append(node) return nodes def all_own(self): """The user's theorems: of this session and, in a theory, also the Boolean ones kept aside (they come back after the theory).""" result = dict(self._saved[4]) if self._saved else {} result.update(self.own) return result def theorems_using(self, name): """What would break if the tactic changed or went away: the user's theorems that call it (also through other tactics) and the proof in progress.""" users = [thm for thm, info in self.all_own().items() if name in self.tactics_called( self.script_nodes(info["script"]))] if self.proof is not None and name in self.tactics_called( self.script_nodes(self.proof.script)): users.append(self.tr("dowód w toku", "the proof in progress")) return users def define_tactic(self, name, body, doc=""): t = self.tr problem = self.tactic_name_problem(name) if problem: return self.error(problem) try: node = self.parse_tactic(body) except TacticError as e: return self.error(self.error_text(e)) if any(n.kind == "hole" for n in tc.walk(node)): return self.error(t("w taktyce zostało □ — uzupełnij je", "the tactic still has □ — fill it in")) unknown = [c for c in tc.calls(node) if c not in self.tactics] if unknown: return self.error(t( f"nie ma taktyki {unknown[0]} — taktyka może wywoływać tylko " "taktyki zdefiniowane wcześniej", f"there is no tactic {unknown[0]} — a tactic may call only " "tactics defined before it")) if name in tc.calls(node) or name in self.tactics_called([node]): return self.error(t( f"{name} wywoływałaby samą siebie — w Leanie makro nie może " "się rozwijać bez końca", f"{name} would call itself — in Lean a macro cannot expand " "forever")) users = self.theorems_using(name) if name in self.tactics else [] if users: return self.error(t( f"z taktyki {name} korzystają twierdzenia: {', '.join(users)}" " — nowa wersja mogłaby je zepsuć; wybierz inną nazwę", f"the theorems {', '.join(users)} use the tactic {name} — a " "new version could break them; choose another name")) text = tc.show(node) doc = " ".join(str(doc or "").split())[:400] self.tactics.pop(name, None) self.tactics[name] = {"node": node, "text": text, "example": False, "doc": doc} w = Output() w.add(("✓ ", "ok"), (t("taktyka ", "tactic "), "ok"), (name, "name"), " := ", (text, "code")) w.add((t(f" od teraz możesz jej używać: {name}", f" from now on you can use it: {name}"), "dim"), (t(" · próba: ", " · dry run: "), "dim"), (f"bl trace {name}", "code", {"insert": f"bl trace {name}"})) self.describe_body(w, name, node) w.extras["tactic_new"] = {"name": name, "text": text, "doc": doc} return w def forget_tactic(self, name): t = self.tr info = self.tactics.get(name) if info is None or info.get("example"): return self.error(t(f"{name} nie jest Twoją taktyką", f"{name} is not one of your tactics")) users = self.theorems_using(name) + [ n for n, i in self.tactics.items() if n != name and name in tc.calls(i["node"])] if users: return self.error(t( f"z taktyki {name} korzystają: {', '.join(users)} — usuń je " "najpierw", f"{name} is used by: {', '.join(users)} — delete them first")) del self.tactics[name] w = Output().add(("✓ ", "ok"), (t(f"usunięta taktyka {name}", f"deleted the tactic {name}"), "ok")) w.extras["tactic_forget"] = name return w def describe_tactic(self, name): t = self.tr info = self.tactics[name] w = Output() w.add((t("Taktyka ", "Tactic "), "heading"), (name, "name"), " := ", (info["text"], "code", {"insert": info["text"]})) if info.get("example"): mark = ("✓ ", "ok") if info["good"] else ("✗ ", "error") w.add((" ", ""), mark, (t("przykład: ", "example: ") + info["description"], "dim")) self.describe_body(w, name, info["node"]) return w def lean_macro_text(self, name, node): doc = self.tactics.get(name, {}).get("doc") or \ self.tactics.get(name, {}).get("description") or "" text = tc.lean_macro(name, node, self._lean_basic) if doc: # a doc comment belongs to the macro doc = doc.replace("-/", "- /") first, _, rest = text.partition("\n") text = f"{first}\n/-- {doc} -/\n{rest}" return text def load_tactics(self, entries): """The user's tactics saved by the page: [{name, text, doc}]. A tactic may call one saved after it (a callee redefined later moves to the end), so the list is gone through until nothing changes.""" waiting = [] for entry in entries if isinstance(entries, list) else []: try: waiting.append((str(entry["name"]), str(entry["text"]), str(entry.get("doc") or ""))) except (AttributeError, KeyError, TypeError): continue accepted = [] while waiting: rest = [] for name, text, doc in waiting: if self.define_tactic(name, text, doc).error: rest.append((name, text, doc)) else: accepted.append(name) if len(rest) == len(waiting): break waiting = rest return accepted, [name for name, _, _ in waiting] # bl trace def p_trace(self, rest): t = self.tr text = rest.strip() if not text: return self.error(t( "użycie: bl trace taktyka, np. bl trace repeat (first | " "rw [H5] | rw [H6])", "usage: bl trace tactic, e.g. bl trace repeat (first | " "rw [H5] | rw [H6])")) d = self.proof if d is None: return self.error(t( "nie ma dowodu w toku — bl trace próbuje taktyki na bieżącym " "celu (zacznij od bl prove …)", "no proof in progress — bl trace tries a tactic on the " "current goal (start with bl prove …)")) try: node = self.parse_tactic(text) except TacticError as e: return self.error(self.error_text(e)) error, end = None, None try: self.run_compound(d, node, dry=True) _, trace, runner, end = self._compound except TacticError as e: error, trace, runner = e, getattr(e, "trace", None), self._runner w = Output() w.add((t("Przebieg ", "Trace of "), "heading"), (tc.show(node), "code"), (t(" próba: stan dowodu się nie zmienia", " a dry run: the proof state does not change"), "dim")) if trace is not None: self.trace_rows(w, trace, 1, [0]) if runner is not None and runner.truncated: w.add((t(" … dalszą część przebiegu pominięto", " … the rest of the trace is left out"), "dim")) if error is None: w.add((t(" wynik:", " result:"), "heading")) self.goal_rows(w, [g for _, g in end.goals]) self.compound_summary(w, runner, end) w.add((t(" zastosuj: ", " apply it: "), "dim"), (tc.show(node), "code", {"insert": tc.show(node)})) else: w.add((" ✗ ", "error"), (self.error_text(error), "error")) return w def goal_rows(self, w, goals): if not goals: w.add((" ✓ ", "ok"), (self.tr("brak celów", "no goals"), "ok")) for i, goal in enumerate(goals[:12]): w.add((" ⊢ ", "code" if i == 0 else "dim"), (show_equation(goal), "goal" if i == 0 else "dim")) if len(goals) > 12: w.add((f" … {self.counted(len(goals) - 12, 'goal')}", "dim")) def short_error(self, e): a = e.args[0] if e.args else "" if isinstance(a, tuple) and a and a[0] == "no_pattern": return self.tr(f"nie ma wzorca {show(a[2])}", f"no pattern {show(a[2])}") return self.error_text(e) def trace_label(self, tr): node = tr.node k = node.kind turn = f"[{tr.turn}] " if tr.turn else "" if k in ("step", "call"): return turn + node.text if k == "repeat": n = tr.turns or 0 return turn + "repeat — " + self.counted(n, "turn") if k == "iterate": return turn + f"iterate {node.count}" if k == "fail": return turn + tc.show(node) return turn + {"seq": ";", "then": "<;>"}.get(k, k) def trace_rows(self, w, tr, depth, counter): if counter[0] >= MAX_TRACE_ROWS: if counter[0] == MAX_TRACE_ROWS: w.add((" " * depth + "…", "dim")) counter[0] += 1 return counter[0] += 1 icon = ("✓ ", "ok") if tr.ok else ("✗ ", "error") pieces = [(" " * depth, ""), icon, (self.trace_label(tr), "code" if tr.node.kind == "step" else "name" if tr.node.kind == "call" else "dim")] if tr.node.kind == "step": if tr.ok: n, goal = tr.after pieces += [(" ⟶ ", "dim"), (show_equation(goal) if goal is not None and n >= tr.before[0] else self.tr("✓ cel zamknięty", "✓ goal closed"), "goal")] elif tr.error is not None: pieces += [(" " + self.short_error(tr.error), "dim")] elif not tr.ok and tr.error is not None and not tr.parts: pieces += [(" " + self.short_error(tr.error), "dim")] w.add(*pieces) for p in tr.parts: self.trace_rows(w, p, depth + 1, counter) # the workshop of the page (JSON) def trace_json(self, tr, budget=None, paths=None): """The trace for the page. paths: id(node) -> its path in the expression being run ("0", "0.1", …); a part of a called tactic has none (and no span: its span is in the callee's text).""" budget = budget if budget is not None else [tc.MAX_TRACE] if tr is None or budget[0] <= 0: return None budget[0] -= 1 paths = paths or {} def goal_text(snap): n, goal = snap return {"n": n, "goal": short_text(show_equation(goal)) if goal is not None else ""} path = paths.get(id(tr.node)) entry = {"kind": tr.node.kind, "label": self.trace_label(tr), "path": path, "turn": tr.turn, "turns": tr.turns, "span": list(tr.node.span) if path is not None else None, "ok": bool(tr.ok), "before": goal_text(tr.before)} if tr.after is not None: entry["after"] = goal_text(tr.after) if tr.error is not None: entry["error"] = self.short_error(tr.error) if tr.info: entry["kernel"] = tr.info parts = [self.trace_json(p, budget, paths) for p in tr.parts] entry["parts"] = [p for p in parts if p is not None] return entry def error_span(self, e): a = e.args[0] if e.args else "" if isinstance(a, tuple) and a and a[0] == "tc_parse": return [a[2], a[2] + 1] if isinstance(a, tuple) and a and a[0] == "tc_step": return [a[2], a[3]] return None def json_tactic(self, text, name=""): """The tactic being built in the workshop: its structure, the analysis and Lean (it does not run).""" try: node = self.parse_tactic(text) except TacticError as e: return json.dumps({"ok": False, "error": self.error_text(e), "span": self.error_span(e)}, ensure_ascii=False) findings = [{"level": f[0], "text": self.finding_text(f), "span": list(f[2])} for f in self.analyse_tactic(node)] name = name.strip() problem = self.tactic_name_problem(name) if name else "" own = name in self.tactics and not self.tactics[name].get("example") lean = [self.lean_macro_text(c, self.tactics[c]["node"]) for c in self.tactics_called([node]) if c != name] lean.append(self.lean_macro_text(name, node) if name and (not problem or own) else tc.show(node, self._lean_basic)) return json.dumps({ "ok": True, "text": tc.show(node), "tree": tc.tree_json(node), "findings": findings, "lean": "\n\n".join(lean), "holes": sum(1 for n in tc.walk(node) if n.kind == "hole"), "name_problem": "" if own else (problem or "")}, ensure_ascii=False) def json_define(self, name, text, doc=""): """The Tactic Lab saves a tactic with its description (it becomes the Lean doc comment of the macro).""" result = self.define_tactic(str(name).strip(), str(text), doc) reply = {"lines": result.rows, "error": result.error} reply.update(result.extras) if not result.error: reply["library"] = self.library_json() return json.dumps(reply, ensure_ascii=False) def json_trace(self, text): """A dry run of the tactic being built on the current goal.""" t = self.tr d = self.proof if d is None or not d.goals: return json.dumps({"ok": False, "trace": None, "error": t( "nie ma celu, na którym można spróbować — zacznij dowód " "(bl prove …)", "there is no goal to try it on — start a " "proof (bl prove …)") if d is None else t( "nie ma już celów — wpisz qed", "no goals left — type qed")}, ensure_ascii=False) try: node = self.parse_tactic(text) except TacticError as e: return json.dumps({"ok": False, "trace": None, "error": self.error_text(e), "span": self.error_span(e)}, ensure_ascii=False) error, end = "", None try: self.run_compound(d, node, dry=True) _, trace, runner, end = self._compound except TacticError as e: error = self.error_text(e) trace, runner = getattr(e, "trace", None), self._runner reply = {"ok": not error, "error": error, "trace": self.trace_json(trace, paths=tc.paths(node)), "truncated": bool(runner and runner.truncated), "tried": runner.steps if runner else 0, "before": [short_text(show_equation(g)) for _, g in d.goals[:6]]} if end is not None: counts = self.steps_used(end) reply["goals"] = [short_text(show_equation(g)) for _, g in end.goals[:6]] reply["n_goals"] = len(end.goals) reply["steps"] = [[s, k] for s, k in counts.items()] return json.dumps(reply, ensure_ascii=False) # -- auto and the solver -- def bfs_solver(self, facts): key = tuple(facts) if self._bfs_cache is None or self._bfs_cache[0] != key: self._bfs_cache = (key, BfsSolver(self.kernel, facts)) return self._bfs_cache[1] def steps_to_rules(self, goal, lefts, rights, limit=None): """Solver steps (each at one place) as rw / nth_rw lines which do exactly these rewrites in Lean's semantics. We cut the full chain l = c₀ → … → cₙ = r at the smallest term c_k: the left side goes c₀ → … → c_k, the right one cₙ → … → c_k (reversed steps). Both sides then get smaller. With `limit` only that many first lines are returned (a hint needs one).""" facts = self.kernel.facts full = [] # (before, after, path, name, backward, args) t = goal[0] for _, (path, name, backward, args) in lefts: after = self._step_term(t, path, name, backward, args) full.append((t, after, path, name, backward, args)) t = after for before, (path, name, backward, args) in reversed(rights): after = before # a reversed step of the right side full.append((t, after, path, name, not backward, args)) t = after chain = [goal[0]] + [k[1] for k in full] sizes = [term_size(c) for c in chain] k = max(i for i, n in enumerate(sizes) if n == min(sizes)) lefts2 = [(p[2], p[3], p[4], p[5]) for p in full[:k]] rights2 = [(p[2], p[3], not p[4], p[5]) for p in reversed(full[k:])] L, R = goal result = [] for side, steps in ((0, lefts2), (1, rights2)): for path, name, backward, args in steps: vs, l, r = facts[name] a, b = (r, l) if backward else (l, r) s = dict(zip(vs, args)) u, v = subst(a, s), subst(b, s) if side == 0: target = (replace_at(L, path, v), R) else: target = (L, replace_at(R, path, v)) line = None for k in range(len(vs) + 1): rule = Rule(name, backward, args[:k]) try: new, _ = rewrite(self.kernel, (L, R), rule) except TacticError: continue if new == target: line = ("rw", rule) break if line is None: places = [(0, p) for p in occurrences(L, u)] + \ [(1, p) for p in occurrences(R, u)] num = places.index((side, path)) + 1 line = (num, Rule(name, backward, args)) result.append(line) if limit is not None and len(result) >= limit: return result L, R = target return result def _step_term(self, t, path, name, backward, args): vs, l, r = self.kernel.facts[name] b = l if backward else r return replace_at(t, path, subst(b, dict(zip(vs, args)))) @staticmethod def lines_from_rules(steps): """Joins consecutive rw rules into one rw [ … ]; nth_rw separately.""" lines, batch = [], [] for tag, rule in steps: if tag == "rw": batch.append(rule.text()) continue if batch: lines.append(f"rw [{', '.join(batch)}]") batch = [] lines.append(f"nth_rw {tag} [{rule.text()}]") if batch: lines.append(f"rw [{', '.join(batch)}]") return lines def auto(self, proof, goal, budget, lemmas): seconds = None if budget is None else float("inf") # explicit budget = budget or 30000 t0 = time.perf_counter() method = "search" if lemmas is not None: # only these facts: breadth-first search for n in lemmas: self.check_rule(proof, Rule(n)) result, visited = self.bfs_solver(lemmas).search( *goal, budget=budget) if result is not None: result = [k for _, k in result[0]] + \ sv.reverse_steps([k for _, k in result[1]]) elif self.theory is not None: found = self.model_cex(*goal) if found is not None: raise TacticError("auto: " + self.theory_falsity_text( goal, found, bool(proof.history))) result, visited = self.theory_steps( proof, goal, budget, None if seconds else 5.0) else: cex = counterexample(*goal) if cex is not None: raise TacticError("auto: " + self.falsity_text( goal, cex, bool(proof.history))) result, method, visited = self.solver_proof( proof, goal, seconds, budget) seconds = time.perf_counter() - t0 if result is None: raise TacticError(self.tr( f"auto: nie znalazłem dowodu (odwiedzone: " f"{self.counted(visited, 'term')}, budżet " f"{fmt_number(budget, self.lang)}, " f"{self.fmt_seconds(seconds)}); " "spróbuj auto 100000, auto bez listy faktów albo podziel " "cel: trans t", f"auto: no proof found (visited " f"{self.counted(visited, 'term')}, budget " f"{fmt_number(budget, self.lang)}, " f"{self.fmt_seconds(seconds)}); " "try auto 100000, auto without a list of facts or split " "the goal: trans t")) steps = self.steps_to_rules(goal, [(None, k) for k in result], []) lines = self.lines_from_rules(steps) or ["rfl"] # the same lines through the ordinary tactics — on a copy trial = ProofState(proof.name, goal, proof.available, proof.exercise, constants=proof.constants) for line in lines: self.run_line(trial, line) if trial.goals: raise TacticError("auto: " + self.tr("wewnętrzny błąd", "internal error")) self._auto_info = (len(steps), visited, seconds, method) return [], lambda: trial.build(), lines # -- the solver: several strategies, the shortest chain -- @property def expander(self): """Expanding theorems into their proofs (solver.py). Facts in a session are only ever added, so one for the whole session.""" if self._expander is None: self._expander = sv.Expander(self.kernel, self.proofs) return self._expander @property def normal_form(self): if self._normal_form is None: self._normal_form = sv.NormalForm(self.kernel, self.names) return self._normal_form def method_text(self, p): """Where the solver took the proof from (empty: plain search).""" t, method = p.get("theorem") or "", p.get("method") if method == "undo": m = p.get("undo_count", 1) span = self.tr("kroku" if m == 1 else f"{m} kroków", "the step" if m == 1 else f"{m} steps") return self.tr( f"solver: wróć poleceniem undo — cel sprzed {span} leży na " f"dowodzie {t} z biblioteki, a stąd droga byłaby dłuższa", f"solver: go back with undo — the goal before {span} lies on " f"the library proof of {t}; from here the way would be " "longer") if method == "variant": k = p.get("solver", 1) return self.tr( f"skrypt wzorcowy ({t}) — do końca " f"{self.counted(k, 'step')}", f"the reference script ({t}): " f"{self.counted(k, 'step')} to go") if method == "reference": return self.tr( f"solver prowadzi dowodem {t} z biblioteki (tylko faktami " "dozwolonymi w ćwiczeniu)", f"the solver follows the library proof of {t} (only with " "the facts allowed in the exercise)") if method == "library" and t: return self.tr( f"cel to twierdzenie {t} z biblioteki — solver prowadzi jego " "dowodem, rozwiniętym do faktów dozwolonych w ćwiczeniu", f"the goal is the library theorem {t} — the solver follows " "its proof, expanded to the facts allowed in the exercise") if method == "normal_form": return self.tr( "solver: dowód przez postać normalną — obie strony stają się " "sumą mintermów; istnieje dla każdej prawdziwej równości", "solver: a proof via the normal form — both sides become a " "sum of minterms; it exists for every true equation") return "" def falsity_text(self, goal, cex, undo=True): vals = ", ".join(f"{k} = {v}" for k, v in cex.items()) or "—" return self.tr( f"ten cel jest fałszywy w algebrze {{0, 1}} ({vals}: lewa " f"{value(goal[0], cex)}, prawa {value(goal[1], cex)}), więc " "nie ma dowodu" + (" — cofnij krok (undo)" if undo else ""), f"this goal is false in the algebra {{0, 1}} ({vals}: left " f"{value(goal[0], cex)}, right {value(goal[1], cex)}), so it " "has no proof" + (" — undo the step (undo)" if undo else "")) def reference_rest(self, proof, goal, allowed): """The rest of the library proof in an exercise: when both sides of the goal lie on the (flattened) reference proof of the statement, returns the piece of the chain between them.""" name = proof.exercise if not name or name not in self.proofs: return None vs, l, r = self.kernel.facts[name] ren = {x: "?" + x for x in vs} free = tuple(ren.values()) s = tac.match_pattern(subst(l, ren), proof.statement[0], free, {}) if s is not None: s = tac.match_pattern(subst(r, ren), proof.statement[1], free, s) if s is None or len(s) != len(free): return None args = tuple(s["?" + x] for x in vs) steps = self.expander.expand([((), name, False, args)], allowed) terms = sv.replay(self.kernel, proof.statement[0], steps) return sv.segment(terms, steps, goal) def solver_proof(self, proof, goal, seconds=0.25, budget=4000): """The shortest chain l → r: (steps, method, visited) or (None, None, visited).""" candidates, visited = self.solver_proofs(proof, goal, seconds, budget) if not candidates: return None, None, visited return candidates[0][0], candidates[0][1], visited def solver_proofs(self, proof, goal, seconds=0.25, budget=4000): """Chains l → r from several strategies, the shortest first: ([(steps, method), …], visited). Methods: "search" (breadth-first, the allowed facts — short, natural proofs), "reference" (the rest of the library proof in an exercise), "library" (the goal is an instance of a theorem), "normal_form" (the normal form: a proof of every true equation). Steps with theorems that may not yet be used in the exercise are already expanded into their proofs, and the chain has no loops. The plan, i.e. the chain chosen at the previous hint (proof.plans), wins ties: whoever follows the hints follows one proof, and the length of the rest of the proof drops with every step — the hints cannot go round in circles.""" allowed = frozenset(proof.available) candidates = [] order = ("plan", "search", "reference", "library", "normal_form") deadline = sv.Deadline(None if seconds is None else max(0.5, 2 * seconds)) # in an exercise, expanded theorems may lead through huge # terms; library proofs grow at most 3 times goal_size = term_size(goal[0]) + term_size(goal[1]) bound = 3 * goal_size + 40 if proof.exercise else sv.SIZE_LIMIT def consider(steps, method, thm="", tag=None): if steps is None: return try: steps = self.expander.expand(steps, allowed, deadline) terms = sv.replay(self.kernel, goal[0], steps) except (sv.TooBig, KeyError, ValueError): return if terms[-1] == goal[1]: steps = sv.without_loops(terms, steps) if proof.exercise and max(map(term_size, sv.replay( self.kernel, goal[0], steps))) > bound: return candidates.append((len(steps), order.index(tag or method), len(candidates), steps, method, thm)) # first the fast and sure strategies… for steps, terms, method, thm in proof.plans: consider(sv.segment(terms, steps, goal), method, thm, "plan") try: consider(self.reference_rest(proof, goal, allowed), "reference", proof.exercise) except (sv.TooBig, KeyError, ValueError): pass for step in sv.instances(self.kernel, goal): consider([step], "library", "" if step[1] in allowed else step[1]) try: consider(self.normal_form.proof(*goal, deadline), "normal_form") except (sv.TooBig, RecursionError): pass # …then breadth-first search for a shorter, natural proof; when # there is a proof already, at most a second (unless timed) if seconds is None and candidates: seconds = 1.0 forbidden = ({c[0] for c in proof.seen} - {goal[0]}, {c[1] for c in proof.seen} - {goal[1]}) result, visited = self.bfs_solver(proof.available).search( *goal, budget=budget, seconds=seconds, forbidden=forbidden) if result is not None: consider([k for _, k in result[0]] + sv.reverse_steps([k for _, k in result[1]]), "search") candidates.sort() # ties: the order of the strategies seen_keys, result = set(), [] for _, _, _, steps, method, thm in candidates: key = tuple(steps) if key not in seen_keys: seen_keys.add(key) result.append((steps, method, thm)) return result, visited # -- suggestions -- def kind(self, goal, new): if new[0] == new[1]: return "closes" before = term_size(goal[0]) + term_size(goal[1]) after = term_size(new[0]) + term_size(new[1]) return "shrinks" if after < before else "same" if after == before \ else "grows" def suggestions(self, proof, goal): """All rewrites of the goal by the facts available in the proof. Returns (sorted suggestions, {fact: {"forward": what rw [h] does, "backward": what rw [← h] does, "best": the best rewrite by the fact}}). Every instance of a pattern in the goal gives a suggestion of its own: the first is rw [h], the others need explicit arguments; a repeated atom (a variable, 0, 1) gets nth_rw k.""" key = (goal, tuple(proof.available)) if self._hint_cache[0] == key: return self._hint_cache[1] if term_size(goal[0]) + term_size(goal[1]) > MAX_HINT_SIZE: return [], {} L, R = goal pool = list(proof.variables) or ["0", "1"] subterms = [] for t in (L, R): for _, u in positions(t): if u not in subterms: subterms.append(u) collected, facts = [], {} if L == R: collected.append(self._hint_entry("rfl", None, "closes", None, [], "tactic", 0, -1)) # in a Robbins theory the order of summands is the job of ac_rfl, # rw_ac and ac_simp: rewrites by A1 and A2 would only be noise skip = set(theories.THEORIES[self.theory].get("ac", ())) \ if self.theory is not None else set() for idx, name in enumerate(proof.available): if name in skip: continue vs, l, r = self.kernel.facts[name] ren = {x: "?" + x for x in vs} free = tuple(ren.values()) found = tac.match_pattern(subst(l, ren), L, free, {}) if found is not None: found = tac.match_pattern(subst(r, ren), R, free, found) if found is not None: rule = Rule(name, False, tuple(found[x] for x in free)) collected.append(self._hint_entry( f"exact {rule.text()}", rule, "closes", None, [], self.source(name), len(vs), idx)) info = {} for backward, (a, b) in ((False, (l, r)), (True, (r, l))): p = self._hint_plain(goal, name, backward, idx) if p is not None: info["backward" if backward else "forward"] = p pat, repl = subst(a, ren), subst(b, ren) extra = [v for v in free if v not in leaves(pat)] if pat in free: # a bare variable: every subterm, candidates = [{pat: u} for u in sorted( # sides first subterms, key=lambda u: (u not in goal, -term_size(u)))] else: candidates = [] for u in subterms: s = tac.match_pattern(pat, u, free, {}) if s is not None: candidates.append(s) seen_keys, growing = set(), 0 for s in candidates: choices = list(product(pool, repeat=len(extra)))[:4] for choice in choices: s2 = dict(s) s2.update(zip(extra, choice)) u = subst(pat, s2) args = tuple(s2[x] for x in free) if (u, args) in seen_keys or growing >= 3: continue seen_keys.add((u, args)) for p in self._hint_instance( goal, name, backward, args, u, subst(repl, s2), idx): if p["kind"] == "grows": if growing >= 3: continue growing += 1 collected.append(p) old = info.get("best") if old is None or KINDS.index(p["kind"]) < \ KINDS.index(old["kind"]): info["best"] = p if info: facts[name] = info result = (self._rank_hints(collected), facts) self._hint_cache = (key, result) return result def _hint_plain(self, goal, name, backward, idx): """What rw [h] (or rw [← h]) does without arguments — or None.""" rule = Rule(name, backward) try: new, _ = rewrite(self.kernel, goal, rule) u = find_match(self.kernel, goal, rule)[2] except TacticError: return None if new == goal: return None return self._hint_entry(f"rw [{rule.text()}]", rule, self.kind(goal, new), new, self._paths(goal, u), self.source(name), 0, idx) @staticmethod def _paths(goal, u): return [path_id(0, p) for p in occurrences(goal[0], u)] + \ [path_id(1, p) for p in occurrences(goal[1], u)] def _hint_instance(self, goal, name, backward, args, u, v, idx): """Suggestions for one instance u → v: rw (all occurrences) with the shortest arguments, or nth_rw k for a repeated atom.""" L, R = goal paths = self._paths(goal, u) if isinstance(u, str) and len(paths) > 1: result = [] for k, sc in enumerate(paths[:3], start=1): rule = Rule(name, backward, args) try: new, _ = rewrite(self.kernel, goal, rule, k) except TacticError: continue result.append(self._hint_entry( f"nth_rw {k} [{rule.text()}]", rule, self.kind(goal, new), new, [sc], self.source(name), len(args) + 1, idx)) return result new = (replace_all(L, u, v), replace_all(R, u, v)) if new == goal: return [] for k in range(len(args) + 1): rule = Rule(name, backward, args[:k]) try: result, _ = rewrite(self.kernel, goal, rule) except TacticError: continue if result == new: return [self._hint_entry( f"rw [{rule.text()}]", rule, self.kind(goal, new), new, paths, self.source(name), len(rule.args), idx)] return [] @staticmethod def _hint_entry(tactic, rule, kind, new, paths, source, nargs, idx): return {"tactic": tactic, "kind": kind, "rule": rule.text() if rule else "", "fact": rule.name if rule else "", "backward": bool(rule and rule.backward), "result": show_equation(new) if new and kind != "closes" else "", "size_after": term_size(new[0]) + term_size(new[1]) if new else 0, "paths": paths, "source": source, "nargs": nargs, "index": idx} @staticmethod def _rank_hints(entries): def rank(p): k = p["kind"] if k == "closes": g = 0 elif p.get("solver"): g = 1 elif k == "shrinks": g = 3 if p["source"] == "axiom" else 2 else: g = 4 if k == "same" else 5 after = 0 if k == "closes" else p["size_after"] return (g, p["tactic"].startswith("exact"), p["nargs"], after, p["backward"], p["index"]) result, seen_keys, closing = [], set(), 0 for p in sorted(entries, key=rank): if p["kind"] == "closes": if closing >= 3 or ("z", p["fact"]) in seen_keys: continue closing += 1 seen_keys.add(("z", p["fact"])) else: if p["result"] in seen_keys: continue seen_keys.add(p["result"]) result.append(p) return result def solver_suggestion(self, proof, goal, seconds=0.25, budget=4000): """The first step of the shortest proof the solver found: (suggestion or None, visited). The suggestion has the fields "solver" (the number of steps), "method" and "theorem" (where the proof comes from). A step that takes a side of the goal back to an earlier form is taken only when no other proof avoids it.""" if term_size(goal[0]) + term_size(goal[1]) > MAX_HINT_SIZE: return None, 0 if self.theory is not None: return self.theory_suggestion(proof, goal, seconds, budget) undo_hint = self._hint_undo(proof) if undo_hint is not None: return undo_hint, 0 candidates, visited = self.solver_proofs(proof, goal, seconds, budget) choice = None # the shortest; on a tie, not reverting for steps, method, thm in candidates: if choice is not None and len(steps) > len(choice[1]): break p = self._first_step(proof, goal, steps, method, thm) if p is None: continue if choice is None or (choice[0]["reverts"] and not p["reverts"]): choice = (p, steps, method, thm) if not p["reverts"]: break undo_hint = self.undo_suggestion( proof, len(choice[1]) if choice else float("inf")) if undo_hint is not None: return undo_hint, visited if choice is None: return None, visited p, steps, method, thm = choice terms = sv.replay(self.kernel, goal[0], steps) proof.plans = (proof.plans + [(steps, terms, method, thm)])[-8:] return p, visited def theory_steps(self, proof, goal, budget, seconds=None): """Breadth-first search with the facts of the proof: (steps or None, visited) — the only strategy in another theory.""" result, visited = self.bfs_solver(proof.available).search( *goal, budget=budget, seconds=seconds) if result is None: return None, visited return [k for _, k in result[0]] + \ sv.reverse_steps([k for _, k in result[1]]), visited def theory_suggestion(self, proof, goal, seconds=0.25, budget=4000): entry = self.variant_suggestion(proof, goal) if entry is not None: return entry, 0 if self.theory is not None and "ac" in theories.THEORIES[self.theory]: return None, 0 # breadth-first search is hopeless here steps, visited = self.theory_steps(proof, goal, budget, seconds) if not steps: return None, visited return self._first_step(proof, goal, steps, "search", ""), visited def undo_suggestion(self, proof, length): """An exercise in which the student left the path: when after m undos the first goal lies on the reference proof and m + the rest of that proof < length (the shortest proof from here), the hint is undo.""" if not proof.exercise or not proof.history: return None allowed = frozenset(proof.available) for m, state in enumerate(reversed(proof.history), start=1): if m >= length or not state[0]: break c = state[0][0][1] try: k = self.reference_rest(proof, c, allowed) except (sv.TooBig, KeyError, ValueError): continue if k is not None and m + len(k) < length: proof.undo_target = (len(proof.history) - m, c, len(k)) return self._hint_undo(proof) return None def _hint_undo(self, proof): """The undo hint from the remembered goal to go back to (proof.undo_target: the length of the history, the goal there and the length of the proof from there) — as long as the student follows it, the solver keeps going back to that goal.""" if proof.undo_target is None: return None T, c, rest = proof.undo_target h = proof.history if not (T < len(h) and h[T][0] and h[T][0][0][1] == c): proof.undo_target = None return None m = len(h) - T next_goal = h[-1][0][0][1] if h[-1][0] else ("", "") return {"tactic": "undo", "kind": "same", "rule": "", "fact": "", "backward": False, "result": show_equation(next_goal) if h[-1][0] else "", "size_after": term_size(next_goal[0]) + term_size(next_goal[1]), "paths": [], "source": "", "nargs": 0, "index": -1, "solver": m + rest, "method": "undo", "theorem": proof.exercise, "undo_count": m, "reverts": False} def _first_step(self, proof, goal, steps, method, thm): lines = self.steps_to_rules(goal, [(None, k) for k in steps], [], limit=1) if not lines: return None tag, rule = lines[0] which = None if tag == "rw" else tag tactic_text = f"rw [{rule.text()}]" if which is None else \ f"nth_rw {which} [{rule.text()}]" new, _ = rewrite(self.kernel, goal, rule, which) side, path, u, _, _ = find_match(self.kernel, goal, rule, which) paths = self._paths(goal, u) if which is None else \ [path_id(side, path)] p = self._hint_entry(tactic_text, rule, self.kind(goal, new), new, paths, self.source(rule.name), len(rule.args), -1) p["solver"] = len(steps) p["method"], p["theorem"] = method, thm (p,), _ = self.mark_reverting(goal, [p], proof.seen) return p # -- the library -- def _replay_library(self): """Every library theorem through the kernel, in the language of the session (names, descriptions, section titles, scripts).""" errors = [] pl = self.lang == "pl" for section in library.SECTIONS: record = {"title": section["title_pl" if pl else "title"]} for thm in section["theorems"]: name = self.names[thm["name"]] l, r = equation(thm["equation"]) proof = ProofState(name, (l, r), self.all_facts()) script = localize_script(thm["script"], self.lang, self.names) t0 = time.perf_counter() try: for line in script: self.run_line(proof, line) if proof.goals: raise TacticError(self.tr( f"zostały cele: {proof.goals}", f"goals remain: {proof.goals}")) d = proof.build() self.kernel.theorem(name, proof.variables, l, r, d) except (TacticError, ProofError) as e: errors.append((name, self.error_text(e))) continue self.proofs[name] = d self.order.append(name) self.lib[name] = { "section": record, "id": thm["name"], "statement": (l, r), "script": script, "short": " ".join(thm["equation"].split()) if has_abbreviations(thm["equation"]) else "", "variables": proof.variables, "description": thm["desc_pl" if pl else "desc_en"], "time": time.perf_counter() - t0, "steps": self.count_steps(proof.script)} self.lib_index.setdefault(canonical(l, r), name) return errors @staticmethod def count_steps(script): n = 0 for line in script: try: tag, data = parse_line(line) except TacticError: # a tactic expression: one step n += 1 continue if tag == "rw": n += len(data[1]) elif tag != "nothing": n += 1 return n def trace(self, name): """The trace of a proof: (step, goals after it), rule by rule.""" info = self.lib.get(name) or self.own.get(name) available = self.all_facts() available = available[:available.index(name)] proof = ProofState(name, info["statement"], available) result = [] for line in info["script"]: log = [] try: if self.run_line(proof, line, log) is None: continue except TacticError as e: result.append((strip_comment(line) + " ✗ " + self.error_text(e), [])) break if self.compound(line) is not None: result.append((strip_comment(line), [c for _, c in proof.goals])) continue tag, data = parse_line(line) goals = [c for _, c in proof.goals] if tag == "rw": prefix = f"nth_rw {data[0]} " if data[0] else "" for i, (desc, goal) in enumerate(log): last = i == len(log) - 1 result.append((prefix + desc, goals if last else [goal])) else: result.append((strip_comment(line), goals)) return result # -- commands -- def run(self, line): """Runs one command or tactic; returns an Output.""" s = " ".join(line.strip().split()) if "\n" not in line else \ line.strip() if not s: return Output() words = s.split(" ") if words[0] == "bl": if len(words) == 1: return self.p_help() command, rest = words[1], " ".join(words[2:]) method = { "help": self.p_help, "axioms": self.p_axioms, "lib": self.p_lib, "prove": self.p_prove, "lean": self.p_lean, "model": self.p_model, "tactic": self.p_tactic, "kernel": self.p_kernel, "forget": self.p_forget, "theory": self.p_theory, "replay": self.p_replay, "trace": self.p_trace}.get(command) if method is None: similar = difflib.get_close_matches(command, COMMANDS, 1) return self.error(self.tr( f"nie ma polecenia bl {command}", f"there is no command bl {command}") + ( f" — bl {similar[0]}?" if similar else " (bl help)")) return method(rest) if command != "help" else method() if s in ("help", "?"): return self.p_help() if s == "qed": return self.p_qed() if s == "undo": return self.p_undo() if s == "restart": return self.p_restart() if s == "abort": return self.p_abort() if s == "script": return self.p_script() if s == "hint": return self.p_hint() if s in ("clear", "cls"): return Output() if self.proof is None: if words[0] in TACTICS or words[0] in TACTICALS or \ words[0] in self.tactics or \ words[0].startswith(("rw[", "(", tc.HOLE)): return self.error(self.tr( "nie ma dowodu w toku — zacznij od bl prove …", "no proof in progress — start with bl prove …")) similar = difflib.get_close_matches( words[0], list(TACTICS) + list(TACTICALS) + list(self.tactics) + ["qed", "undo", "hint", "bl"], 1) return self.error(self.tr( f"nie znam polecenia {words[0]!r}", f"unknown command {words[0]!r}") + ( f" — {similar[0]}?" if similar else " (bl help)")) return self.p_tactic_step(s) def show_goals(self, w, proof): if not proof.goals: w.add((" ✓ ", "ok"), (self.tr( "brak celów — wpisz qed, a jądro sprawdzi cały dowód", "no goals — type qed and the kernel checks the whole proof"), "ok")) return n = len(proof.goals) if n > 1: w.add((f" {self.counted(n, 'goal')}", "dim")) for i, (_, goal) in enumerate(proof.goals): w.add((" ⊢ ", "code" if i == 0 else "dim"), (show_equation(goal), "goal" if i == 0 else "dim")) def p_tactic_step(self, s): proof = self.proof log = [] self._auto_info = None self._compound = None try: lines = self.run_line(proof, s, log) except (TacticError, ProofError) as e: w = self.error(self.error_text(e)) if getattr(e, "trace", None) is not None: w.add((" ", ""), (self.tr("gdzie zawiodła: ", "where it failed: "), "dim"), (f"bl trace {s}", "code", {"insert": f"bl trace {s}"})) return w w = Output() if lines is None: return w if self._compound is not None: _, _, runner, end = self._compound self.compound_summary(w, runner, end) elif self._auto_info: k, visited, seconds, method = self._auto_info origin = {"reference": self.tr("dowód z biblioteki", "a library proof"), "library": self.tr("dowód z biblioteki", "a library proof"), "normal_form": self.tr("postać normalna", "the normal form")}.get(method) w.add((" auto: ", "solver"), (self.tr( f"dowód w {self.in_steps(k)} (odwiedzone: " f"{self.counted(visited, 'term')}, " f"{self.fmt_seconds(seconds)}", f"proof in {self.counted(k, 'step')} (visited " f"{self.counted(visited, 'term')}, " f"{self.fmt_seconds(seconds)}") + (f"; {origin})" if origin else ")"), "solver")) for line in lines: w.add((" ", ""), (line, "code", {"insert": line})) elif len(log) > 1: for desc, goal in log[:-1]: w.add((" · ", "dim"), (desc, "dim"), (" ", ""), (show_equation(goal), "dim")) self.show_goals(w, proof) return w def p_help(self, *_): w = Output() t = self.tr w.add((t("Boole Lab — algebra Boole'a w jądrze z wykładu 3", "Boole Lab — Boolean algebra in the kernel of Lecture 3"), "heading")) w.add((t("Polecenia", "Commands"), "heading")) rows = [ ("bl prove nazwa : równość", "bl prove name : equation", "zacznij dowód, np. bl prove moje : x * x = x", "start a proof, e.g. bl prove mine : x * x = x", "bl prove "), ("bl prove równość", "bl prove equation", "to samo, nazwa nadana automatycznie", "the same, with an automatic name", "bl prove "), ("bl prove nazwa", "bl prove name", "ćwiczenie: twierdzenie z biblioteki od nowa", "exercise: re-prove a library theorem", "bl prove "), ("bl axioms", "bl axioms", "aksjomaty Huntingtona H1–H8", "Huntington's axioms H1–H8", "bl axioms"), ("bl lib [nazwa]", "bl lib [name]", "biblioteka twierdzeń / jedno twierdzenie z dowodem", "the theorem library / one theorem with its proof", "bl lib "), ("bl lean nazwa [full]", "bl lean name [full]", "ten sam dowód w Leanie 4 (full: cały plik)", "the same proof in Lean 4 (full: a whole file)", "bl lean "), ("bl model równość", "bl model equation", "czy równość zachodzi w algebrze {0, 1}?", "does the equation hold in the algebra {0, 1}?", "bl model "), ("bl tactic [nazwa]", "bl tactic [name]", "opis taktyki", "how a tactic works", "bl tactic "), ("bl kernel", "bl kernel", "co sprawdza jądro, gdzie jest kod", "what the kernel checks, where its code is", "bl kernel"), ("bl forget nazwa", "bl forget name", "usuń własne twierdzenie", "delete your own theorem", "bl forget "), ("bl theory [nazwa]", "bl theory [name]", "inne aksjomaty: DN1, Sh1, mediana; modele skończone", "other axioms: DN1, Sh1, the median; finite models", "bl theory "), ("bl tactic nazwa := t", "bl tactic name := t", "własna taktyka (w Leanie: macro); budowa i analiza", "your own tactic (in Lean: a macro); structure and analysis", "bl tactic "), ("bl trace taktyka", "bl trace tactic", "próba na bieżącym celu, przebieg krok po kroku", "a dry run on the current goal, step by step", "bl trace "), ("bl replay mann | mccune", "bl replay mann | mccune", "dowód Robbinsa krok po kroku (wariant Manna / McCune'a)", "the Robbins proof step by step (Mann's / McCune's variant)", "bl replay "), ] for pl, en, desc_pl, desc_en, insert in rows: w.add((" ", ""), (t(pl, en).ljust(28), "code", {"insert": insert}), (t(desc_pl, desc_en), "dim")) w.add((t("Taktyki (działają na pierwszym celu; zapis jak w Leanie 4)", "Tactics (act on the first goal; written as in Lean 4)"), "heading")) tactics = [ ("rw [H6, ← H7 x, H2 n(x) y]", "rw [", "przepisywanie, na końcu rfl", "rewriting, then rfl"), ("nth_rw k [h]", "nth_rw ", "przepisz tylko k-te dopasowanie", "rewrite only the k-th match"), ("rfl · symm · trans t", "trans ", "zwrotność, symetria, przechodniość", "reflexivity, symmetry, transitivity"), ("exact h args", "exact ", "cel jest instancją faktu h", "the goal is an instance of the fact h"), (t("auto [budżet] [[h, …]]", "auto [budget] [[h, …]]"), "auto", "solver: dowód każdej prawdziwej równości", "solver: a proof of every true equation"), ("first | t₁ | t₂ · try t", "first | ", "pierwsza, która się uda · próba bez ryzyka", "the first that succeeds · a safe attempt"), ("repeat t · iterate n t", "repeat ", "powtarzaj, dopóki się udaje · n razy", "again while it succeeds · n times"), ("t₁; t₂ · t₁ <;> t₂ · all_goals t", "all_goals ", "po kolei · na każdym nowym celu · na wszystkich", "in turn · on every new goal · on all goals"), ("ac_rfl · rw_ac [h] · ac_simp [h]", "rw_ac [", "modulo A1, A2 (bl theory robbins)", "modulo A1, A2 (bl theory robbins)"), ] for cmd, insert, desc_pl, desc_en in tactics: w.add((" ", ""), (cmd.ljust(28), "code", {"insert": insert}), (t(desc_pl, desc_en), "dim")) w.add((t("Dowód", "Proof"), "heading")) w.add((" ", ""), ("qed", "code"), t(" jądro sprawdza dowód · ", " the kernel checks the proof · "), ("undo", "code"), " · ", ("restart", "code"), " · ", ("abort", "code"), " · ", ("script", "code"), " · ", ("hint", "code"), " · ", ("clear", "code")) w.add((t(" TAB albo → przyjmuje podpowiedź · ↑/↓ historia · " "kolory: zielony zamyka cel, niebieski go zmniejsza, " "bursztynowy nie zmienia rozmiaru, szary powiększa", " TAB or → accepts the suggestion · ↑/↓ history · colors: " "green closes the goal, blue shrinks it, amber keeps its " "size, grey grows it"), "dim")) return w def p_axioms(self, *_): if self.theory is not None: return self.theory_card() w = Output() w.add((self.tr("Aksjomaty Huntingtona (1904): algebra Boole'a jako " "teoria równościowa", "Huntington's axioms (1904): Boolean algebra as an " "equational theory"), "heading")) for name in self.axioms: w.add((" ", ""), (name.ljust(4), "name", {"insert": f"rw [{name}]"}), (self.fact_text(name), "goal")) w.add((self.tr(" W Leanie: pola klasy AlgebraBoolea " "(lean/Wyklad03.lean).", " In Lean: fields of the class HuntingtonAlgebra " "(lean/Lecture03.lean)."), "dim")) return w def p_lib(self, rest=""): rest = rest.strip() if rest: return self.lib_one(rest) w = Output() n = len(self.order) w.add((self.tr(f"Biblioteka: {self.counted(n, 'theorem')}, każde " "przyjęte przez jądro przy starcie", f"Library: {self.counted(n, 'theorem')}, each " "accepted by the kernel at startup"), "heading")) sections = [] for name in self.order: s = self.lib[name]["section"] if s not in sections: sections.append(s) for s in sections: w.add((s["title"], "heading")) for name in self.order: info = self.lib[name] if info["section"] is not s: continue self._lib_row(w, name, info) if self.own: w.add((self.tr("Twoje twierdzenia", "Your theorems"), "heading")) for name, info in self.own.items(): self._lib_row(w, name, info) w.add((self.tr(" bl lib nazwa — dowód i ślad; kliknij nazwę", " bl lib name — the proof and its trace; click a " "name"), "dim")) return w def _lib_row(self, w, name, info): assumed = sorted(self.kernel.assumptions[name], key=lambda a: self.axioms.index(a)) name_width = max(map(len, self.order + list(self.own))) + 2 text = info.get("short") or show_equation(info["statement"]) w.add((" ✓ ", "ok"), (name.ljust(name_width), "name", {"run": f"bl lib {name}"}), (text.ljust(max(42, len(text) + 2)), "goal"), (self.counted(info["steps"], "step").ljust(11), "dim"), (" ".join(assumed), "dim")) def lib_one(self, name): if name in self.axioms: w = Output() w.add((name, "name"), " : ", (self.fact_text(name), "goal"), (self.tr(" aksjomat", " axiom"), "dim")) return w info = self.lib.get(name) or self.own.get(name) if info is None: similar = difflib.get_close_matches(name, self.all_facts(), 3) return self.error(self.tr(f"nie ma twierdzenia {name}", f"there is no theorem {name}") + ( " — " + ", ".join(similar) + "?" if similar else "")) w = Output() t = self.tr w.add((name, "name"), " : ", (info.get("short") or show_equation(info["statement"]), "goal"), (" ✓ " + t("przyjęte przez jądro", "accepted by the kernel"), "ok")) if info.get("short"): w.add((t(" po rozwinięciu skrótów: ", " with the abbreviations expanded: "), "dim"), (show_equation(info["statement"]), "dim")) if name in self.lib: s = info["section"] w.add((t(" sekcja: ", " section: ") + s["title"] + " — " + info["description"], "dim")) w.add((t(f" skrypt ({self.counted(info['steps'], 'step')}):", f" script ({self.counted(info['steps'], 'step')}):"), "heading")) for line in info["script"]: style = "dim" if line.startswith("--") else "code" w.add((" ", ""), (line, style)) w.add((t(" przebieg:", " trace:"), "heading")) trace_rows = self.trace(name) width = max([len(o) for o, _ in trace_rows] + [0]) + 2 w.add((" " + " " * (width + 2), ""), (show_equation(info["statement"]), "goal")) for desc, goals in trace_rows: goals_text = " | ".join(show_equation(c) for c in goals) or \ t("✓ brak celów", "✓ no goals") w.add((" ", ""), (desc.ljust(width), "code"), ("⟶ ", "dim"), (goals_text, "goal" if goals else "ok")) d = self.proofs[name] assumed = sorted(self.kernel.assumptions[name], key=lambda a: self.axioms.index(a)) used = sorted(used_facts(d), key=self.all_facts().index) w.add((t(" założenia (jak #print axioms): ", " assumptions (like #print axioms): "), "dim"), (", ".join(assumed), "code")) w.add((t(" korzysta z: ", " uses: "), "dim"), *self._name_list(used)) w.add((t(f" drzewo dowodu dla jądra: {self.counted(size(d), 'node')}", f" proof tree for the kernel: " f"{self.counted(size(d), 'node')}"), "dim")) w.add((" ", ""), (f"bl lean {name}", "code", {"run": f"bl lean {name}"}), (t(" — ten sam dowód w Leanie · ", " — the same proof in Lean · "), "dim"), (f"bl prove {name}", "code", {"run": f"bl prove {name}"}), (t(" — udowodnij sam", " — prove it yourself"), "dim")) return w def _name_list(self, names): result = [] for i, n in enumerate(names): if i: result.append((", ", "dim")) action = {"run": f"bl lib {n}"} if n not in self.axioms \ else None result.append((n, "name", action) if action else (n, "name")) return result def p_prove(self, rest): rest = rest.strip() t = self.tr m = re.fullmatch(r"([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+)", rest) exercise = None if m: name, text = m.group(1), m.group(2) elif NAME.fullmatch(rest) and rest in self.lib: name, text = rest, show_equation(self.lib[rest]["statement"]) elif NAME.fullmatch(rest) and self.variant_step(rest): name, text = rest, self.variant_step(rest)[2]["statement"] elif "=" in rest: name, text = None, rest else: return self.error(t( "użycie: bl prove nazwa : równość (np. bl prove moje : " "x * x = x) albo bl prove nazwa_z_biblioteki", "usage: bl prove name : equation (e.g. bl prove mine : " "x * x = x) or bl prove library_name")) try: l, r = self.parse_equation(text) if self.theory is not None: self.kernel.term(l), self.kernel.term(r) except (SyntaxError, ValueError, IndexError, ProofError): return self.error(t( f"nie rozumiem równości {text!r} — zapis: " f"{self.notation_text()}, nawiasy", f"cannot parse the equation {text!r} — notation: " f"{self.notation_text()}, parentheses")) if term_size(l) + term_size(r) > MAX_STATEMENT: return self.error(t( f"równość jest za długa (najwyżej {MAX_STATEMENT} węzłów) — " "podziel ją na lematy", f"the equation is too long (at most {MAX_STATEMENT} nodes) — " "split it into lemmas")) vs = equation_vars(l, r) bad = [v for v in vs if not VARIABLE.fullmatch(v)] if bad: return self.error(t( f"zmienne to litery z ewentualnym numerem (x, y, a1); " f"popraw: {', '.join(bad)}", f"variables are letters with an optional number (x, y, a1); " f"fix: {', '.join(bad)}")) taken = False ex = self.lib_index.get(canonical(l, r)) or \ self.lib_index.get(canonical(r, l)) if name is None: i = 1 while f"{t('tw', 'thm')}{i}" in self.kernel.facts or \ f"{t('tw', 'thm')}{i}" in self.tactics: i += 1 name = f"{t('tw', 'thm')}{i}" elif name in self.kernel.facts: if name in self.lib and ex == name: taken = True else: return self.error(t( f"nazwa {name} jest już zajęta — wybierz inną", f"the name {name} is taken — choose another")) elif name in self.tactics: return self.error(t( f"{name} to nazwa taktyki — twierdzenie musi się nazywać " "inaczej", f"{name} is the name of a tactic — a theorem needs another " "name")) elif (name in FORBIDDEN and not (self._replaying and name in LEGACY_NAMES)) or \ VARIABLE.fullmatch(name): return self.error(t( f"{name} nie może być nazwą twierdzenia (słowo Leana, " "polecenie albo nazwa zmiennej)", f"{name} cannot be a theorem name (a Lean keyword, a " "command or a variable name)")) available = self.all_facts() if ex: available = self.axioms + \ self.order[:self.order.index(ex)] w = Output() if self.proof is not None: w.add((t(f" (porzucam dowód {self.proof.name})", f" (abandoning the proof of {self.proof.name})"), "dim")) command = f"bl prove {name} : {show(l)} = {show(r)}" self.proof = ProofState(name, (l, r), available, ex, taken, command, self.constants()) self.last = None w.add((t("Dowód ", "Proof of "), "heading"), (name, "name"), " : ", (show_equation((l, r)), "goal")) if ex: n_earlier = len(available) - len(self.axioms) if n_earlier == 0: scope = t("dostępne są tylko aksjomaty", "you may use only the axioms") else: scope = t( f"dostępne są aksjomaty i " f"{self.counted(n_earlier, 'theorem')}" f" {word_form(n_earlier, 'earlier', 'pl')}", f"you may use the axioms and the " f"{self.counted(n_earlier, 'theorem')} before it") w.add((t(f" ćwiczenie: to twierdzenie {ex} z biblioteki — ", f" exercise: this is the library theorem {ex} — ") + scope, "warning")) if self.lib[ex].get("short"): w.add((t(" w skrócie: ", " in short: "), "dim"), (self.lib[ex]["short"], "dim")) elif self.theory is None and has_abbreviations(text): w.add((t(" w skrócie: ", " in short: "), "dim"), (" ".join(text.split()), "dim")) found = self.variant_step(name, (l, r)) if found is not None: key, stage, step = found variant = rl.VARIANTS[key] w.add((t(f" {variant['title_pl']}, etap {stage}: " f"{step['source_pl']} — hint i TAB prowadzą skryptem " "wzorcowym", f" {variant['title_en']}, stage {stage}: " f"{step['source_en']} — hint and TAB follow the " "reference script"), "dim")) if self.theory is not None: w.add((t(f" teoria {self.theory_name(self.theory)}: " f"aksjomaty {', '.join(self.axioms)}", f" theory {self.theory_name(self.theory)}: axioms " f"{', '.join(self.axioms)}"), "dim")) found = self.model_cex(l, r) if found is not None: w.add((" " + t("uwaga: ", "warning: ") + self.theory_falsity_text((l, r), found), "warning")) cex = counterexample(l, r) if self.theory is None else None if cex is not None: vals = ", ".join(f"{k} = {v}" for k, v in cex.items()) or "—" w.add((t(f" uwaga: ta równość jest fałszywa w algebrze {{0, 1}} " f"({vals}: lewa {value(l, cex)}, prawa " f"{value(r, cex)}) — jądro nie przyjmie żadnego dowodu", f" warning: this equation is false in the algebra " f"{{0, 1}} ({vals}: left {value(l, cex)}, right " f"{value(r, cex)}) — the kernel will accept no proof"), "warning")) self.show_goals(w, self.proof) return w def p_qed(self): t = self.tr proof = self.proof if proof is None: return self.error(t("nie ma dowodu w toku", "no proof in progress")) if proof.goals: return self.error(t( f"otwarte cele: {len(proof.goals)} — jądro dostaje tylko " "pełny dowód", f"open goals: {len(proof.goals)} — the kernel takes only a " "complete proof")) d = proof.build() l, r = proof.statement if proof.taken: # an exercise under a library name: a fresh kernel checks it, # knowing only the facts available in the exercise kernel = Kernel(boolean.SIGNATURE) for n in proof.available: kernel.facts[n] = self.kernel.facts[n] kernel.assumptions[n] = self.kernel.assumptions[n] else: kernel = self.kernel try: kernel.theorem(proof.name, proof.variables, l, r, d) except ProofError as e: return self.error(t("jądro odrzuciło dowód: ", "the kernel rejected the proof: ") + str(e)) w = Output() w.add(("✓ ", "ok"), (t("jądro przyjęło ", "the kernel accepted "), "ok"), (proof.name, "name"), " : ", (show_equation(proof.statement), "goal")) assumed = sorted(kernel.assumptions[proof.name], key=lambda a: self.axioms.index(a)) w.add((t(f" drzewo dowodu: {self.counted(size(d), 'node')} · " "założenia (jak #print axioms): ", f" proof tree: {self.counted(size(d), 'node')} · " "assumptions (like #print axioms): "), "dim"), (", ".join(assumed), "code")) self.last = (proof.command, list(proof.script)) if proof.taken: w.add((t(f" {proof.name} jest już w bibliotece — Twój dowód " "sprawdziło osobne jądro z faktami z ćwiczenia", f" {proof.name} is already in the library — your proof " "was checked by a separate kernel holding the facts of " "the exercise"), "dim")) else: self.proofs[proof.name] = d script = list(proof.script) self.own[proof.name] = { "statement": (l, r), "script": script, "variables": proof.variables, "steps": self.count_steps(script), "command": proof.command} if self.theory is None: # the page keeps only Boolean ones w.extras["new"] = {"name": proof.name, "equation": show_equation((l, r)), "script": script} w.add((t(" od teraz możesz go używać: ", " from now on you can use it: "), "dim"), (f"rw [{proof.name}]", "code"), " · ", (f"bl lean {proof.name}", "code", {"run": f"bl lean {proof.name}"})) self.proof = None return w def p_undo(self): if self.proof is None: return self.error(self.tr("nie ma dowodu w toku", "no proof in progress")) if not self.proof.history: return self.error(self.tr("nie ma czego cofać", "nothing to undo")) self.proof.undo() w = Output().add((self.tr(" cofnięte", " undone"), "dim")) self.show_goals(w, self.proof) return w def p_restart(self): d = self.proof if d is None: return self.error(self.tr("nie ma dowodu w toku", "no proof in progress")) self.proof = ProofState(d.name, d.statement, d.available, d.exercise, d.taken, d.command, d.constants) w = Output().add((self.tr(" od początku: ", " from the start: "), "dim"), (d.name, "name")) self.show_goals(w, self.proof) return w def p_abort(self): if self.proof is None: return self.error(self.tr("nie ma dowodu w toku", "no proof in progress")) name, self.proof = self.proof.name, None return Output().add((self.tr(f" porzucony dowód {name}", f" abandoned the proof of {name}"), "dim")) def p_script(self): w = Output() if self.proof is not None: w.add((self.tr("-- dowód w toku (jądro jeszcze go nie sprawdziło)", "-- proof in progress (not yet checked by the " "kernel)"), "dim")) command, script, end = (self.proof.command, self.proof.script, []) elif self.last is not None: w.add((self.tr("-- sprawdzone przez jądro (qed)", "-- checked by the kernel (qed)"), "ok")) command, script = self.last end = ["qed"] else: return self.error(self.tr("nie ma skryptu do pokazania", "there is no script to show")) for line in [command] + script + end: w.add((line, "code")) return w def p_hint(self): proof = self.proof if proof is None: return self.error(self.tr( "nie ma dowodu w toku — np. bl prove idem_plus", "no proof in progress — e.g. bl prove add_idem")) w = Output() if not proof.goals: return w.add((" qed", "code", {"insert": "qed"}), (self.tr( " — wszystkie cele zamknięte", " — all goals are closed"), "dim")) goal = proof.goals[0][1] self.variant_hint(w, proof, goal) entries, _ = self.suggestions(proof, goal) sol = None found = self.model_cex(*goal) if self.theory is not None else None if found is not None: return w.add((self.tr("Podpowiedzi dla ", "Suggestions for "), "heading"), (show_equation(goal), "goal")).add( (" ✗ ", "error"), (self.theory_falsity_text( goal, found, bool(proof.history)), "warning")) cex = counterexample(*goal) if self.theory is None else None if cex is not None: falsity = self.falsity_text(goal, cex, bool(proof.history)) return w.add((self.tr("Podpowiedzi dla ", "Suggestions for "), "heading"), (show_equation(goal), "goal")).add( (" ✗ ", "error"), (falsity, "warning")) if not entries or entries[0]["kind"] != "closes": sol, visited = self.solver_suggestion(proof, goal) if sol: entries = self._rank_hints([sol] + [ p for p in entries if p["tactic"] != sol["tactic"]]) w.add((self.tr("Podpowiedzi dla ", "Suggestions for "), "heading"), (show_equation(goal), "goal")) descs = {"closes": self.tr("zamyka cel", "closes the goal"), "shrinks": self.tr("zmniejsza", "shrinks"), "same": self.tr("ten sam rozmiar", "same size"), "grows": self.tr("powiększa", "grows")} width = max([len(p["tactic"]) for p in entries[:10]] + [0]) + 2 for p in entries[:10]: desc = descs[p["kind"]] if p.get("solver"): k = p["solver"] desc = self.tr(f"solver: dowód w {self.in_steps(k)}", f"solver: proof in {self.counted(k, 'step')}") w.add((" ● ", p["kind"]), (p["tactic"].ljust(width), "code", {"insert": p["tactic"]}), (desc.ljust(28), p["kind"]), (p["result"], "dim")) if len(entries) > 10: w.add((self.tr(f" … i {fmt_number(len(entries) - 10, 'pl')}" " innych " "(panel Podpowiedzi)", f" … and {len(entries) - 10} more (Suggestions " "panel)"), "dim")) if sol is not None and self.method_text(sol): w.add((" " + self.method_text(sol), "dim")) if sol is None and entries and entries[0]["kind"] != "closes": if self.theory is not None and \ "ac" in theories.THEORIES[self.theory]: w.add((self.tr( " tu nie ma przeszukiwania wszerz (dowody są za " "długie) — skorzystaj z wariantów dowodu (bl replay) albo " "z auto [reguły, instancje]", " there is no breadth-first search here (the proofs are " "too long) — follow a variant of the proof (bl replay) or " "use auto [rules, instances]"), "dim")) elif self.theory is not None: w.add((self.tr( " przeszukiwanie wszerz nie znalazło dowodu w limicie — " "w tej teorii dowody bywają bardzo długie; spróbuj auto " "100000 albo podziel cel: trans t", " breadth-first search found no proof within the limit " "— proofs in this theory can be very long; try auto " "100000 or split the goal: trans t"), "dim")) else: w.add((self.tr( " solver nie zmieścił się w limicie (za duży cel)" " — spróbuj auto albo podziel cel: trans t", " the solver hit its limit (the goal is too big) " "— try auto or split the goal: trans t"), "dim")) return w def p_model(self, rest): t = self.tr if self.theory is not None: return self.theory_model(rest) try: l, r = equation(rest) except (SyntaxError, ValueError, IndexError): return self.error(t("użycie: bl model x + y = y + x", "usage: bl model x + y = y + x")) vs = equation_vars(l, r) if len(vs) > 10: return self.error(t("za dużo zmiennych (najwyżej 10)", "too many variables (at most 10)")) cex = counterexample(l, r) w = Output() n = 2 ** len(vs) if cex is None: w.add(("✓ ", "ok"), (show_equation((l, r)), "goal"), (t( f" zachodzi dla wszystkich {fmt_number(n, 'pl')} " "wartościowań " "w {0, 1}", f" holds for all {fmt_number(n, 'en')} valuations in " "{0, 1}"), "ok")) w.add((t(" Równość prawdziwa w {0, 1} zachodzi w każdej " "algebrze Boole'a (twierdzenie Stone'a), więc da się ją " "wyprowadzić z H1–H8 (twierdzenie Birkhoffa o pełności " "logiki równościowej).", " An equation true in {0, 1} holds in every Boolean " "algebra (Stone's theorem), so it can be derived from " "H1–H8 (Birkhoff's completeness theorem for equational " "logic)."), "dim")) else: vals = ", ".join(f"{k} = {v}" for k, v in cex.items()) w.add(("✗ ", "error"), (show_equation((l, r)), "goal"), (t( f" fałszywa dla {vals}: lewa {value(l, cex)}, prawa " f"{value(r, cex)}", f" false for {vals}: left {value(l, cex)}, right " f"{value(r, cex)}"), "error")) return w def theory_model(self, rest): """bl model in another theory: the equation in every finite model of the theory (also in those where some axiom fails).""" t = self.tr try: l, r = self.parse_equation(rest) self.kernel.term(l), self.kernel.term(r) except (SyntaxError, ValueError, IndexError, ProofError): return self.error(t(f"użycie: bl model równość — zapis: " f"{self.notation_text()}", f"usage: bl model equation — notation: " f"{self.notation_text()}")) names = theories.variables_of(r, theories.variables_of(l)) if len(names) > 6: return self.error(t("za dużo zmiennych (najwyżej 6)", "too many variables (at most 6)")) w = Output() w.add((show_equation((l, r)), "goal")) for model, bad in theories.models(self.theory): v = theories.counterexample(l, r, model, names) role = t("model aksjomatów", "a model of the axioms") if not bad \ else t(f"nie spełnia {', '.join(bad)}", f"fails {', '.join(bad)}") if v is None: w.add((" ✓ ", "ok"), (self.model_text(model), "code"), (t(f" — {role}: zachodzi", f" — {role}: holds"), "ok")) else: vals = ", ".join(f"{k} = {x}" for k, x in v.items()) w.add((" ✗ ", "error"), (self.model_text(model), "code"), (t(f" — {role}: fałsz dla {vals}: lewa " f"{theories.value(l, model, v)}, prawa " f"{theories.value(r, model, v)}", f" — {role}: false for {vals}: left " f"{theories.value(l, model, v)}, right " f"{theories.value(r, model, v)}"), "error")) w.add((t(" Fałsz w modelu aksjomatów = brak dowodu (twierdzenie " "o poprawności). Prawda we wszystkich tych modelach jeszcze " "niczego nie dowodzi.", " False in a model of the axioms = no proof (the soundness " "theorem). True in all these models proves nothing yet."), "dim")) return w def p_tactic(self, rest=""): t = self.tr rest = rest.strip() if ":=" in rest: name, _, body = rest.partition(":=") return self.define_tactic(name.strip(), body.strip()) words = rest.split() if len(words) == 2 and words[0] == "forget": return self.forget_tactic(words[1]) if rest in self.tactics: return self.describe_tactic(rest) cards = { "rw": ( "rw [r₁, …, rₖ] — przepisywanie (w Leanie: rw)", "rw [r₁, …, rₖ] — rewriting (in Lean: rw)", ["r to H6, ← H6 albo H2 n(x) y: fakt, kierunek i " "argumenty (złożone w nawiasach: ← H6 (x + x)).", "Każda reguła szuka pierwszego dopasowania wzorca: najpierw " "lewa strona celu, potem prawa, od korzenia w głąb. To " "dopasowanie ustala instancję; rw zamienia WSZYSTKIE jej " "wystąpienia. Na końcu rw próbuje rfl.", "Wzorzec będący samą zmienną (← H6) pasowałby wszędzie — " "Lean go odrzuca, więc trzeba podać argument.", "Jądro dostaje z każdej reguły: Inst (fakt dla argumentów), " "CongrArg (kontekst z dziurą), Symm, Trans."], ["r is H6, ← H6 or H2 n(x) y: a fact, a direction and " "arguments (compound ones in parentheses: ← H6 (x + x)).", "Each rule looks for the first match of its pattern: the " "left side of the goal first, then the right side, from the " "root down. That match fixes the instance; rw replaces ALL " "its occurrences. At the end rw tries rfl.", "A pattern that is a bare variable (← H6) would match " "anywhere — Lean rejects it, so give an argument.", "From each rule the kernel gets: Inst (the fact for the " "arguments), CongrArg (a context with a hole), Symm, " "Trans."], "bl prove x + x = x\nrw [← H6 (x + x), ← H7 x, ← H3, H8, " "H5]\nqed"), "nth_rw": ( "nth_rw k [h] — przepisz tylko k-te dopasowanie", "nth_rw k [h] — rewrite only the k-th match", ["Dopasowania liczymy od 1, w tej samej kolejności co rw " "(także zagnieżdżone). W Leanie 4 bez Mathliba: " "rw (occs := .pos [k]) [h]."], ["Matches are counted from 1, in the same order as rw " "(nested ones too). In Lean 4 without Mathlib: " "rw (occs := .pos [k]) [h]."], "bl prove x * y = y * x\nnth_rw 2 [H2]"), "rfl": ( "rfl — zamyka cel t = t", "rfl — closes a goal t = t", ["Jądro: Refl(t)."], ["Kernel: Refl(t)."], ""), "symm": ( "symm — zamienia strony celu", "symm — swaps the sides", ["Cel a = b zamienia się w b = a. Jądro: Symm."], ["The goal a = b becomes b = a. Kernel: Symm."], "bl prove x = x + 0\nsymm\nrw [H5]"), "trans": ( "trans t — rozbija a = b na a = t i t = b", "trans t — splits a = b into a = t and t = b", ["Dwa cele, najpierw a = t. Jądro: Trans. W Leanie 4 bez " "Mathliba: refine Eq.trans (b := t) ?_ ?_."], ["Two goals, a = t first. Kernel: Trans. In Lean 4 without " "Mathlib: refine Eq.trans (b := t) ?_ ?_."], "bl prove x + x = x\ntrans (x + x) * 1"), "exact": ( "exact h args — cel jest instancją faktu h", "exact h args — the goal is an instance of the fact h", ["Brakujące argumenty dopasuje laboratorium; skrypt " "zapisuje wszystkie (Lean ich wymaga). Jądro: Inst."], ["The lab fills in missing arguments; the script records " "all of them (Lean needs them). Kernel: Inst."], "bl prove y + x = x + y\nexact H1"), "auto": ( "auto [budżet] [[h, …]] — solver", "auto [budget] [[h, …]] — solver", ["Ten sam solver co w podpowiedziach (solver.py) bierze " "najkrótszy dowód z kilku strategii: przeszukiwanie wszerz " "z obu stron celu (jak taktyki.szukaj z wykładu), dowód " "twierdzenia z biblioteki (w ćwiczeniu rozwinięty do " "dozwolonych faktów) i postać normalna — obie strony stają " "się sumą mintermów, więc auto dowodzi każdej prawdziwej " "równości. Fałszywą rozpoznaje po kontrprzykładzie " "w {0, 1}.", "Dowód trafia do skryptu jako jawne rw / nth_rw, więc " "script i bl lean pokazują zwykłe kroki. Budżet: liczba " "termów przeszukiwania wszerz (domyślnie 30 000); " "z listą faktów w nawiasach auto tylko przeszukuje wszerz " "tymi faktami. Długie szukanie przerywa przycisk Stop."], ["The same solver as in the hints (solver.py) takes the " "shortest proof from several strategies: breadth-first " "search from both sides of the goal (like tactics.search " "from the lecture), the proof of a library theorem " "(expanded to the allowed facts in an exercise) and the " "normal form — both sides become a sum of minterms, so " "auto proves every true equation. It recognises a false " "one by a counterexample in {0, 1}.", "The proof goes into the script as explicit rw / nth_rw " "lines, so script and bl lean show ordinary steps. " "Budget: the number of terms of the breadth-first search " "(30,000 by default); with a list of facts in brackets " "auto only searches breadth-first with those facts. The " "Stop button interrupts a long search."], "bl prove x + x * y = x\nauto"), } basic = list(cards) cards.update(TACTICAL_CARDS) w = Output() if rest not in cards: return self.tactic_list(basic) title_pl, title_en, paras_pl, paras_en, example = cards[rest] w.add((t(title_pl, title_en), "heading")) for paragraph in (paras_pl if self.lang == "pl" else paras_en): w.add((" " + paragraph, "")) if example: w.add((t(" przykład:", " example:"), "dim")) for line in example.split("\n"): w.add((" ", ""), (line, "code", {"insert": line})) return w def tactic_list(self, basic): t = self.tr w = Output() def links(names): pieces = [] for i, k in enumerate(names): if i: pieces.append((" · ", "dim")) pieces.append((k, "code", {"run": f"bl tactic {k}"})) return pieces w.add((t("Taktyki podstawowe (bl tactic nazwa)", "Basic tactics (bl tactic name)"), "heading")) w.add((" ", ""), *links(basic)) w.add((t("Taktyki z taktyk — tacticals (bl tactic nazwa)", "Tactics from tactics — tacticals (bl tactic name)"), "heading")) w.add((" ", ""), *links([k for k in TACTICAL_CARDS if k != "design"])) w.add((" ", ""), ("bl tactic design", "code", {"run": "bl tactic design"}), (t(" — jak projektować dobre taktyki", " — how to design good tactics"), "dim")) own = [n for n, i in self.tactics.items() if not i.get("example")] examples = [n for n, i in self.tactics.items() if i.get("example")] if own: w.add((t("Twoje taktyki", "Your tactics"), "heading")) for n in own: w.add((" ", ""), (n, "name", {"run": f"bl tactic {n}"}), " := ", (self.tactics[n]["text"], "code")) if examples and self.theory is None: w.add((t("Przykłady — dobre (✓) i złe (✗)", "Examples — good (✓) and bad (✗)"), "heading")) for n in examples: info = self.tactics[n] w.add((" ", ""), ("✓ " if info["good"] else "✗ ", "ok" if info["good"] else "error"), (n.ljust(22), "name", {"run": f"bl tactic {n}"}), (info["description"], "dim")) w.add((t(" Własna taktyka: bl tactic nazwa := taktyka · próba: " "bl trace taktyka · usunięcie: bl tactic forget nazwa · " "warsztat taktyk: przycisk pod terminalem", " Your own tactic: bl tactic name := tactic · dry run: " "bl trace tactic · deleting: bl tactic forget name · the " "tactic workshop: the button below the terminal"), "dim")) return w def p_kernel(self, *_): t = self.tr w = Output() w.add((t("Jądro (kernel.py) — jedyny kod, któremu trzeba ufać", "The kernel (kernel.py) — the only code you must trust"), "heading")) try: with open(__file__.replace("lab.py", "kernel.py"), encoding="utf-8") as f: n_lines = sum(1 for _ in f) except OSError: n_lines = None if n_lines: w.add((t(f" kernel.py: {self.counted(n_lines, 'line')}; " "reguły: ", f" kernel.py: {self.counted(n_lines, 'line')}; " "rules: "), "dim"), ("Refl, Symm, Trans, CongrArg, Inst", "code")) w.add((t(" Taktyki, podpowiedzi i solver tylko budują drzewo z tych " "reguł. qed oddaje je jądru razem z pierwotną tezą: " "Jadro.twierdzenie liczy, co drzewo dowodzi, i dopisuje " "twierdzenie tylko wtedy, gdy to dokładnie teza.", " Tactics, suggestions and the solver only build a tree of " "these rules. qed hands it to the kernel with the original " "statement: Kernel.theorem computes what the tree proves " "and adds the theorem only if it is exactly the " "statement."), "")) w.add((t(" Trzy prawa: każde qed sprawdza jądro · nieudana taktyka " "nie zmienia stanu · jądro nie importuje niczego z " "laboratorium.", " Three laws: every qed is checked by the kernel · a " "failing tactic leaves the state unchanged · the kernel " "imports nothing from the lab."), "dim")) w.add((" ", ""), (t("kod jądra: ", "kernel code: "), "dim"), (self.base_url + "kernel.py", "code", {"href": self.base_url + "kernel.py.html"}), " · ", (self.base_url + "lab.py", "code", {"href": self.base_url + "lab.py.html"})) return w def p_forget(self, rest): name = rest.strip() if name not in self.own: return self.error(self.tr( f"{name or '?'} nie jest Twoim twierdzeniem", f"{name or '?'} is not one of your theorems")) dependents = [n for n in self.own if n != name and name in used_facts(self.proofs[n])] if dependents: return self.error(self.tr( f"z {name} korzystają: {', '.join(dependents)} — usuń je " "najpierw", f"{name} is used by: {', '.join(dependents)} — delete them " "first")) w = Output().add((self.tr(f" usuwam {name} i uruchamiam jądro od " "nowa…", f" deleting {name} and restarting the " "kernel…"), "dim")) w.extras["forget"] = name return w def p_lean(self, rest): parts = rest.split() if not parts: return self.error(self.tr("użycie: bl lean nazwa [full]", "usage: bl lean name [full]")) name = parts[0] full_file = len(parts) > 1 and parts[1] == "full" if name not in self.lib and name not in self.own: return self.error(self.tr(f"nie ma twierdzenia {name}", f"there is no theorem {name}")) if self.own[name].get("given") if name in self.own else False: return Output().add((self.tr( f" {name} to fakt dany: w Leanie jest polem klasy " f"{self.lean_class_name()} (bl lean z dowolnym twierdzeniem " "tej teorii i full pokazuje klasę)", f" {name} is a given fact: in Lean it is a field of the " f"class {self.lean_class_name()} (bl lean with any theorem " "of this theory and full shows the class)"), "dim")) w = Output() if full_file: text = self.lean_file(self.closure(name)) else: assumed = [n for n in sorted(used_facts(self.proofs[name]), key=self.all_facts().index) if n not in self.axioms] header = [self.tr( "-- klasa AlgebraBoolea: lean/Wyklad03.lean; otwórz ją " "(open AlgebraBoolea)", "-- class HuntingtonAlgebra: lean/Lecture03.lean; open it " "(open HuntingtonAlgebra)") if self.theory is None else self.tr(f"-- klasa {self.lean_class_name()}: bl lean " f"{name} full (cały plik)", f"-- class {self.lean_class_name()}: bl lean {name} " "full (a whole file)"), f"-- variable {{α : Type}} [{self.lean_class_name()} α]"] if assumed: header.append(self.tr("-- korzysta z: ", "-- uses: ") + ", ".join(assumed)) header += self.lean_macros([name]) text = "\n".join(header) + "\n" + self.lean_theorem(name) for line in text.split("\n"): w.add((line, "lean")) if not full_file: w.add((self.tr(" cały plik do skompilowania: ", " a whole file ready to compile: "), "dim"), (f"bl lean {name} full", "code", {"run": f"bl lean {name} full"})) w.extras["lean"] = text return w # -- Lean -- def lean_line(self, line): """A script line in Lean 4 (a comment -- … stays).""" tactic_text = self._lean_tactic(line) _, _, comment = line.partition("--") if comment and strip_comment(line): return f"{tactic_text} --{comment.rstrip()}" return tactic_text def _lean_tactic(self, line): node = self.compound(line) if node is not None: return tc.show(node, lambda x: self._lean_basic(x, True)) return self._lean_basic(line) def _lean_basic(self, line, inside=False): """One basic tactic in Lean 4. exact gets _ for each argument it leaves out (Lean needs all of them; the lab finds them). A line this session cannot read (the notation of another theory) stays as it is.""" try: tag, data = parse_line(line, self.notation) except TacticError: return line.strip() if tag == "nothing": return line.strip() if tag == "rw": which, rules = data rules_text = ", ".join( r.lean(lambda a: self.lean_term(a, 3)) for r in rules) if which: return f"rw (occs := .pos [{which}]) [{rules_text}]" return f"rw [{rules_text}]" if tag in ("rfl", "symm"): return tag if tag == "ac_rfl": # Lean's ac_rfl does not look under n(...): a macro of the class # file repeats ac_nf (theories.lean_class) return "ac_rfl_deep" if tag in ("rw_ac", "ac_simp") or (tag == "auto" and self.theory is not None): raise NotInLean(line) if tag == "exact": text = data.lean(lambda a: self.lean_term(a, 3)) fact = self.kernel.facts.get(data.name) missing = len(fact[0]) - len(data.args) if fact else 0 return f"exact {text}" + " _" * max(missing, 0) if tag == "trans": return (f"refine Eq.trans (b := ({self.lean_term(data)} : α)) " "?_ ?_") raise ValueError(line) def lean_theorem(self, name): info = self.lib.get(name) or self.own[name] l, r = info["statement"] vs = info["variables"] if vs: statement = f"({' '.join(vs)} : α) : " \ f"{self.lean_term(l)} = {self.lean_term(r)}" else: statement = f": ({self.lean_term(l)} : α) = {self.lean_term(r)}" lines = [f"-- {info['short']}"] if info.get("short") else [] try: body = [" " + self.lean_line(x) for x in info["script"]] except NotInLean: # rw_ac, ac_simp, auto: the kernel's proof lines += [self.tr( "-- taktyki modulo AC nie mają odpowiednika w Leanie: " "dowód jądra jako term", "-- the tactics modulo AC have no Lean counterpart: the " "kernel's proof as a term"), f"theorem {name} {statement} :=", " " + lean_proof_term(self.proofs[name])] return "\n".join(lines) lines += [f"theorem {name} {statement} := by"] + body return "\n".join(lines) def closure(self, name): """The theorems needed for the proof of `name` (in order).""" needed, stack = set(), [name] while stack: n = stack.pop() if n in needed or n in self.axioms: continue needed.add(n) stack.extend(used_facts(self.proofs[n])) return [n for n in self.all_facts() if n in needed] def lean_file(self, names, header=None): if header is None: header = self.tr( "/- Boole Lab: dowody z laboratorium w Leanie 4 (bez " "Mathliba).\n Sprawdzenie: lean Plik.lean -/", "/- Boole Lab: proofs from the lab in Lean 4 (no Mathlib)." "\n Check: lean File.lean -/") cls = self.lean_class_name() parts = [header, "", self.lean_class_text().rstrip(), "", f"open {cls}", "", f"variable {{α : Type}} [{cls} α]", ""] parts += self.lean_macros(names) for n in names: if not self.own.get(n, {}).get("given"): # a class field parts += [self.lean_theorem(n), ""] return "\n".join(parts) def lean_macros(self, names): """The user tactics that the proofs of `names` call, as Lean macros (each after those it calls), with a blank line after each.""" scripts = [] for n in names: info = self.lib.get(n) or self.own.get(n) if info: scripts += info["script"] result = [] for c in self.tactics_called(self.script_nodes(scripts)): result += [self.lean_macro_text(c, self.tactics[c]["node"]), ""] return result # -- the browser interface (JSON) -- def replay_own(self, entries): """Replays the user's theorems (localStorage) through the kernel. Entries saved by the first version of the page have Polish keys (LEGACY_KEYS).""" accepted, rejected = [], [] for entry in entries: try: entry = {LEGACY_KEYS.get(k, k): v for k, v in entry.items()} name, text = entry["name"], entry["equation"] script = list(entry["script"]) except (AttributeError, KeyError, TypeError): continue self.drop_example(name) old = self.proof self._replaying = True try: result = self.run(f"bl prove {name} : {text}") finally: self._replaying = False ok = not result.error if ok: for line in script: if self.run(line).error: ok = False break if ok: ok = not self.p_qed().error (accepted if ok else rejected).append(name) self.proof = old self.last = None return accepted, rejected def library_json(self): sections = [] for name in self.order: info = self.lib[name] s = info["section"] if not sections or sections[-1]["source"] is not s: sections.append({"source": s, "title": s["title"], "theorems": []}) sections[-1]["theorems"].append(self._thm_json(name, info)) result = [{"title": s["title"], "theorems": s["theorems"]} for s in sections] if self.own: result.append({"title": self.tr("Twoje twierdzenia", "Your theorems"), "own": True, "theorems": [self._thm_json(n, i) for n, i in self.own.items()]}) lib = {"axioms": [{"name": n, "text": self.fact_text(n)} for n in self.axioms], "sections": result} if self.theory is not None: # bl theory: its name and challenges lib["theory"] = self.theory_name(self.theory) lib["challenges"] = self.challenges_json() lib["tactics"] = [ {"name": n, "text": i["text"], "example": i["example"], "good": i.get("good"), "description": i.get("description", ""), "doc": i.get("doc", "")} for n, i in self.tactics.items() if not (i["example"] and self.theory is not None)] return lib def challenges_json(self): """The equations to try in the current theory (as on its card): the text and the model in which it fails ("" if none does).""" entries = [] steps = {} # a Robbins theory: the next steps robbins = "ac" in theories.THEORIES[self.theory] for key, stage, step in (rl.steps_of(self.theory) if robbins else ()): if step["name"] not in self.kernel.facts and \ len(steps.setdefault(key, [])) < 3: steps[key].append({ "text": step["name"], "false_in": "", "note": self.tr(step["source_pl"], step["source_en"])}) for found in steps.values(): entries += found for text in theories.THEORIES[self.theory]["challenges"]: l, r = self.parse_equation(text) found = self.model_cex(l, r) entries.append({"text": show_equation((l, r)), "false_in": found[0] if found else ""}) return entries def _thm_json(self, name, info): """A theorem for the interface; "id" is its English name (the same on both pages; for the user's theorems: the name).""" return {"name": name, "id": info.get("id", name), "text": show_equation(info["statement"]), "short": info.get("short") or "", "steps": info["steps"], "description": info.get("description") or "", "assumptions": sorted(self.kernel.assumptions[name], key=lambda a: self.axioms.index(a))} def state(self): d = self.proof if d is None: return {"proof": None} goals = [] for i, (_, c) in enumerate(d.goals): entry = {"text": show_equation(c)} if i == 0: entry["tree"] = [tree(c[0], "0"), tree(c[1], "1")] goals.append(entry) suggested, facts = [], {} if d.goals: suggested, facts = self.suggestions(d, d.goals[0][1]) suggested, facts = self.mark_reverting( d.goals[0][1], suggested, d.seen, facts) else: suggested = [{"tactic": "qed", "kind": "closes", "rule": "", "fact": "", "result": "", "paths": [], "source": "tactic", "nargs": 0, "size_after": 0, "index": -1}] too_big = bool(d.goals) and term_size(d.goals[0][1][0]) + \ term_size(d.goals[0][1][1]) > MAX_HINT_SIZE return {"too_big": too_big, "proof": {"name": d.name, "statement": show_equation(d.statement), "exercise": d.exercise, "command": d.command, "script": list(d.script), "available": list(d.available)}, "goals": goals, "suggestions": suggested[:60], "facts": facts} @staticmethod def mark_reverting(goal, suggested, seen, facts=None): """A step that takes a side of the goal back to an earlier form (the left one to an earlier left side, the right one to an earlier right side) goes to the end of the list — otherwise suggestions could go round in circles. Returns (suggestions, facts) with the field "reverts".""" L, R = map(show, goal) lefts = {show(c[0]) for c in seen} rights = {show(c[1]) for c in seen} def mark(p): reverts = False if p["result"]: l2, r2 = p["result"].split(" = ") reverts = (l2 != L and l2 in lefts) or \ (r2 != R and r2 in rights) return dict(p, reverts=reverts) result = sorted(map(mark, suggested), key=lambda p: p["reverts"]) facts = {n: {k: mark(p) for k, p in info.items()} for n, info in (facts or {}).items()} return result, facts def json_run(self, line): t0 = time.perf_counter() before = (self.theory, tuple(self.own)) try: result = self.run(line) except RecursionError: result = self.error(self.tr("za głęboka rekursja", "recursion too deep")) reply = {"lines": result.rows, "error": result.error, "state": self.state(), "time": time.perf_counter() - t0} reply.update(result.extras) # the page redraws its library after a new theorem and after # bl theory (other axioms, no library, the theory's challenges) if "new" in result.extras or "tactic_new" in result.extras or \ "tactic_forget" in result.extras or \ (self.theory, tuple(self.own)) != before: reply["library"] = self.library_json() return json.dumps(reply, ensure_ascii=False) def json_preview(self, line): """The goal after the leading rules of the line being typed.""" d = self.proof if d is None or not d.goals: return json.dumps({"goal": None}) m = re.fullmatch(r"\s*(rw|nth_rw\s+(\d+))\s*\[(.*)", line) if not m: return json.dumps({"goal": None}) which = int(m.group(2)) if m.group(2) else None parts = split_top(m.group(3), ",")[:-1] goal = d.goals[0][1] seen = list(d.seen) try: for c in parts: rule = parse_rule(c, self.notation) self.check_rule(d, rule) seen.append(goal) goal, _ = rewrite(self.kernel, goal, rule, which) except (TacticError, ProofError) as e: return json.dumps({"goal": None, "error": self.error_text(e)}, ensure_ascii=False) suggested, facts = self.suggestions(d, goal) suggested, facts = self.mark_reverting(goal, suggested, seen, facts) return json.dumps({"goal": show_equation(goal), "tree": [tree(goal[0], "0"), tree(goal[1], "1")], "suggestions": suggested[:60], "facts": facts, "rules": len(parts)}, ensure_ascii=False) def json_solver(self, seconds=0.4): d = self.proof if d is None or not d.goals: return json.dumps({"suggestion": None}) goal = d.goals[0][1] found = self.model_cex(*goal) if self.theory is not None else None if found is not None: return json.dumps({"suggestion": None, "goal": show_equation(goal), "falsity": self.theory_falsity_text( goal, found, bool(d.history))}, ensure_ascii=False) cex = counterexample(*goal) if self.theory is None else None if cex is not None: return json.dumps({"suggestion": None, "goal": show_equation(goal), "falsity": self.falsity_text(goal, cex, bool(d.history))}, ensure_ascii=False) entries, _ = self.suggestions(d, goal) if entries and entries[0]["kind"] == "closes": return json.dumps({"suggestion": None, "goal": show_equation(goal)}) p, visited = self.solver_suggestion(d, goal, seconds=seconds) if p is not None: p["description"] = self.method_text(p) return json.dumps({"suggestion": p, "visited": visited, "goal": show_equation(goal)}, ensure_ascii=False) def json_start(self, own_json="[]", tactics_json="[]"): try: entries = json.loads(own_json) except ValueError: entries = [] try: saved_tactics = json.loads(tactics_json) except ValueError: saved_tactics = [] t0 = time.perf_counter() tactics_ok, tactics_bad = self.load_tactics(saved_tactics) accepted, rejected = self.replay_own( entries if isinstance(entries, list) else []) own_time = time.perf_counter() - t0 return json.dumps({ "library": self.library_json(), "count": len(self.order), "errors": self.library_errors, "time": self.library_time, "own": accepted, "rejected": rejected, "own_time": own_time, "tactics": tactics_ok, "tactics_rejected": tactics_bad, "banner": self.banner(accepted, rejected, tactics_ok, tactics_bad).rows, "state": self.state()}, ensure_ascii=False) def banner(self, accepted=(), rejected=(), tactics_ok=(), tactics_bad=()): t = self.tr seconds = self.fmt_seconds(self.library_time) example = f"bl prove {self.names['add_idem']}" w = Output() w.add(("Boole Lab", "heading"), (t( " — algebra Boole'a w jądrze z wykładu 3", " — Boolean algebra in the kernel of Lecture 3"), "dim")) w.add((f"Python {sys.version.split()[0]}", "dim"), (t(" · aksjomaty Huntingtona H1–H8 · biblioteka: ", " · Huntington's axioms H1–H8 · library: "), "dim"), (self.counted(len(self.order), "theorem"), "ok"), (t(f" przyjętych przez jądro ({seconds})", f" accepted by the kernel ({seconds})"), "dim")) if self.library_errors: for name, desc in self.library_errors: w.add(("✗ ", "error"), (f"{name}: {desc}", "error")) if accepted: w.add((t(f"Twoje twierdzenia: {len(accepted)} — odtworzone i " "ponownie sprawdzone przez jądro", f"Your theorems: {len(accepted)} — replayed and checked " "again by the kernel"), "ok")) if rejected: w.add((t("Nie przeszły ponownego sprawdzenia: ", "Failed the new check: ") + ", ".join(rejected), "warning")) if tactics_ok: w.add((t(f"Twoje taktyki: {', '.join(tactics_ok)}", f"Your tactics: {', '.join(tactics_ok)}"), "ok")) if tactics_bad: w.add((t("Taktyki odrzucone przy starcie: ", "Tactics rejected at the start: ") + ", ".join(tactics_bad), "warning")) w.add((t("Wpisz ", "Type "), "dim"), ("bl help", "code", {"run": "bl help"}), (t(" albo zacznij od ", " or start with "), "dim"), (example, "code", {"run": example}), (t(". TAB albo → przyjmuje podpowiedź.", ". TAB or → accepts the suggestion."), "dim")) return w # --- terminal ---------------------------------------------------------------- def main(argv): lang = "pl" if "--pl" in argv else "en" commands = [argv[i + 1] for i, a in enumerate(argv[:-1]) if a == "-c"] session = Session(lang) print(session.banner().text()) if commands: for p in commands: print(f"bl> {p}") result = session.run(p) print(result.text()) if result.error: return 1 return 0 while True: try: line = input("bl> ") except EOFError: return 0 if line.strip() in ("exit", "quit"): return 0 try: print(session.run(line).text()) except RecursionError: print("✗ recursion too deep") if __name__ == "__main__": sys.exit(main(sys.argv[1:]))