"""Tacticals: tactics made of tactics (the Boole Lab, lecture 3). A tactic gets the proof state -- a list of goals, each an equation l = r -- and either FAILS, changing nothing, or replaces the first goal by new goals together with a justification: a function that turns proofs of the new goals into a proof of the old one. This is the design of LCF (R. Milner and others, 1979). The kernel checks only the finished tree of rules, so no tactic, however badly written, proves a false equation: a bad tactic can only fail or run forever. Tacticals put tactics together. The lab writes them as Lean 4 does (in brackets: the names from LCF): t1; t2 t1, then t2 (THEN) t1 <;> t2 t2 on every goal that t1 made (THEN + ALL) first | t1 | t2 the first alternative that succeeds (ORELSE) try t t, or nothing if t fails (TRY) repeat t t again and again until it fails (REPEAT) iterate n t t exactly n times all_goals t t on every goal; fails if it fails on one of them any_goals t t on every goal; fails if it fails on all of them skip · done · fail "message" A tactic of the user is a name for such an expression (in Lean: a macro), e.g. bl tactic units := repeat (first | rw [H5] | rw [H6]). This module parses the notation (parse), prints it (show; in Lean: lean_macro), runs it on a list of goals and records what happened (Runner, a Trace), and checks two marks of a good tactic (analyse): * it stops: every turn of a repeat makes the goals smaller -- the sum of their sizes is a natural number, so it cannot go down forever; * every part can matter: no alternative stands after one that never fails, no repeat runs a body that never fails. The basic tactics (rw, nth_rw, rfl, symm, exact, trans) come from the lab as a function step(goal, text); this module knows nothing about terms beyond equality and a size. """ import time from dataclasses import dataclass from tactics import TacticError HOLE = "□" # a gap to fill in (the tactic workshop) STEPS = ("rw", "nth_rw", "rfl", "symm", "exact", "trans", "ac_rfl") PREFIX = ("try", "repeat", "all_goals", "any_goals") KEYWORDS = frozenset(STEPS + PREFIX + ("first", "iterate", "skip", "done", "fail", "auto", "rw_ac", "ac_simp")) SIMPLE = frozenset(("step", "call", "skip", "done", "fail", "hole")) MAX_ITERATE = 100 # iterate n: 1 <= n <= MAX_ITERATE MAX_DEPTH = 40 # nesting of brackets, combinators and calls MAX_STEPS = 2000 # basic steps tried by one run MAX_NODES = 20000 # parts of the expression run by one run MAX_SIZE = 3000 # symbols of a goal made by a step MAX_TERM_DEPTH = 100 # nesting of a term made by a step (the lab's # functions on terms are recursive) MAX_TRACE = 600 # entries of the trace SECONDS = 4.0 # time of one run @dataclass(frozen=True) class Node: """A tactic expression. kind: seq, then, first, try, repeat, iterate, all_goals, any_goals, skip, done, fail, step (a basic tactic, its text), call (a tactic of the user, its name) or hole; parts: the sub-expressions; count: n of iterate; span: (start, end) in the source text.""" kind: str parts: tuple = () text: str = "" count: int = 0 span: tuple = (0, 0) greedy: bool = False # a prefix combinator took a ; sequence # --- reading ----------------------------------------------------------------- def parse_error(what, pos, text): return TacticError(("tc_parse", what, pos, text)) def blank_comments(text): """The text with each comment (-- to the end of the line, outside a string) replaced by spaces, so that positions stay the same.""" out, in_string, i = [], False, 0 while i < len(text): c = text[i] if c == '"': in_string = not in_string elif c == "\n": in_string = False elif not in_string and text.startswith("--", i): end = text.find("\n", i) end = len(text) if end < 0 else end out.append(" " * (end - i)) i = end continue out.append(c) i += 1 return "".join(out) def has_separator(text): """Is there a ;, <;> or | outside brackets? (Then the line is not one basic tactic.)""" depth = 0 for i, c in enumerate(text): if c in "([": depth += 1 elif c in ")]": depth -= 1 elif depth == 0 and (c in ";|" or text.startswith("<;>", i)): return True return False class _Parser: """Recursive descent, as Lean reads it on one line: a prefix combinator (try, repeat, all_goals, any_goals, iterate n) and every alternative of first take the whole sequence after them, up to |, ) or the end; <;> binds more tightly than ;.""" def __init__(self, text, check_step=None): self.s, self.i, self.check_step, self.depth = text, 0, check_step, 0 def error(self, what, pos=None): return parse_error(what, self.i if pos is None else pos, self.s) def ws(self): while self.i < len(self.s) and self.s[self.i].isspace(): self.i += 1 def at(self, token): self.ws() return self.s.startswith(token, self.i) def word(self): self.ws() j = self.i while j < len(self.s) and (self.s[j].isalnum() or self.s[j] == "_"): j += 1 return self.s[self.i:j] def deeper(self): self.depth += 1 if self.depth > MAX_DEPTH: raise self.error("depth") def seq(self): self.ws() start = self.i parts = [self.then()] while self.at(";"): self.i += 1 parts.append(self.then()) if len(parts) == 1: return parts[0] return Node("seq", tuple(parts), span=(start, parts[-1].span[1])) def then(self): self.ws() start = self.i node, chain = self.unit(), 0 while self.at("<;>"): self.i += 3 chain += 1 if self.depth + chain > MAX_DEPTH: raise self.error("depth") right = self.unit() node = Node("then", (node, right), span=(start, right.span[1])) return node def unit(self): self.ws() start = self.i if self.i >= len(self.s): raise self.error("missing") if self.at("("): self.i += 1 self.deeper() node = self.seq() self.depth -= 1 if not self.at(")"): raise self.error("close") self.i += 1 return node if self.at(HOLE): self.i += len(HOLE) return Node("hole", span=(start, self.i)) w = self.word() if not w or not w[0].isascii() or w[0].isdigit(): raise self.error("bar" if self.at("|") else "stray_close" if self.at(")") else "unexpected") if w == "first": self.i += len(w) self.deeper() alternatives = [] while self.at("|"): self.i += 1 alternatives.append(self.seq()) self.depth -= 1 if not alternatives: raise self.error("first") return Node("first", tuple(alternatives), span=(start, alternatives[-1].span[1])) if w in PREFIX or w == "iterate": self.i += len(w) count = 0 if w == "iterate": number = self.word() if not (number.isascii() and number.isdecimal()) or not \ 1 <= int(number) <= MAX_ITERATE: raise self.error("count") count = int(number) self.i += len(number) self.deeper() bracket = self.at("(") body = self.seq() self.depth -= 1 return Node(w, (body,), count=count, span=(start, body.span[1]), greedy=body.kind == "seq" and not bracket) if w in ("skip", "done"): self.i += len(w) return Node(w, span=(start, self.i)) if w == "fail": self.i += len(w) message = "" if self.at('"'): end = self.s.find('"', self.i + 1) if end < 0: raise self.error("string") message = self.s[self.i + 1:end] if "\\" in message: # Lean would read an escape raise self.error("escape") self.i = end + 1 return Node("fail", text=message, span=(start, self.i)) if w == "auto": raise self.error("auto") if w in ("rw_ac", "ac_simp"): # no Lean tactic does this raise self.error("ac_tactic") if w in STEPS: text = self.step_text() end = self.i if self.check_step is not None: try: self.check_step(text) except TacticError as e: raise TacticError(("tc_step", e, start, end, self.s)) from None return Node("step", text=text, span=(start, end)) self.i += len(w) return Node("call", text=w, span=(start, self.i)) def step_text(self): """A basic tactic: up to ;, <;>, | or a ) that closes a group.""" start, depth = self.i, 0 while self.i < len(self.s): c = self.s[self.i] if c in "([": depth += 1 elif c in ")]": if depth == 0: break depth -= 1 elif depth == 0 and (c in ";|" or self.s.startswith("<;>", self.i)): break self.i += 1 while self.i > start and self.s[self.i - 1].isspace(): self.i -= 1 return " ".join(self.s[start:self.i].split()) def parse(text, check_step=None): """The tactic expression in `text` -> Node; TacticError on a syntax error (key 'tc_parse' with a position, or 'tc_step' for a basic tactic that check_step rejects).""" if not text.strip(): raise parse_error("empty", 0, text) p = _Parser(text, check_step) node = p.seq() p.ws() if p.i < len(text): raise p.error("stray_bar" if text[p.i] == "|" else "stray_close" if text[p.i] == ")" else "unexpected") return node # --- writing ----------------------------------------------------------------- def show(node, lean_step=None): """The expression as text: the lab's notation, or Lean 4 when lean_step translates a basic tactic. Compound parts get brackets, so the text reads back as the same tree.""" def part(p): s = show(p, lean_step) return s if p.kind in SIMPLE else f"({s})" k = node.kind if k == "step": return lean_step(node.text) if lean_step else node.text if k == "call": return node.text if k == "hole": return HOLE if k in ("skip", "done"): return k if k == "fail": return f'fail "{node.text}"' if node.text else "fail" if k == "seq": return "; ".join(part(p) for p in node.parts) if k == "then": a, b = node.parts left = show(a, lean_step) if a.kind == "then" else part(a) return f"{left} <;> {part(b)}" if k == "first": return "first " + " ".join("| " + part(p) for p in node.parts) if k == "iterate": return f"iterate {node.count} {part(node.parts[0])}" return f"{k} {part(node.parts[0])}" def lean_macro(name, node, lean_step): """A tactic of the user as a Lean 4 macro. Hygiene is off, so the names in it (H5, x, α) mean what they mean where it is used.""" return ("set_option hygiene false in\n" f'macro "{name}" : tactic => `(tactic| ({show(node, lean_step)}))') def walk(node): """The node and all its parts, in prefix order.""" stack = [node] while stack: n = stack.pop() yield n stack.extend(reversed(n.parts)) def calls(node): """The names of the user tactics that the expression calls.""" return [n.text for n in walk(node) if n.kind == "call"] def paths(node, path="0", result=None): """id(part) -> its path ("0", "0.1", "0.1.0", …): the address of a part in the expression (the page draws and edits by it).""" result = {} if result is None else result stack = [(node, path)] while stack: n, p = stack.pop() result[id(n)] = p stack.extend((c, f"{p}.{i}") for i, c in enumerate(n.parts)) return result def tree_json(node, path="0"): """The structure for the page: kind, text, span, count, path, parts.""" return {"kind": node.kind, "text": show(node), "span": list(node.span), "count": node.count, "path": path, "parts": [tree_json(p, f"{path}.{i}") for i, p in enumerate(node.parts)]} # --- running ----------------------------------------------------------------- @dataclass(frozen=True) class State: """Goals ((id, equation), ...) -- the first is the main goal -- and the justifications so far: a linked list (link, earlier links) of links (goal id, ids of its new goals, compose, step text). A failed branch simply drops its state: the state is never changed.""" goals: tuple links: tuple = () next_id: int = 1 def justifications(state): """The links of a state, the oldest first.""" result, links = [], state.links while links: result.append(links[0]) links = links[1] return result[::-1] def goals_key(state): return tuple(eq for _, eq in state.goals) class LimitError(TacticError): """A limit of the runner -- steps, time, size, a loop of repeat. It stops the whole tactic: first, try and repeat do not catch it (in Lean such a tactic would run until the time runs out).""" class Trace: """What one part of the expression did: ok or the error, the goals before and after it (their number and the first one), the traces of its parts, the turn (of repeat or iterate) and, for repeat, the number of turns.""" __slots__ = ("node", "ok", "error", "before", "after", "parts", "turn", "turns", "info") def __init__(self, node, before, turn): self.node, self.before, self.turn = node, before, turn self.ok, self.error, self.after, self.parts = None, None, None, [] self.turns = self.info = None def snapshot(state): return (len(state.goals), state.goals[0][1] if state.goals else None) class Runner: """Runs an expression on a State. step(goal, text) does one basic tactic on one goal and returns (new goals, compose) or raises TacticError; tactics: name -> Node; size(goal): its symbols.""" def __init__(self, step, tactics=None, size=None, depth=None, max_steps=MAX_STEPS, seconds=SECONDS, max_size=MAX_SIZE, max_trace=MAX_TRACE, max_nodes=MAX_NODES): self.step, self.tactics, self.size = step, tactics or {}, size self.depth = depth self.max_steps, self.max_size = max_steps, max_size self.max_trace, self.max_nodes = max_trace, max_nodes self.seconds = seconds self.deadline = time.perf_counter() + seconds self.steps = self.nodes = self.recorded = 0 self.truncated = False def run(self, node, state): """-> (end state, trace). On failure the TacticError carries the trace in its attribute `trace`.""" root = [] try: end = self._run(node, state, root, 0, 0) except TacticError as e: e.trace = root[0] if root else None raise return end, root[0] def _tick(self): self.nodes += 1 if self.nodes > self.max_nodes: raise LimitError(("tc_nodes", self.max_nodes)) if time.perf_counter() > self.deadline: raise LimitError(("tc_time", self.seconds)) def _trace(self, node, state, out, turn): if out is None: return None if self.recorded >= self.max_trace: self.truncated = True return None self.recorded += 1 t = Trace(node, snapshot(state), turn) out.append(t) return t def _run(self, node, state, out, depth, turn): if depth > MAX_DEPTH: raise LimitError(("tc_depth", MAX_DEPTH)) self._tick() t = self._trace(node, state, out, turn) kids = t.parts if t is not None else None try: end = getattr(self, "_" + node.kind)(node, state, kids, depth, t) except TacticError as e: if t is not None: t.ok, t.error = False, e raise if t is not None: t.ok, t.after = True, snapshot(end) return end def _step(self, node, state, kids, depth, t): if not state.goals: raise TacticError(("tc_no_goals",)) self.steps += 1 if self.steps > self.max_steps: raise LimitError(("tc_steps", self.max_steps)) gid, goal = state.goals[0] try: result = self.step(goal, node.text) except RecursionError: raise LimitError(("tc_deep", MAX_TERM_DEPTH)) from None new, compose = result[0], result[1] if t is not None and len(result) > 2: t.info = result[2] # what the kernel gets for g in new: if self.size is not None and self.size(g) > self.max_size: raise LimitError(("tc_size", self.size(g), self.max_size)) if self.depth is not None and self.depth(g) > MAX_TERM_DEPTH: raise LimitError(("tc_deep", MAX_TERM_DEPTH)) ids = tuple(range(state.next_id, state.next_id + len(new))) return State(tuple(zip(ids, new)) + state.goals[1:], ((gid, ids, compose, node.text), state.links), state.next_id + len(new)) def _call(self, node, state, kids, depth, t): body = self.tactics.get(node.text) if body is None: raise TacticError(("tc_unknown", node.text)) return self._run(body, state, kids, depth + 1, 0) def _skip(self, node, state, kids, depth, t): return state def _done(self, node, state, kids, depth, t): if state.goals: raise TacticError(("tc_done", len(state.goals))) return state def _fail(self, node, state, kids, depth, t): raise TacticError(("tc_fail", node.text)) def _hole(self, node, state, kids, depth, t): raise TacticError(("tc_hole",)) def _seq(self, node, state, kids, depth, t): for p in node.parts: state = self._run(p, state, kids, depth + 1, 0) return state def _then(self, node, state, kids, depth, t): """t1 <;> t2 as in Lean: focus on the main goal, t1, then t2 on every goal that t1 left.""" if not state.goals: raise TacticError(("tc_no_goals",)) a, b = node.parts focus = State(state.goals[:1], state.links, state.next_id) middle = self._run(a, focus, kids, depth + 1, 0) end = self._each(b, middle, kids, depth, True) return State(end.goals + state.goals[1:], end.links, end.next_id) def _each(self, body, state, kids, depth, need_all): """body on every goal, each on its own (Lean: focus).""" goals, links, next_id, succeeded = [], state.links, state.next_id, 0 for g in state.goals: try: r = self._run(body, State((g,), links, next_id), kids, depth + 1, 0) except LimitError: raise except TacticError: if need_all: raise goals.append(g) continue goals.extend(r.goals) links, next_id = r.links, r.next_id succeeded += 1 if not need_all and not succeeded: raise TacticError(("tc_any_goals", len(state.goals))) return State(tuple(goals), links, next_id) def _all_goals(self, node, state, kids, depth, t): return self._each(node.parts[0], state, kids, depth, True) def _any_goals(self, node, state, kids, depth, t): return self._each(node.parts[0], state, kids, depth, False) def _first(self, node, state, kids, depth, t): for p in node.parts: try: return self._run(p, state, kids, depth + 1, 0) except LimitError: raise except TacticError: continue raise TacticError(("tc_first", len(node.parts))) def _try(self, node, state, kids, depth, t): try: return self._run(node.parts[0], state, kids, depth + 1, 0) except LimitError: raise except TacticError: return state def _iterate(self, node, state, kids, depth, t): for k in range(1, node.count + 1): state = self._run(node.parts[0], state, kids, depth + 1, k) return state def _repeat(self, node, state, kids, depth, t): """The body while it succeeds. A turn after which the goals are the same as after an earlier one would repeat for ever: that is a LimitError (Lean would run until it hits its limits).""" seen = {goals_key(state): 0} turn = 0 while True: try: after = self._run(node.parts[0], state, kids, depth + 1, turn + 1) except LimitError: raise except TacticError: break turn += 1 if t is not None: t.turns = turn key = goals_key(after) if key in seen: first = after.goals[0][1] if after.goals else None raise LimitError(("tc_loop", turn, seen[key], first)) seen[key] = turn state = after if t is not None: t.turns = turn return state # --- a good tactic: analysis ------------------------------------------------- # # The measure is the sum of the sizes of all goals (an equation l = r # counts size(l) + size(r) + 1). A successful run of a part of a tactic # can make it smaller ("shrinks"), keep it or make it smaller ("same"), # perhaps make it larger ("grows") -- or never succeed ("never"). SHRINKS, SAME, GROWS, NEVER = "shrinks", "same", "grows", "never" _ORDER = (SHRINKS, SAME, GROWS) def _occurrences(t, v): if isinstance(t, str): return 1 if t == v else 0 return sum(_occurrences(a, v) for a in t[1:]) def _metavariables(t, result): if isinstance(t, str): if t.startswith("?"): result.add(t) else: for a in t[1:]: _metavariables(a, result) return result def metavariables(t): """The metavariables (?x) of a pattern.""" return _metavariables(t, set()) def rule_effect(l, r, size): """What rewriting l -> r does to the size of a term, for EVERY instance: shrinks when l is larger than r and no metavariable (?x) occurs more often in r than in l -- then size(σl) - size(σr) = size(l) - size(r) + Σ (occ_l(x) - occ_r(x)) (size(σx) - 1) > 0.""" ms = _metavariables(l, set()) | _metavariables(r, set()) if any(_occurrences(r, v) > _occurrences(l, v) for v in ms): return GROWS a, b = size(l), size(r) return SHRINKS if a > b else SAME if a == b else GROWS def in_sequence(effects): """The effect of parts that all run, one after another.""" effects = list(effects) if NEVER in effects: return NEVER if GROWS in effects: return GROWS return SHRINKS if SHRINKS in effects else SAME def worst(effects): """The effect of one of several parts (we do not know which).""" effects = [e for e in effects if e != NEVER] if not effects: return NEVER return max(effects, key=_ORDER.index) class Analysis: """effect(node) -> (effect, can_fail): can_fail is False when the part succeeds on every goal list with a goal (skip, try, repeat, symm). step_info(text) -> (effect, can_fail, rules) for a basic tactic, rules: [(rule text, effect, l, r)]; it raises TacticError for a step that cannot run here (an unknown fact).""" def __init__(self, step_info, tactics): self.step_info, self.tactics = step_info, tactics self.findings, self.memo = [], {} def note(self, level, key, node, *data): self.findings.append((level, key, node.span, data)) def effect(self, node): """(effect, can it fail while a goal is left, can it fail with no goal at all). A basic step always fails without a goal; skip, try and repeat never fail.""" k = node.kind if k == "step": try: e, can_fail, _ = self.step_info(node.text) except TacticError: return GROWS, True, True return e, can_fail, True if k == "call": if node.text not in self.memo: self.memo[node.text] = (GROWS, True, True) # computing body = self.tactics.get(node.text) self.memo[node.text] = self.effect(body) if body \ else (GROWS, True, True) return self.memo[node.text] if k == "skip": return SAME, False, False if k == "done": return SAME, True, False if k == "fail": return NEVER, True, True if k == "hole": return GROWS, True, True parts = [self.effect(p) for p in node.parts] if k == "seq": return (in_sequence(e for e, _, _ in parts), any(f for _, f, _ in parts), any(g for _, _, g in parts)) if k == "then": # <;> needs a goal return (in_sequence(e for e, _, _ in parts), any(f for _, f, _ in parts), True) if k == "first": return (worst(e for e, _, _ in parts), all(f for _, f, _ in parts), all(g for _, _, g in parts)) e, can_fail, empty = parts[0] if k in ("try", "repeat"): return worst([SAME, e]), False, False if k == "all_goals": return worst([SAME, e]), can_fail, False if k == "any_goals": return e, True, True return e, can_fail, empty # iterate def rules(self, node): """The rewrite rules inside a part: (text, effect, l, r).""" result, seen = [], set() for n in walk(node): if n.kind == "call" and n.text not in seen: seen.add(n.text) body = self.tactics.get(n.text) if body is not None: result += self.rules(body) if n.kind == "step": try: result += self.step_info(n.text)[2] except TacticError: pass return result def check(self, node): for n in walk(node): k = n.kind if k == "step": try: self.step_info(n.text) except TacticError as e: self.note("error", "step", n, n.text, e) elif k == "call" and n.text not in self.tactics: self.note("error", "unknown", n, n.text) elif k == "hole": self.note("info", "hole", n) elif k == "repeat": self.check_repeat(n) elif k == "first": self.check_first(n) elif k == "try" and not self.effect(n.parts[0])[2]: self.note("info", "try_useless", n, show(n.parts[0])) if n.greedy: self.note("warning", "greedy", n, k, show(n), show(n.parts[0].parts[0])) elif k == "then" and n.parts[0].kind == "step" and \ n.parts[0].text.split()[0] in ("rw", "nth_rw", "rfl", "exact", "symm", "ac_rfl"): self.note("info", "then_one", n, show(n.parts[0])) return self.findings def check_repeat(self, n): body = n.parts[0] e, can_fail, can_fail_empty = self.effect(body) rules = self.rules(body) if not can_fail_empty: self.note("error", "repeat_never_fails", n, show(body)) elif not can_fail: self.note("warning", "repeat_fails_only_empty", n, show(body)) elif e == NEVER: self.note("warning", "repeat_never_succeeds", n, show(body)) elif e == SHRINKS: self.note("ok", "repeat_stops", n, rules) elif e == SAME: self.note("warning", "repeat_may_loop", n, [r for r in rules if r[1] == SAME]) else: self.note("warning", "repeat_may_grow", n, [r for r in rules if r[1] == GROWS]) def check_first(self, n): if len(n.parts) == 1: self.note("info", "first_one", n) for i, p in enumerate(n.parts[:-1]): if not self.effect(p)[1]: self.note("warning", "first_unreachable", n, show(p), [show(q) for q in n.parts[i + 1:]]) break def analyse(node, step_info, tactics): """Findings about a tactic: [(level, key, span, data)], level: ok, info, warning or error.""" return Analysis(step_info, tactics).check(node)