"""Tactics and a small solver for the kernel of equational logic (lecture 3). A tactic is an ordinary program: it gets a goal (left, right) and returns a proof — a tree of the kernel's rules. A tactic may search, guess and make mistakes: the kernel checks its result anyway. That is why tactics need not be trusted. """ from collections import deque from kernel import Refl, Symm, Trans, CongrArg, Inst, subst from syntax import term, equation, show, show_equation class TacticError(Exception): """The tactic cannot build a proof (this is not a kernel error).""" # --- tools on terms ---------------------------------------------------------- def variables(t, result=None): """Variables of a term in the order of first occurrence.""" result = [] if result is None else result if isinstance(t, str): if t.isidentifier() and t not in result: result.append(t) else: for a in t[1:]: variables(a, result) return result def match_pattern(pattern, t, free, s): """A substitution s of the variables in `free` with pattern[s] == t.""" if isinstance(pattern, str) and pattern in free: if pattern in s: return s if s[pattern] == t else None return {**s, pattern: t} if isinstance(pattern, str) or isinstance(t, str): return s if pattern == t else None if pattern[0] != t[0] or len(pattern) != len(t): return None for a, b in zip(pattern[1:], t[1:]): s = match_pattern(a, b, free, s) if s is None: return None return s def subterms(t): """Subterms in prefix order (the whole term first).""" yield t if not isinstance(t, str): for a in t[1:]: yield from subterms(a) def abstract(t, u, z): """Replaces each occurrence of the subterm u by the variable z (a hole).""" if t == u: return z if isinstance(t, str): return t return (t[0],) + tuple(abstract(a, u, z) for a in t[1:]) def fresh(*terms): """A variable that does not occur in the given terms (for a hole).""" taken = set() for t in terms: taken.update(variables(t)) for candidate in ["z"] + [f"z{i}" for i in range(1, 1000)]: if candidate not in taken: return candidate # --- composing proofs without needless steps --------------------------------- def trans(*proofs): proofs = [d for d in proofs if d is not None and not isinstance(d, Refl)] if not proofs: return None result = proofs[0] for d in proofs[1:]: result = Trans(result, d) return result def congr(z, C, p): if C == z: return p if z not in variables(C): return None # a context without a hole: t = t, skip it return CongrArg(z, C, p) def symm(p): return None if p is None else (p.p if isinstance(p, Symm) else Symm(p)) # --- tactics ----------------------------------------------------------------- def _rule(kernel, text): """'H3', '← H7', 'H7 x', '← H3 (x + y) z w' -> (name, backward, args).""" text = text.strip() backward = text.startswith("←") text = text.lstrip("←").strip() name, _, rest = text.partition(" ") if name not in kernel.facts: raise TacticError(f"unknown fact {name}") args, depth, current = [], 0, "" for c in rest: if c == " " and depth == 0: if current: args.append(term(current)) current = "" continue depth += (c == "(") - (c == ")") current += c if current: args.append(term(current)) return name, backward, (tuple(args) if args else None) def rewrite(kernel, goal, rule): """One rw step: (new goal, function: proof of the new -> of the old).""" name, backward, args = _rule(kernel, rule) free, l, r = kernel.facts[name] if backward: l, r = r, l L, R = goal if args is not None: # explicit arguments: rw [H7 x] s = dict(zip(free, args)) instance = None for u in list(subterms(L)) + list(subterms(R)): if u == subst(l, s): instance = s break else: # arguments from matching: rw [H7] if any(x not in variables(l) for x in free): raise TacticError(f"rw [{rule}]: give the arguments") instance = None for u in list(subterms(L)) + list(subterms(R)): instance = match_pattern(l, u, free, {}) if instance is not None: break if instance is None: raise TacticError(f"rw [{rule}]: no pattern {show(l)} " f"in {show_equation(goal)}") arguments = tuple(instance[x] for x in free) pe = Inst(name, arguments) if backward: pe = Symm(pe) l2, r2 = subst(l, instance), subst(r, instance) z = fresh(L, R, l2, r2) CL, CR = abstract(L, l2, z), abstract(R, l2, z) new = (subst(CL, {z: r2}), subst(CR, {z: r2})) def compose(q): # L = L' (q: L' = R') R' = R return trans(congr(z, CL, pe), q, symm(congr(z, CR, pe))) return new, compose def rw(*rules): """The tactic rw [h₁, h₂, …]: rewrites in turn, then tries rfl.""" def tactic(kernel, goal): pieces = [] for rule in rules: previous = goal goal, compose = rewrite(kernel, goal, rule) pieces.append((previous, compose)) if goal[0] != goal[1]: raise TacticError(f"rw: the goal {show_equation(goal)} remains") d = Refl(goal[0]) for previous, compose in reversed(pieces): d = compose(d) or Refl(previous[0]) return d return tactic def rfl(): def tactic(kernel, goal): if goal[0] != goal[1]: raise TacticError(f"rfl: the sides differ: {show_equation(goal)}") return Refl(goal[0]) return tactic def calc(first, *steps): """calc a = b := t₁; _ = c := t₂; … — a chain (each step a tactic).""" def tactic(kernel, goal): a = term(first) if a != goal[0]: raise TacticError(f"calc: start {show(a)}, goal {show(goal[0])}") proofs = [] for text, t in steps: b = term(text) proofs.append(t(kernel, (a, b))) a = b if a != goal[1]: raise TacticError(f"calc: end {show(a)}, goal {show(goal[1])}") return trans(*proofs) or Refl(a) return tactic def prove(kernel, name, text, tactic): """The theorem ∀ variables, text: the tactic builds, the kernel checks.""" l, r = equation(text) proof = tactic(kernel, (l, r)) kernel.theorem(name, variables(r, variables(l)), l, r, proof) return proof # --- a small solver: breadth-first search from both ends --------------------- def _size(t): return 1 if isinstance(t, str) else 1 + sum(_size(a) for a in t[1:]) def _positions(t, path=()): yield path, t if not isinstance(t, str): for i, a in enumerate(t[1:], start=1): yield from _positions(a, path + (i,)) def _insert(t, path, u): if not path: return u i = path[0] return t[:i] + (_insert(t[i], path[1:], u),) + t[i + 1:] def _neighbours(kernel, t, facts, pool, bound): """Terms reachable from t by one rewrite (each fact in both directions).""" for name in facts: free, l, r = kernel.facts[name] for backward, (pat, goal) in ((False, (l, r)), (True, (r, l))): extra = [x for x in free if x not in variables(pat)] for path, u in _positions(t): s = match_pattern(pat, u, free, {}) if s is None: continue choices = [{}] for x in extra: # variables the pattern does not fix choices = [{**w, x: v} for w in choices for v in pool] for w in choices: s2 = {**s, **w} new = _insert(t, path, subst(goal, s2)) if _size(new) <= bound: args = tuple(s2[x] for x in free) yield new, (path, name, backward, args, t) def _step_proof(path, name, backward, args, t): pe = Inst(name, args) if backward: pe = Symm(pe) z = fresh(t) return congr(z, _insert(t, path, z), pe) def search(kernel, text, facts, max_size=9, limit=200_000): """Searches for a proof of an equation breadth-first from both sides. Returns (proof, number of visited terms). The proof is an ordinary tree of rules, so the kernel checks it — the solver need not be trusted.""" l, r = equation(text) pool = variables(r, variables(l)) parent = [{l: None}, {r: None}] queue = deque([(l, 0), (r, 1)]) while queue and len(parent[0]) + len(parent[1]) < limit: t, side = queue.popleft() for new, step in _neighbours(kernel, t, facts, pool, max_size): if new in parent[side]: continue parent[side][new] = step if new in parent[1 - side]: visited = len(parent[0]) + len(parent[1]) return _rebuild(parent, new, side), visited queue.append((new, side)) return None, len(parent[0]) + len(parent[1]) def _path(parent, t): """Steps from the root of the search tree to t: a proof root = t.""" proofs = [] while parent[t] is not None: path, name, backward, args, previous = parent[t] proofs.append(_step_proof(path, name, backward, args, previous)) t = previous return trans(*reversed(proofs)) def _rebuild(parent, meeting, side): from_left = _path(parent[0], meeting) # l = meeting from_right = _path(parent[1], meeting) # r = meeting return trans(from_left, symm(from_right)) or Refl(meeting)