Tacticals: tactics made of tactics (the Boole Lab, lecture 3).
Code with colored syntax: click a line number to get a link to it; an underlined name leads to its definition.
| 1 | """Tacticals: tactics made of tactics (the Boole Lab, lecture 3). |
| 2 | |
| 3 | A tactic gets the proof state -- a list of goals, each an equation |
| 4 | l = r -- and either FAILS, changing nothing, or replaces the first goal |
| 5 | by new goals together with a justification: a function that turns |
| 6 | proofs of the new goals into a proof of the old one. This is the design |
| 7 | of LCF (R. Milner and others, 1979). The kernel checks only the finished |
| 8 | tree of rules, so no tactic, however badly written, proves a false |
| 9 | equation: a bad tactic can only fail or run forever. |
| 10 | |
| 11 | Tacticals put tactics together. The lab writes them as Lean 4 does (in |
| 12 | brackets: the names from LCF): |
| 13 | |
| 14 | t1; t2 t1, then t2 (THEN) |
| 15 | t1 <;> t2 t2 on every goal that t1 made (THEN + ALL) |
| 16 | first | t1 | t2 the first alternative that succeeds (ORELSE) |
| 17 | try t t, or nothing if t fails (TRY) |
| 18 | repeat t t again and again until it fails (REPEAT) |
| 19 | iterate n t t exactly n times |
| 20 | all_goals t t on every goal; fails if it fails on one of them |
| 21 | any_goals t t on every goal; fails if it fails on all of them |
| 22 | skip · done · fail "message" |
| 23 | |
| 24 | A tactic of the user is a name for such an expression (in Lean: a |
| 25 | macro), e.g. bl tactic units := repeat (first | rw [H5] | rw [H6]). |
| 26 | |
| 27 | This module parses the notation (parse), prints it (show; in Lean: |
| 28 | lean_macro), runs it on a list of goals and records what happened |
| 29 | (Runner, a Trace), and checks two marks of a good tactic (analyse): |
| 30 | |
| 31 | * it stops: every turn of a repeat makes the goals smaller -- the sum |
| 32 | of their sizes is a natural number, so it cannot go down forever; |
| 33 | * every part can matter: no alternative stands after one that never |
| 34 | fails, no repeat runs a body that never fails. |
| 35 | |
| 36 | The basic tactics (rw, nth_rw, rfl, symm, exact, trans) come from the |
| 37 | lab as a function step(goal, text); this module knows nothing about |
| 38 | terms beyond equality and a size. |
| 39 | """ |
| 40 | |
| 41 | import time |
| 42 | from dataclasses import dataclass |
| 43 | |
| 44 | from tactics import TacticError |
| 45 | |
| 46 | HOLE = "□" # a gap to fill in (the tactic workshop) |
| 47 | STEPS = ("rw", "nth_rw", "rfl", "symm", "exact", "trans", "ac_rfl") |
| 48 | PREFIX = ("try", "repeat", "all_goals", "any_goals") |
| 49 | KEYWORDS = frozenset(STEPS + PREFIX + ("first", "iterate", "skip", "done", |
| 50 | "fail", "auto", "rw_ac", "ac_simp")) |
| 51 | SIMPLE = frozenset(("step", "call", "skip", "done", "fail", "hole")) |
| 52 | MAX_ITERATE = 100 # iterate n: 1 <= n <= MAX_ITERATE |
| 53 | MAX_DEPTH = 40 # nesting of brackets, combinators and calls |
| 54 | MAX_STEPS = 2000 # basic steps tried by one run |
| 55 | MAX_NODES = 20000 # parts of the expression run by one run |
| 56 | MAX_SIZE = 3000 # symbols of a goal made by a step |
| 57 | MAX_TERM_DEPTH = 100 # nesting of a term made by a step (the lab's |
| 58 | # functions on terms are recursive) |
| 59 | MAX_TRACE = 600 # entries of the trace |
| 60 | SECONDS = 4.0 # time of one run |
| 61 | |
| 62 | |
| 63 | @dataclass(frozen=True) |
| 64 | class Node: |
| 65 | """A tactic expression. kind: seq, then, first, try, repeat, iterate, |
| 66 | all_goals, any_goals, skip, done, fail, step (a basic tactic, its |
| 67 | text), call (a tactic of the user, its name) or hole; parts: the |
| 68 | sub-expressions; count: n of iterate; span: (start, end) in the |
| 69 | source text.""" |
| 70 | kind: str |
| 71 | parts: tuple = () |
| 72 | text: str = "" |
| 73 | count: int = 0 |
| 74 | span: tuple = (0, 0) |
| 75 | greedy: bool = False # a prefix combinator took a ; sequence |
| 76 | |
| 77 | |
| 78 | # --- reading ----------------------------------------------------------------- |
| 79 | |
| 80 | def parse_error(what, pos, text): |
| 81 | return TacticError(("tc_parse", what, pos, text)) |
| 82 | |
| 83 | |
| 84 | def blank_comments(text): |
| 85 | """The text with each comment (-- to the end of the line, outside a |
| 86 | string) replaced by spaces, so that positions stay the same.""" |
| 87 | out, in_string, i = [], False, 0 |
| 88 | while i < len(text): |
| 89 | c = text[i] |
| 90 | if c == '"': |
| 91 | in_string = not in_string |
| 92 | elif c == "\n": |
| 93 | in_string = False |
| 94 | elif not in_string and text.startswith("--", i): |
| 95 | end = text.find("\n", i) |
| 96 | end = len(text) if end < 0 else end |
| 97 | out.append(" " * (end - i)) |
| 98 | i = end |
| 99 | continue |
| 100 | out.append(c) |
| 101 | i += 1 |
| 102 | return "".join(out) |
| 103 | |
| 104 | |
| 105 | def has_separator(text): |
| 106 | """Is there a ;, <;> or | outside brackets? (Then the line is not |
| 107 | one basic tactic.)""" |
| 108 | depth = 0 |
| 109 | for i, c in enumerate(text): |
| 110 | if c in "([": |
| 111 | depth += 1 |
| 112 | elif c in ")]": |
| 113 | depth -= 1 |
| 114 | elif depth == 0 and (c in ";|" or text.startswith("<;>", i)): |
| 115 | return True |
| 116 | return False |
| 117 | |
| 118 | |
| 119 | class _Parser: |
| 120 | """Recursive descent, as Lean reads it on one line: a prefix |
| 121 | combinator (try, repeat, all_goals, any_goals, iterate n) and every |
| 122 | alternative of first take the whole sequence after them, up to |, ) |
| 123 | or the end; <;> binds more tightly than ;.""" |
| 124 | |
| 125 | def __init__(self, text, check_step=None): |
| 126 | self.s, self.i, self.check_step, self.depth = text, 0, check_step, 0 |
| 127 | |
| 128 | def error(self, what, pos=None): |
| 129 | return parse_error(what, self.i if pos is None else pos, self.s) |
| 130 | |
| 131 | def ws(self): |
| 132 | while self.i < len(self.s) and self.s[self.i].isspace(): |
| 133 | self.i += 1 |
| 134 | |
| 135 | def at(self, token): |
| 136 | self.ws() |
| 137 | return self.s.startswith(token, self.i) |
| 138 | |
| 139 | def word(self): |
| 140 | self.ws() |
| 141 | j = self.i |
| 142 | while j < len(self.s) and (self.s[j].isalnum() or self.s[j] == "_"): |
| 143 | j += 1 |
| 144 | return self.s[self.i:j] |
| 145 | |
| 146 | def deeper(self): |
| 147 | self.depth += 1 |
| 148 | if self.depth > MAX_DEPTH: |
| 149 | raise self.error("depth") |
| 150 | |
| 151 | def seq(self): |
| 152 | self.ws() |
| 153 | start = self.i |
| 154 | parts = [self.then()] |
| 155 | while self.at(";"): |
| 156 | self.i += 1 |
| 157 | parts.append(self.then()) |
| 158 | if len(parts) == 1: |
| 159 | return parts[0] |
| 160 | return Node("seq", tuple(parts), span=(start, parts[-1].span[1])) |
| 161 | |
| 162 | def then(self): |
| 163 | self.ws() |
| 164 | start = self.i |
| 165 | node, chain = self.unit(), 0 |
| 166 | while self.at("<;>"): |
| 167 | self.i += 3 |
| 168 | chain += 1 |
| 169 | if self.depth + chain > MAX_DEPTH: |
| 170 | raise self.error("depth") |
| 171 | right = self.unit() |
| 172 | node = Node("then", (node, right), span=(start, right.span[1])) |
| 173 | return node |
| 174 | |
| 175 | def unit(self): |
| 176 | self.ws() |
| 177 | start = self.i |
| 178 | if self.i >= len(self.s): |
| 179 | raise self.error("missing") |
| 180 | if self.at("("): |
| 181 | self.i += 1 |
| 182 | self.deeper() |
| 183 | node = self.seq() |
| 184 | self.depth -= 1 |
| 185 | if not self.at(")"): |
| 186 | raise self.error("close") |
| 187 | self.i += 1 |
| 188 | return node |
| 189 | if self.at(HOLE): |
| 190 | self.i += len(HOLE) |
| 191 | return Node("hole", span=(start, self.i)) |
| 192 | w = self.word() |
| 193 | if not w or not w[0].isascii() or w[0].isdigit(): |
| 194 | raise self.error("bar" if self.at("|") else |
| 195 | "stray_close" if self.at(")") else "unexpected") |
| 196 | if w == "first": |
| 197 | self.i += len(w) |
| 198 | self.deeper() |
| 199 | alternatives = [] |
| 200 | while self.at("|"): |
| 201 | self.i += 1 |
| 202 | alternatives.append(self.seq()) |
| 203 | self.depth -= 1 |
| 204 | if not alternatives: |
| 205 | raise self.error("first") |
| 206 | return Node("first", tuple(alternatives), |
| 207 | span=(start, alternatives[-1].span[1])) |
| 208 | if w in PREFIX or w == "iterate": |
| 209 | self.i += len(w) |
| 210 | count = 0 |
| 211 | if w == "iterate": |
| 212 | number = self.word() |
| 213 | if not (number.isascii() and number.isdecimal()) or not \ |
| 214 | 1 <= int(number) <= MAX_ITERATE: |
| 215 | raise self.error("count") |
| 216 | count = int(number) |
| 217 | self.i += len(number) |
| 218 | self.deeper() |
| 219 | bracket = self.at("(") |
| 220 | body = self.seq() |
| 221 | self.depth -= 1 |
| 222 | return Node(w, (body,), count=count, span=(start, body.span[1]), |
| 223 | greedy=body.kind == "seq" and not bracket) |
| 224 | if w in ("skip", "done"): |
| 225 | self.i += len(w) |
| 226 | return Node(w, span=(start, self.i)) |
| 227 | if w == "fail": |
| 228 | self.i += len(w) |
| 229 | message = "" |
| 230 | if self.at('"'): |
| 231 | end = self.s.find('"', self.i + 1) |
| 232 | if end < 0: |
| 233 | raise self.error("string") |
| 234 | message = self.s[self.i + 1:end] |
| 235 | if "\\" in message: # Lean would read an escape |
| 236 | raise self.error("escape") |
| 237 | self.i = end + 1 |
| 238 | return Node("fail", text=message, span=(start, self.i)) |
| 239 | if w == "auto": |
| 240 | raise self.error("auto") |
| 241 | if w in ("rw_ac", "ac_simp"): # no Lean tactic does this |
| 242 | raise self.error("ac_tactic") |
| 243 | if w in STEPS: |
| 244 | text = self.step_text() |
| 245 | end = self.i |
| 246 | if self.check_step is not None: |
| 247 | try: |
| 248 | self.check_step(text) |
| 249 | except TacticError as e: |
| 250 | raise TacticError(("tc_step", e, start, end, |
| 251 | self.s)) from None |
| 252 | return Node("step", text=text, span=(start, end)) |
| 253 | self.i += len(w) |
| 254 | return Node("call", text=w, span=(start, self.i)) |
| 255 | |
| 256 | def step_text(self): |
| 257 | """A basic tactic: up to ;, <;>, | or a ) that closes a group.""" |
| 258 | start, depth = self.i, 0 |
| 259 | while self.i < len(self.s): |
| 260 | c = self.s[self.i] |
| 261 | if c in "([": |
| 262 | depth += 1 |
| 263 | elif c in ")]": |
| 264 | if depth == 0: |
| 265 | break |
| 266 | depth -= 1 |
| 267 | elif depth == 0 and (c in ";|" or |
| 268 | self.s.startswith("<;>", self.i)): |
| 269 | break |
| 270 | self.i += 1 |
| 271 | while self.i > start and self.s[self.i - 1].isspace(): |
| 272 | self.i -= 1 |
| 273 | return " ".join(self.s[start:self.i].split()) |
| 274 | |
| 275 | |
| 276 | def parse(text, check_step=None): |
| 277 | """The tactic expression in `text` -> Node; TacticError on a syntax |
| 278 | error (key 'tc_parse' with a position, or 'tc_step' for a basic tactic |
| 279 | that check_step rejects).""" |
| 280 | if not text.strip(): |
| 281 | raise parse_error("empty", 0, text) |
| 282 | p = _Parser(text, check_step) |
| 283 | node = p.seq() |
| 284 | p.ws() |
| 285 | if p.i < len(text): |
| 286 | raise p.error("stray_bar" if text[p.i] == "|" else |
| 287 | "stray_close" if text[p.i] == ")" else "unexpected") |
| 288 | return node |
| 289 | |
| 290 | |
| 291 | # --- writing ----------------------------------------------------------------- |
| 292 | |
| 293 | def show(node, lean_step=None): |
| 294 | """The expression as text: the lab's notation, or Lean 4 when |
| 295 | lean_step translates a basic tactic. Compound parts get brackets, |
| 296 | so the text reads back as the same tree.""" |
| 297 | def part(p): |
| 298 | s = show(p, lean_step) |
| 299 | return s if p.kind in SIMPLE else f"({s})" |
| 300 | k = node.kind |
| 301 | if k == "step": |
| 302 | return lean_step(node.text) if lean_step else node.text |
| 303 | if k == "call": |
| 304 | return node.text |
| 305 | if k == "hole": |
| 306 | return HOLE |
| 307 | if k in ("skip", "done"): |
| 308 | return k |
| 309 | if k == "fail": |
| 310 | return f'fail "{node.text}"' if node.text else "fail" |
| 311 | if k == "seq": |
| 312 | return "; ".join(part(p) for p in node.parts) |
| 313 | if k == "then": |
| 314 | a, b = node.parts |
| 315 | left = show(a, lean_step) if a.kind == "then" else part(a) |
| 316 | return f"{left} <;> {part(b)}" |
| 317 | if k == "first": |
| 318 | return "first " + " ".join("| " + part(p) for p in node.parts) |
| 319 | if k == "iterate": |
| 320 | return f"iterate {node.count} {part(node.parts[0])}" |
| 321 | return f"{k} {part(node.parts[0])}" |
| 322 | |
| 323 | |
| 324 | def lean_macro(name, node, lean_step): |
| 325 | """A tactic of the user as a Lean 4 macro. Hygiene is off, so the |
| 326 | names in it (H5, x, α) mean what they mean where it is used.""" |
| 327 | return ("set_option hygiene false in\n" |
| 328 | f'macro "{name}" : tactic => `(tactic| ({show(node, lean_step)}))') |
| 329 | |
| 330 | |
| 331 | def walk(node): |
| 332 | """The node and all its parts, in prefix order.""" |
| 333 | stack = [node] |
| 334 | while stack: |
| 335 | n = stack.pop() |
| 336 | yield n |
| 337 | stack.extend(reversed(n.parts)) |
| 338 | |
| 339 | |
| 340 | def calls(node): |
| 341 | """The names of the user tactics that the expression calls.""" |
| 342 | return [n.text for n in walk(node) if n.kind == "call"] |
| 343 | |
| 344 | |
| 345 | def paths(node, path="0", result=None): |
| 346 | """id(part) -> its path ("0", "0.1", "0.1.0", …): the address of a |
| 347 | part in the expression (the page draws and edits by it).""" |
| 348 | result = {} if result is None else result |
| 349 | stack = [(node, path)] |
| 350 | while stack: |
| 351 | n, p = stack.pop() |
| 352 | result[id(n)] = p |
| 353 | stack.extend((c, f"{p}.{i}") for i, c in enumerate(n.parts)) |
| 354 | return result |
| 355 | |
| 356 | |
| 357 | def tree_json(node, path="0"): |
| 358 | """The structure for the page: kind, text, span, count, path, |
| 359 | parts.""" |
| 360 | return {"kind": node.kind, "text": show(node), "span": list(node.span), |
| 361 | "count": node.count, "path": path, |
| 362 | "parts": [tree_json(p, f"{path}.{i}") |
| 363 | for i, p in enumerate(node.parts)]} |
| 364 | |
| 365 | |
| 366 | # --- running ----------------------------------------------------------------- |
| 367 | |
| 368 | @dataclass(frozen=True) |
| 369 | class State: |
| 370 | """Goals ((id, equation), ...) -- the first is the main goal -- and |
| 371 | the justifications so far: a linked list (link, earlier links) of |
| 372 | links (goal id, ids of its new goals, compose, step text). A failed |
| 373 | branch simply drops its state: the state is never changed.""" |
| 374 | goals: tuple |
| 375 | links: tuple = () |
| 376 | next_id: int = 1 |
| 377 | |
| 378 | |
| 379 | def justifications(state): |
| 380 | """The links of a state, the oldest first.""" |
| 381 | result, links = [], state.links |
| 382 | while links: |
| 383 | result.append(links[0]) |
| 384 | links = links[1] |
| 385 | return result[::-1] |
| 386 | |
| 387 | |
| 388 | def goals_key(state): |
| 389 | return tuple(eq for _, eq in state.goals) |
| 390 | |
| 391 | |
| 392 | class LimitError(TacticError): |
| 393 | """A limit of the runner -- steps, time, size, a loop of repeat. It |
| 394 | stops the whole tactic: first, try and repeat do not catch it (in |
| 395 | Lean such a tactic would run until the time runs out).""" |
| 396 | |
| 397 | |
| 398 | class Trace: |
| 399 | """What one part of the expression did: ok or the error, the goals |
| 400 | before and after it (their number and the first one), the traces of |
| 401 | its parts, the turn (of repeat or iterate) and, for repeat, the |
| 402 | number of turns.""" |
| 403 | __slots__ = ("node", "ok", "error", "before", "after", "parts", "turn", |
| 404 | "turns", "info") |
| 405 | |
| 406 | def __init__(self, node, before, turn): |
| 407 | self.node, self.before, self.turn = node, before, turn |
| 408 | self.ok, self.error, self.after, self.parts = None, None, None, [] |
| 409 | self.turns = self.info = None |
| 410 | |
| 411 | |
| 412 | def snapshot(state): |
| 413 | return (len(state.goals), state.goals[0][1] if state.goals else None) |
| 414 | |
| 415 | |
| 416 | class Runner: |
| 417 | """Runs an expression on a State. step(goal, text) does one basic |
| 418 | tactic on one goal and returns (new goals, compose) or raises |
| 419 | TacticError; tactics: name -> Node; size(goal): its symbols.""" |
| 420 | |
| 421 | def __init__(self, step, tactics=None, size=None, depth=None, |
| 422 | max_steps=MAX_STEPS, seconds=SECONDS, max_size=MAX_SIZE, |
| 423 | max_trace=MAX_TRACE, max_nodes=MAX_NODES): |
| 424 | self.step, self.tactics, self.size = step, tactics or {}, size |
| 425 | self.depth = depth |
| 426 | self.max_steps, self.max_size = max_steps, max_size |
| 427 | self.max_trace, self.max_nodes = max_trace, max_nodes |
| 428 | self.seconds = seconds |
| 429 | self.deadline = time.perf_counter() + seconds |
| 430 | self.steps = self.nodes = self.recorded = 0 |
| 431 | self.truncated = False |
| 432 | |
| 433 | def run(self, node, state): |
| 434 | """-> (end state, trace). On failure the TacticError carries the |
| 435 | trace in its attribute `trace`.""" |
| 436 | root = [] |
| 437 | try: |
| 438 | end = self._run(node, state, root, 0, 0) |
| 439 | except TacticError as e: |
| 440 | e.trace = root[0] if root else None |
| 441 | raise |
| 442 | return end, root[0] |
| 443 | |
| 444 | def _tick(self): |
| 445 | self.nodes += 1 |
| 446 | if self.nodes > self.max_nodes: |
| 447 | raise LimitError(("tc_nodes", self.max_nodes)) |
| 448 | if time.perf_counter() > self.deadline: |
| 449 | raise LimitError(("tc_time", self.seconds)) |
| 450 | |
| 451 | def _trace(self, node, state, out, turn): |
| 452 | if out is None: |
| 453 | return None |
| 454 | if self.recorded >= self.max_trace: |
| 455 | self.truncated = True |
| 456 | return None |
| 457 | self.recorded += 1 |
| 458 | t = Trace(node, snapshot(state), turn) |
| 459 | out.append(t) |
| 460 | return t |
| 461 | |
| 462 | def _run(self, node, state, out, depth, turn): |
| 463 | if depth > MAX_DEPTH: |
| 464 | raise LimitError(("tc_depth", MAX_DEPTH)) |
| 465 | self._tick() |
| 466 | t = self._trace(node, state, out, turn) |
| 467 | kids = t.parts if t is not None else None |
| 468 | try: |
| 469 | end = getattr(self, "_" + node.kind)(node, state, kids, depth, |
| 470 | t) |
| 471 | except TacticError as e: |
| 472 | if t is not None: |
| 473 | t.ok, t.error = False, e |
| 474 | raise |
| 475 | if t is not None: |
| 476 | t.ok, t.after = True, snapshot(end) |
| 477 | return end |
| 478 | |
| 479 | def _step(self, node, state, kids, depth, t): |
| 480 | if not state.goals: |
| 481 | raise TacticError(("tc_no_goals",)) |
| 482 | self.steps += 1 |
| 483 | if self.steps > self.max_steps: |
| 484 | raise LimitError(("tc_steps", self.max_steps)) |
| 485 | gid, goal = state.goals[0] |
| 486 | try: |
| 487 | result = self.step(goal, node.text) |
| 488 | except RecursionError: |
| 489 | raise LimitError(("tc_deep", MAX_TERM_DEPTH)) from None |
| 490 | new, compose = result[0], result[1] |
| 491 | if t is not None and len(result) > 2: |
| 492 | t.info = result[2] # what the kernel gets |
| 493 | for g in new: |
| 494 | if self.size is not None and self.size(g) > self.max_size: |
| 495 | raise LimitError(("tc_size", self.size(g), self.max_size)) |
| 496 | if self.depth is not None and self.depth(g) > MAX_TERM_DEPTH: |
| 497 | raise LimitError(("tc_deep", MAX_TERM_DEPTH)) |
| 498 | ids = tuple(range(state.next_id, state.next_id + len(new))) |
| 499 | return State(tuple(zip(ids, new)) + state.goals[1:], |
| 500 | ((gid, ids, compose, node.text), state.links), |
| 501 | state.next_id + len(new)) |
| 502 | |
| 503 | def _call(self, node, state, kids, depth, t): |
| 504 | body = self.tactics.get(node.text) |
| 505 | if body is None: |
| 506 | raise TacticError(("tc_unknown", node.text)) |
| 507 | return self._run(body, state, kids, depth + 1, 0) |
| 508 | |
| 509 | def _skip(self, node, state, kids, depth, t): |
| 510 | return state |
| 511 | |
| 512 | def _done(self, node, state, kids, depth, t): |
| 513 | if state.goals: |
| 514 | raise TacticError(("tc_done", len(state.goals))) |
| 515 | return state |
| 516 | |
| 517 | def _fail(self, node, state, kids, depth, t): |
| 518 | raise TacticError(("tc_fail", node.text)) |
| 519 | |
| 520 | def _hole(self, node, state, kids, depth, t): |
| 521 | raise TacticError(("tc_hole",)) |
| 522 | |
| 523 | def _seq(self, node, state, kids, depth, t): |
| 524 | for p in node.parts: |
| 525 | state = self._run(p, state, kids, depth + 1, 0) |
| 526 | return state |
| 527 | |
| 528 | def _then(self, node, state, kids, depth, t): |
| 529 | """t1 <;> t2 as in Lean: focus on the main goal, t1, then t2 on |
| 530 | every goal that t1 left.""" |
| 531 | if not state.goals: |
| 532 | raise TacticError(("tc_no_goals",)) |
| 533 | a, b = node.parts |
| 534 | focus = State(state.goals[:1], state.links, state.next_id) |
| 535 | middle = self._run(a, focus, kids, depth + 1, 0) |
| 536 | end = self._each(b, middle, kids, depth, True) |
| 537 | return State(end.goals + state.goals[1:], end.links, end.next_id) |
| 538 | |
| 539 | def _each(self, body, state, kids, depth, need_all): |
| 540 | """body on every goal, each on its own (Lean: focus).""" |
| 541 | goals, links, next_id, succeeded = [], state.links, state.next_id, 0 |
| 542 | for g in state.goals: |
| 543 | try: |
| 544 | r = self._run(body, State((g,), links, next_id), kids, |
| 545 | depth + 1, 0) |
| 546 | except LimitError: |
| 547 | raise |
| 548 | except TacticError: |
| 549 | if need_all: |
| 550 | raise |
| 551 | goals.append(g) |
| 552 | continue |
| 553 | goals.extend(r.goals) |
| 554 | links, next_id = r.links, r.next_id |
| 555 | succeeded += 1 |
| 556 | if not need_all and not succeeded: |
| 557 | raise TacticError(("tc_any_goals", len(state.goals))) |
| 558 | return State(tuple(goals), links, next_id) |
| 559 | |
| 560 | def _all_goals(self, node, state, kids, depth, t): |
| 561 | return self._each(node.parts[0], state, kids, depth, True) |
| 562 | |
| 563 | def _any_goals(self, node, state, kids, depth, t): |
| 564 | return self._each(node.parts[0], state, kids, depth, False) |
| 565 | |
| 566 | def _first(self, node, state, kids, depth, t): |
| 567 | for p in node.parts: |
| 568 | try: |
| 569 | return self._run(p, state, kids, depth + 1, 0) |
| 570 | except LimitError: |
| 571 | raise |
| 572 | except TacticError: |
| 573 | continue |
| 574 | raise TacticError(("tc_first", len(node.parts))) |
| 575 | |
| 576 | def _try(self, node, state, kids, depth, t): |
| 577 | try: |
| 578 | return self._run(node.parts[0], state, kids, depth + 1, 0) |
| 579 | except LimitError: |
| 580 | raise |
| 581 | except TacticError: |
| 582 | return state |
| 583 | |
| 584 | def _iterate(self, node, state, kids, depth, t): |
| 585 | for k in range(1, node.count + 1): |
| 586 | state = self._run(node.parts[0], state, kids, depth + 1, k) |
| 587 | return state |
| 588 | |
| 589 | def _repeat(self, node, state, kids, depth, t): |
| 590 | """The body while it succeeds. A turn after which the goals are |
| 591 | the same as after an earlier one would repeat for ever: that is |
| 592 | a LimitError (Lean would run until it hits its limits).""" |
| 593 | seen = {goals_key(state): 0} |
| 594 | turn = 0 |
| 595 | while True: |
| 596 | try: |
| 597 | after = self._run(node.parts[0], state, kids, depth + 1, |
| 598 | turn + 1) |
| 599 | except LimitError: |
| 600 | raise |
| 601 | except TacticError: |
| 602 | break |
| 603 | turn += 1 |
| 604 | if t is not None: |
| 605 | t.turns = turn |
| 606 | key = goals_key(after) |
| 607 | if key in seen: |
| 608 | first = after.goals[0][1] if after.goals else None |
| 609 | raise LimitError(("tc_loop", turn, seen[key], first)) |
| 610 | seen[key] = turn |
| 611 | state = after |
| 612 | if t is not None: |
| 613 | t.turns = turn |
| 614 | return state |
| 615 | |
| 616 | |
| 617 | # --- a good tactic: analysis ------------------------------------------------- |
| 618 | # |
| 619 | # The measure is the sum of the sizes of all goals (an equation l = r |
| 620 | # counts size(l) + size(r) + 1). A successful run of a part of a tactic |
| 621 | # can make it smaller ("shrinks"), keep it or make it smaller ("same"), |
| 622 | # perhaps make it larger ("grows") -- or never succeed ("never"). |
| 623 | |
| 624 | SHRINKS, SAME, GROWS, NEVER = "shrinks", "same", "grows", "never" |
| 625 | _ORDER = (SHRINKS, SAME, GROWS) |
| 626 | |
| 627 | |
| 628 | def _occurrences(t, v): |
| 629 | if isinstance(t, str): |
| 630 | return 1 if t == v else 0 |
| 631 | return sum(_occurrences(a, v) for a in t[1:]) |
| 632 | |
| 633 | |
| 634 | def _metavariables(t, result): |
| 635 | if isinstance(t, str): |
| 636 | if t.startswith("?"): |
| 637 | result.add(t) |
| 638 | else: |
| 639 | for a in t[1:]: |
| 640 | _metavariables(a, result) |
| 641 | return result |
| 642 | |
| 643 | |
| 644 | def metavariables(t): |
| 645 | """The metavariables (?x) of a pattern.""" |
| 646 | return _metavariables(t, set()) |
| 647 | |
| 648 | |
| 649 | def rule_effect(l, r, size): |
| 650 | """What rewriting l -> r does to the size of a term, for EVERY |
| 651 | instance: shrinks when l is larger than r and no metavariable (?x) |
| 652 | occurs more often in r than in l -- then size(σl) - size(σr) = |
| 653 | size(l) - size(r) + Σ (occ_l(x) - occ_r(x)) (size(σx) - 1) > 0.""" |
| 654 | ms = _metavariables(l, set()) | _metavariables(r, set()) |
| 655 | if any(_occurrences(r, v) > _occurrences(l, v) for v in ms): |
| 656 | return GROWS |
| 657 | a, b = size(l), size(r) |
| 658 | return SHRINKS if a > b else SAME if a == b else GROWS |
| 659 | |
| 660 | |
| 661 | def in_sequence(effects): |
| 662 | """The effect of parts that all run, one after another.""" |
| 663 | effects = list(effects) |
| 664 | if NEVER in effects: |
| 665 | return NEVER |
| 666 | if GROWS in effects: |
| 667 | return GROWS |
| 668 | return SHRINKS if SHRINKS in effects else SAME |
| 669 | |
| 670 | |
| 671 | def worst(effects): |
| 672 | """The effect of one of several parts (we do not know which).""" |
| 673 | effects = [e for e in effects if e != NEVER] |
| 674 | if not effects: |
| 675 | return NEVER |
| 676 | return max(effects, key=_ORDER.index) |
| 677 | |
| 678 | |
| 679 | class Analysis: |
| 680 | """effect(node) -> (effect, can_fail): can_fail is False when the |
| 681 | part succeeds on every goal list with a goal (skip, try, repeat, |
| 682 | symm). step_info(text) -> (effect, can_fail, rules) for a basic |
| 683 | tactic, rules: [(rule text, effect, l, r)]; it raises TacticError |
| 684 | for a step that cannot run here (an unknown fact).""" |
| 685 | |
| 686 | def __init__(self, step_info, tactics): |
| 687 | self.step_info, self.tactics = step_info, tactics |
| 688 | self.findings, self.memo = [], {} |
| 689 | |
| 690 | def note(self, level, key, node, *data): |
| 691 | self.findings.append((level, key, node.span, data)) |
| 692 | |
| 693 | def effect(self, node): |
| 694 | """(effect, can it fail while a goal is left, can it fail with no |
| 695 | goal at all). A basic step always fails without a goal; skip, |
| 696 | try and repeat never fail.""" |
| 697 | k = node.kind |
| 698 | if k == "step": |
| 699 | try: |
| 700 | e, can_fail, _ = self.step_info(node.text) |
| 701 | except TacticError: |
| 702 | return GROWS, True, True |
| 703 | return e, can_fail, True |
| 704 | if k == "call": |
| 705 | if node.text not in self.memo: |
| 706 | self.memo[node.text] = (GROWS, True, True) # computing |
| 707 | body = self.tactics.get(node.text) |
| 708 | self.memo[node.text] = self.effect(body) if body \ |
| 709 | else (GROWS, True, True) |
| 710 | return self.memo[node.text] |
| 711 | if k == "skip": |
| 712 | return SAME, False, False |
| 713 | if k == "done": |
| 714 | return SAME, True, False |
| 715 | if k == "fail": |
| 716 | return NEVER, True, True |
| 717 | if k == "hole": |
| 718 | return GROWS, True, True |
| 719 | parts = [self.effect(p) for p in node.parts] |
| 720 | if k == "seq": |
| 721 | return (in_sequence(e for e, _, _ in parts), |
| 722 | any(f for _, f, _ in parts), any(g for _, _, g in parts)) |
| 723 | if k == "then": # <;> needs a goal |
| 724 | return (in_sequence(e for e, _, _ in parts), |
| 725 | any(f for _, f, _ in parts), True) |
| 726 | if k == "first": |
| 727 | return (worst(e for e, _, _ in parts), |
| 728 | all(f for _, f, _ in parts), all(g for _, _, g in parts)) |
| 729 | e, can_fail, empty = parts[0] |
| 730 | if k in ("try", "repeat"): |
| 731 | return worst([SAME, e]), False, False |
| 732 | if k == "all_goals": |
| 733 | return worst([SAME, e]), can_fail, False |
| 734 | if k == "any_goals": |
| 735 | return e, True, True |
| 736 | return e, can_fail, empty # iterate |
| 737 | |
| 738 | def rules(self, node): |
| 739 | """The rewrite rules inside a part: (text, effect, l, r).""" |
| 740 | result, seen = [], set() |
| 741 | for n in walk(node): |
| 742 | if n.kind == "call" and n.text not in seen: |
| 743 | seen.add(n.text) |
| 744 | body = self.tactics.get(n.text) |
| 745 | if body is not None: |
| 746 | result += self.rules(body) |
| 747 | if n.kind == "step": |
| 748 | try: |
| 749 | result += self.step_info(n.text)[2] |
| 750 | except TacticError: |
| 751 | pass |
| 752 | return result |
| 753 | |
| 754 | def check(self, node): |
| 755 | for n in walk(node): |
| 756 | k = n.kind |
| 757 | if k == "step": |
| 758 | try: |
| 759 | self.step_info(n.text) |
| 760 | except TacticError as e: |
| 761 | self.note("error", "step", n, n.text, e) |
| 762 | elif k == "call" and n.text not in self.tactics: |
| 763 | self.note("error", "unknown", n, n.text) |
| 764 | elif k == "hole": |
| 765 | self.note("info", "hole", n) |
| 766 | elif k == "repeat": |
| 767 | self.check_repeat(n) |
| 768 | elif k == "first": |
| 769 | self.check_first(n) |
| 770 | elif k == "try" and not self.effect(n.parts[0])[2]: |
| 771 | self.note("info", "try_useless", n, show(n.parts[0])) |
| 772 | if n.greedy: |
| 773 | self.note("warning", "greedy", n, k, show(n), |
| 774 | show(n.parts[0].parts[0])) |
| 775 | elif k == "then" and n.parts[0].kind == "step" and \ |
| 776 | n.parts[0].text.split()[0] in ("rw", "nth_rw", "rfl", |
| 777 | "exact", "symm", "ac_rfl"): |
| 778 | self.note("info", "then_one", n, show(n.parts[0])) |
| 779 | return self.findings |
| 780 | |
| 781 | def check_repeat(self, n): |
| 782 | body = n.parts[0] |
| 783 | e, can_fail, can_fail_empty = self.effect(body) |
| 784 | rules = self.rules(body) |
| 785 | if not can_fail_empty: |
| 786 | self.note("error", "repeat_never_fails", n, show(body)) |
| 787 | elif not can_fail: |
| 788 | self.note("warning", "repeat_fails_only_empty", n, show(body)) |
| 789 | elif e == NEVER: |
| 790 | self.note("warning", "repeat_never_succeeds", n, show(body)) |
| 791 | elif e == SHRINKS: |
| 792 | self.note("ok", "repeat_stops", n, rules) |
| 793 | elif e == SAME: |
| 794 | self.note("warning", "repeat_may_loop", n, |
| 795 | [r for r in rules if r[1] == SAME]) |
| 796 | else: |
| 797 | self.note("warning", "repeat_may_grow", n, |
| 798 | [r for r in rules if r[1] == GROWS]) |
| 799 | |
| 800 | def check_first(self, n): |
| 801 | if len(n.parts) == 1: |
| 802 | self.note("info", "first_one", n) |
| 803 | for i, p in enumerate(n.parts[:-1]): |
| 804 | if not self.effect(p)[1]: |
| 805 | self.note("warning", "first_unreachable", n, show(p), |
| 806 | [show(q) for q in n.parts[i + 1:]]) |
| 807 | break |
| 808 | |
| 809 | |
| 810 | def analyse(node, step_info, tactics): |
| 811 | """Findings about a tactic: [(level, key, span, data)], level: ok, |
| 812 | info, warning or error.""" |
| 813 | return Analysis(step_info, tactics).check(node) |