Course page › Code of Lecture 3 › tactics.py · 298 lines
the Polish versionraw file

Tactics and a small solver for the kernel of 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"""Tactics and a small solver for the kernel of equational logic (lecture 3).
2
3A tactic is an ordinary program: it gets a goal (left, right) and returns a
4proof — a tree of the kernel's rules. A tactic may search, guess and make
5mistakes: the kernel checks its result anyway. That is why tactics need not
6be trusted.
7"""
8
9from collections import deque
10
11from kernel import Refl, Symm, Trans, CongrArg, Inst, subst
12from syntax import term, equation, show, show_equation
13
14
15class TacticError(Exception):
16 """The tactic cannot build a proof (this is not a kernel error)."""
17
18
19# --- tools on terms ----------------------------------------------------------
20
21def variables(t, result=None):
22 """Variables of a term in the order of first occurrence."""
23 result = [] if result is None else result
24 if isinstance(t, str):
25 if t.isidentifier() and t not in result:
26 result.append(t)
27 else:
28 for a in t[1:]:
29 variables(a, result)
30 return result
31
32
33def match_pattern(pattern, t, free, s):
34 """A substitution s of the variables in `free` with pattern[s] == t."""
35 if isinstance(pattern, str) and pattern in free:
36 if pattern in s:
37 return s if s[pattern] == t else None
38 return {**s, pattern: t}
39 if isinstance(pattern, str) or isinstance(t, str):
40 return s if pattern == t else None
41 if pattern[0] != t[0] or len(pattern) != len(t):
42 return None
43 for a, b in zip(pattern[1:], t[1:]):
44 s = match_pattern(a, b, free, s)
45 if s is None:
46 return None
47 return s
48
49
50def subterms(t):
51 """Subterms in prefix order (the whole term first)."""
52 yield t
53 if not isinstance(t, str):
54 for a in t[1:]:
55 yield from subterms(a)
56
57
58def abstract(t, u, z):
59 """Replaces each occurrence of the subterm u by the variable z (a hole)."""
60 if t == u:
61 return z
62 if isinstance(t, str):
63 return t
64 return (t[0],) + tuple(abstract(a, u, z) for a in t[1:])
65
66
67def fresh(*terms):
68 """A variable that does not occur in the given terms (for a hole)."""
69 taken = set()
70 for t in terms:
71 taken.update(variables(t))
72 for candidate in ["z"] + [f"z{i}" for i in range(1, 1000)]:
73 if candidate not in taken:
74 return candidate
75
76
77# --- composing proofs without needless steps ---------------------------------
78
79def trans(*proofs):
80 proofs = [d for d in proofs if d is not None and not isinstance(d, Refl)]
81 if not proofs:
82 return None
83 result = proofs[0]
84 for d in proofs[1:]:
85 result = Trans(result, d)
86 return result
87
88
89def congr(z, C, p):
90 if C == z:
91 return p
92 if z not in variables(C):
93 return None # a context without a hole: t = t, skip it
94 return CongrArg(z, C, p)
95
96
97def symm(p):
98 return None if p is None else (p.p if isinstance(p, Symm) else Symm(p))
99
100
101# --- tactics -----------------------------------------------------------------
102
103def _rule(kernel, text):
104 """'H3', '← H7', 'H7 x', '← H3 (x + y) z w' -> (name, backward, args)."""
105 text = text.strip()
106 backward = text.startswith("←")
107 text = text.lstrip("←").strip()
108 name, _, rest = text.partition(" ")
109 if name not in kernel.facts:
110 raise TacticError(f"unknown fact {name}")
111 args, depth, current = [], 0, ""
112 for c in rest:
113 if c == " " and depth == 0:
114 if current:
115 args.append(term(current))
116 current = ""
117 continue
118 depth += (c == "(") - (c == ")")
119 current += c
120 if current:
121 args.append(term(current))
122 return name, backward, (tuple(args) if args else None)
123
124
125def rewrite(kernel, goal, rule):
126 """One rw step: (new goal, function: proof of the new -> of the old)."""
127 name, backward, args = _rule(kernel, rule)
128 free, l, r = kernel.facts[name]
129 if backward:
130 l, r = r, l
131 L, R = goal
132 if args is not None: # explicit arguments: rw [H7 x]
133 s = dict(zip(free, args))
134 instance = None
135 for u in list(subterms(L)) + list(subterms(R)):
136 if u == subst(l, s):
137 instance = s
138 break
139 else: # arguments from matching: rw [H7]
140 if any(x not in variables(l) for x in free):
141 raise TacticError(f"rw [{rule}]: give the arguments")
142 instance = None
143 for u in list(subterms(L)) + list(subterms(R)):
144 instance = match_pattern(l, u, free, {})
145 if instance is not None:
146 break
147 if instance is None:
148 raise TacticError(f"rw [{rule}]: no pattern {show(l)} "
149 f"in {show_equation(goal)}")
150 arguments = tuple(instance[x] for x in free)
151 pe = Inst(name, arguments)
152 if backward:
153 pe = Symm(pe)
154 l2, r2 = subst(l, instance), subst(r, instance)
155 z = fresh(L, R, l2, r2)
156 CL, CR = abstract(L, l2, z), abstract(R, l2, z)
157 new = (subst(CL, {z: r2}), subst(CR, {z: r2}))
158
159 def compose(q): # L = L' (q: L' = R') R' = R
160 return trans(congr(z, CL, pe), q, symm(congr(z, CR, pe)))
161 return new, compose
162
163
164def rw(*rules):
165 """The tactic rw [h₁, h₂, …]: rewrites in turn, then tries rfl."""
166 def tactic(kernel, goal):
167 pieces = []
168 for rule in rules:
169 previous = goal
170 goal, compose = rewrite(kernel, goal, rule)
171 pieces.append((previous, compose))
172 if goal[0] != goal[1]:
173 raise TacticError(f"rw: the goal {show_equation(goal)} remains")
174 d = Refl(goal[0])
175 for previous, compose in reversed(pieces):
176 d = compose(d) or Refl(previous[0])
177 return d
178 return tactic
179
180
181def rfl():
182 def tactic(kernel, goal):
183 if goal[0] != goal[1]:
184 raise TacticError(f"rfl: the sides differ: {show_equation(goal)}")
185 return Refl(goal[0])
186 return tactic
187
188
189def calc(first, *steps):
190 """calc a = b := t₁; _ = c := t₂; … — a chain (each step a tactic)."""
191 def tactic(kernel, goal):
192 a = term(first)
193 if a != goal[0]:
194 raise TacticError(f"calc: start {show(a)}, goal {show(goal[0])}")
195 proofs = []
196 for text, t in steps:
197 b = term(text)
198 proofs.append(t(kernel, (a, b)))
199 a = b
200 if a != goal[1]:
201 raise TacticError(f"calc: end {show(a)}, goal {show(goal[1])}")
202 return trans(*proofs) or Refl(a)
203 return tactic
204
205
206def prove(kernel, name, text, tactic):
207 """The theorem ∀ variables, text: the tactic builds, the kernel checks."""
208 l, r = equation(text)
209 proof = tactic(kernel, (l, r))
210 kernel.theorem(name, variables(r, variables(l)), l, r, proof)
211 return proof
212
213
214# --- a small solver: breadth-first search from both ends ---------------------
215
216def _size(t):
217 return 1 if isinstance(t, str) else 1 + sum(_size(a) for a in t[1:])
218
219
220def _positions(t, path=()):
221 yield path, t
222 if not isinstance(t, str):
223 for i, a in enumerate(t[1:], start=1):
224 yield from _positions(a, path + (i,))
225
226
227def _insert(t, path, u):
228 if not path:
229 return u
230 i = path[0]
231 return t[:i] + (_insert(t[i], path[1:], u),) + t[i + 1:]
232
233
234def _neighbours(kernel, t, facts, pool, bound):
235 """Terms reachable from t by one rewrite (each fact in both directions)."""
236 for name in facts:
237 free, l, r = kernel.facts[name]
238 for backward, (pat, goal) in ((False, (l, r)), (True, (r, l))):
239 extra = [x for x in free if x not in variables(pat)]
240 for path, u in _positions(t):
241 s = match_pattern(pat, u, free, {})
242 if s is None:
243 continue
244 choices = [{}]
245 for x in extra: # variables the pattern does not fix
246 choices = [{**w, x: v} for w in choices for v in pool]
247 for w in choices:
248 s2 = {**s, **w}
249 new = _insert(t, path, subst(goal, s2))
250 if _size(new) <= bound:
251 args = tuple(s2[x] for x in free)
252 yield new, (path, name, backward, args, t)
253
254
255def _step_proof(path, name, backward, args, t):
256 pe = Inst(name, args)
257 if backward:
258 pe = Symm(pe)
259 z = fresh(t)
260 return congr(z, _insert(t, path, z), pe)
261
262
263def search(kernel, text, facts, max_size=9, limit=200_000):
264 """Searches for a proof of an equation breadth-first from both sides.
265
266 Returns (proof, number of visited terms). The proof is an ordinary tree
267 of rules, so the kernel checks it — the solver need not be trusted."""
268 l, r = equation(text)
269 pool = variables(r, variables(l))
270 parent = [{l: None}, {r: None}]
271 queue = deque([(l, 0), (r, 1)])
272 while queue and len(parent[0]) + len(parent[1]) < limit:
273 t, side = queue.popleft()
274 for new, step in _neighbours(kernel, t, facts, pool, max_size):
275 if new in parent[side]:
276 continue
277 parent[side][new] = step
278 if new in parent[1 - side]:
279 visited = len(parent[0]) + len(parent[1])
280 return _rebuild(parent, new, side), visited
281 queue.append((new, side))
282 return None, len(parent[0]) + len(parent[1])
283
284
285def _path(parent, t):
286 """Steps from the root of the search tree to t: a proof root = t."""
287 proofs = []
288 while parent[t] is not None:
289 path, name, backward, args, previous = parent[t]
290 proofs.append(_step_proof(path, name, backward, args, previous))
291 t = previous
292 return trans(*reversed(proofs))
293
294
295def _rebuild(parent, meeting, side):
296 from_left = _path(parent[0], meeting) # l = meeting
297 from_right = _path(parent[1], meeting) # r = meeting
298 return trans(from_left, symm(from_right)) or Refl(meeting)