"""A minimal kernel for equational logic — lecture 3. The kernel searches for nothing. It receives a finished proof — a tree built from five rules — and computes which equation the proof justifies. A theorem enters the environment only when that equation is exactly the announced one. The rules are named as in Lean: Eq.refl, Eq.symm, Eq.trans, congrArg and the application of a theorem to arguments. Terms are tuples: a variable is the string 'x', a constant is the string '0', and the application of a symbol to arguments is the tuple ('+', 'x', ('n', 'x')). There are no quantifiers and no λ here, so substitution is a plain replacement of letters — that is why we can do without de Bruijn indices. """ from dataclasses import dataclass class ProofError(Exception): """The kernel rejects a proof.""" # --- proofs: five rules ------------------------------------------------------ @dataclass(frozen=True) class Refl: # t = t t: object @dataclass(frozen=True) class Symm: # from a = b follows b = a p: object @dataclass(frozen=True) class Trans: # from a = b and b = c follows a = c p: object q: object @dataclass(frozen=True) class CongrArg: # from a = b follows C[z:=a] = C[z:=b] z: str C: object p: object @dataclass(frozen=True) class Inst: # the fact `name` for concrete terms name: str args: tuple def subst(t, s): """Replaces at once the variables in the dict s (variable -> term).""" if isinstance(t, str): return s.get(t, t) return (t[0],) + tuple(subst(a, s) for a in t[1:]) def term_vars(t, signature=()): """Variables of a term: names (identifiers) outside the signature.""" if isinstance(t, str): return {t} if t.isidentifier() and t not in signature else set() return set().union(*(term_vars(a, signature) for a in t[1:])) class Kernel: def __init__(self, signature): self.signature = dict(signature) # symbol -> number of arguments self.facts = {} # name -> (variables, left, right) self.assumptions = {} # name -> axioms used def is_var(self, x): """Is x a variable: a name (identifier) outside the signature?""" return type(x) is str and x.isidentifier() and x not in self.signature def term(self, t): """Checks that t is a well-formed term of the signature. Only plain strings and tuples (type(...) is ...): a subclass of str with its own == could fool the comparison of middles in Trans.""" if type(t) is str: if self.signature.get(t) == 0 or self.is_var(t): return t elif (type(t) is tuple and t and type(t[0]) is str and self.signature.get(t[0]) == len(t) - 1): for a in t[1:]: self.term(a) return t raise ProofError(f"not a term: {t!r}") def conclusion(self, d): """The equation (left, right) that the proof d justifies.""" match d: case Refl(t): return self.term(t), t case Symm(p): a, b = self.conclusion(p) return b, a case Trans(p, q): a, b = self.conclusion(p) b2, c = self.conclusion(q) if b != b2: raise ProofError(f"Trans: middles {b!r} and {b2!r}") return a, c case CongrArg(z, C, p): if not self.is_var(z): raise ProofError(f"CongrArg: {z!r} is not a variable") self.term(C) a, b = self.conclusion(p) return subst(C, {z: a}), subst(C, {z: b}) case Inst(name, args): if name not in self.facts: raise ProofError(f"unknown fact: {name}") variables, l, r = self.facts[name] if len(args) != len(variables): raise ProofError(f"{name}: wrong number of arguments") s = dict(zip(variables, map(self.term, args))) return subst(l, s), subst(r, s) raise ProofError(f"not a proof: {d!r}") def _add(self, name, variables, l, r, assumptions): variables = tuple(variables) if name in self.facts: raise ProofError(f"name already taken: {name}") self.term(l), self.term(r) if not all(map(self.is_var, variables)): # a constant is no variable raise ProofError(f"{name}: {variables!r} are not all variables") if not (term_vars(l, self.signature) | term_vars(r, self.signature)) <= set(variables): raise ProofError(f"{name}: undeclared variable") self.facts[name] = (variables, l, r) self.assumptions[name] = frozenset(assumptions) def axiom(self, name, variables, l, r): self._add(name, variables, l, r, {name}) def theorem(self, name, variables, l, r, proof): """Adds ∀ variables, l = r — only when the proof justifies it.""" if self.conclusion(proof) != (l, r): raise ProofError(f"{name}: the proof justifies another equation") used = used_facts(proof) assumed = set().union(*(self.assumptions[n] for n in used)) self._add(name, variables, l, r, assumed) def used_facts(d): """Names of the facts the proof refers to (its Inst nodes).""" match d: case Inst(name, _): return {name} case Symm(p) | CongrArg(_, _, p): return used_facts(p) case Trans(p, q): return used_facts(p) | used_facts(q) return set()