Course page › Code of Lecture 3 › kernel.py · 153 lines
the Polish versionraw file

A minimal kernel for equational logic — lecture 3.

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

1"""A minimal kernel for equational logic — lecture 3.
2
3The kernel searches for nothing. It receives a finished proof — a tree built
4from five rules — and computes which equation the proof justifies. A theorem
5enters the environment only when that equation is exactly the announced one.
6The rules are named as in Lean: Eq.refl, Eq.symm, Eq.trans, congrArg and
7the application of a theorem to arguments.
8
9Terms are tuples: a variable is the string 'x', a constant is the string
10'0', and the application of a symbol to arguments is the tuple
11('+', 'x', ('n', 'x')). There are no quantifiers and no λ here, so
12substitution is a plain replacement of letters — that is why we can do
13without de Bruijn indices.
14"""
15
16from dataclasses import dataclass
17
18
19class ProofError(Exception):
20 """The kernel rejects a proof."""
21
22
23# --- proofs: five rules ------------------------------------------------------
24
25@dataclass(frozen=True)
26class Refl: # t = t
27 t: object
28
29@dataclass(frozen=True)
30class Symm: # from a = b follows b = a
31 p: object
32
33@dataclass(frozen=True)
34class Trans: # from a = b and b = c follows a = c
35 p: object
36 q: object
37
38@dataclass(frozen=True)
39class CongrArg: # from a = b follows C[z:=a] = C[z:=b]
40 z: str
41 C: object
42 p: object
43
44@dataclass(frozen=True)
45class Inst: # the fact `name` for concrete terms
46 name: str
47 args: tuple
48
49
50def subst(t, s):
51 """Replaces at once the variables in the dict s (variable -> term)."""
52 if isinstance(t, str):
53 return s.get(t, t)
54 return (t[0],) + tuple(subst(a, s) for a in t[1:])
55
56
57def term_vars(t, signature=()):
58 """Variables of a term: names (identifiers) outside the signature."""
59 if isinstance(t, str):
60 return {t} if t.isidentifier() and t not in signature else set()
61 return set().union(*(term_vars(a, signature) for a in t[1:]))
62
63
64class Kernel:
65 def __init__(self, signature):
66 self.signature = dict(signature) # symbol -> number of arguments
67 self.facts = {} # name -> (variables, left, right)
68 self.assumptions = {} # name -> axioms used
69
70 def is_var(self, x):
71 """Is x a variable: a name (identifier) outside the signature?"""
72 return type(x) is str and x.isidentifier() and x not in self.signature
73
74 def term(self, t):
75 """Checks that t is a well-formed term of the signature.
76
77 Only plain strings and tuples (type(...) is ...): a subclass of str
78 with its own == could fool the comparison of middles in Trans."""
79 if type(t) is str:
80 if self.signature.get(t) == 0 or self.is_var(t):
81 return t
82 elif (type(t) is tuple and t and type(t[0]) is str
83 and self.signature.get(t[0]) == len(t) - 1):
84 for a in t[1:]:
85 self.term(a)
86 return t
87 raise ProofError(f"not a term: {t!r}")
88
89 def conclusion(self, d):
90 """The equation (left, right) that the proof d justifies."""
91 match d:
92 case Refl(t):
93 return self.term(t), t
94 case Symm(p):
95 a, b = self.conclusion(p)
96 return b, a
97 case Trans(p, q):
98 a, b = self.conclusion(p)
99 b2, c = self.conclusion(q)
100 if b != b2:
101 raise ProofError(f"Trans: middles {b!r} and {b2!r}")
102 return a, c
103 case CongrArg(z, C, p):
104 if not self.is_var(z):
105 raise ProofError(f"CongrArg: {z!r} is not a variable")
106 self.term(C)
107 a, b = self.conclusion(p)
108 return subst(C, {z: a}), subst(C, {z: b})
109 case Inst(name, args):
110 if name not in self.facts:
111 raise ProofError(f"unknown fact: {name}")
112 variables, l, r = self.facts[name]
113 if len(args) != len(variables):
114 raise ProofError(f"{name}: wrong number of arguments")
115 s = dict(zip(variables, map(self.term, args)))
116 return subst(l, s), subst(r, s)
117 raise ProofError(f"not a proof: {d!r}")
118
119 def _add(self, name, variables, l, r, assumptions):
120 variables = tuple(variables)
121 if name in self.facts:
122 raise ProofError(f"name already taken: {name}")
123 self.term(l), self.term(r)
124 if not all(map(self.is_var, variables)): # a constant is no variable
125 raise ProofError(f"{name}: {variables!r} are not all variables")
126 if not (term_vars(l, self.signature)
127 | term_vars(r, self.signature)) <= set(variables):
128 raise ProofError(f"{name}: undeclared variable")
129 self.facts[name] = (variables, l, r)
130 self.assumptions[name] = frozenset(assumptions)
131
132 def axiom(self, name, variables, l, r):
133 self._add(name, variables, l, r, {name})
134
135 def theorem(self, name, variables, l, r, proof):
136 """Adds ∀ variables, l = r — only when the proof justifies it."""
137 if self.conclusion(proof) != (l, r):
138 raise ProofError(f"{name}: the proof justifies another equation")
139 used = used_facts(proof)
140 assumed = set().union(*(self.assumptions[n] for n in used))
141 self._add(name, variables, l, r, assumed)
142
143
144def used_facts(d):
145 """Names of the facts the proof refers to (its Inst nodes)."""
146 match d:
147 case Inst(name, _):
148 return {name}
149 case Symm(p) | CongrArg(_, _, p):
150 return used_facts(p)
151 case Trans(p, q):
152 return used_facts(p) | used_facts(q)
153 return set()