Course page › Code of Lecture 3 › syntax.py · 151 lines
the Polish versionraw file

Notation for terms and proofs: reading strings and printing (lecture 3).

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

1"""Notation for terms and proofs: reading strings and printing (lecture 3).
2
3This is not a part of the kernel, but what the kernel checks depends on
4this module: if the parser misreads a theorem, the kernel checks a different
5statement from the one we had in mind.
6
7Grammar (Boolean algebra in Huntington's notation, the complement as n(x),
8as in the papers on the Robbins problem):
9 sum := product ('+' product)* x + y + z = (x + y) + z
10 product := atom ('*' atom)*
11 atom := variable | 0 | 1 | n(sum) | (sum)
12"""
13
14import re
15
16from kernel import Refl, Symm, Trans, CongrArg, Inst
17
18_TOKEN = re.compile(r"\s*(?:(\d+)|([A-Za-z_][A-Za-z0-9_]*)|(.))")
19
20
21def _tokens(text):
22 result = []
23 for m in _TOKEN.finditer(text):
24 if m.group(0).strip():
25 result.append(m.group(1) or m.group(2) or m.group(3))
26 return result
27
28
29def term(text):
30 """'x + n(x)' -> ('+', 'x', ('n', 'x'))"""
31 toks = _tokens(text)
32 pos = 0
33
34 def peek():
35 return toks[pos] if pos < len(toks) else None
36
37 def take(expected=None):
38 nonlocal pos
39 z = peek()
40 if z is None or (expected and z != expected):
41 raise SyntaxError(f"in {text!r}: expected "
42 f"{expected or 'an expression'}, got {z!r}")
43 pos += 1
44 return z
45
46 def sum_term():
47 t = product_term()
48 while peek() == "+":
49 take()
50 t = ("+", t, product_term())
51 return t
52
53 def product_term():
54 t = atom()
55 while peek() == "*":
56 take()
57 t = ("*", t, atom())
58 return t
59
60 def atom():
61 z = take()
62 if z == "(":
63 t = sum_term()
64 take(")")
65 return t
66 if z == "n" and peek() == "(":
67 take("(")
68 t = sum_term()
69 take(")")
70 return ("n", t)
71 if z in ("0", "1") or (z.isidentifier() and z != "n"):
72 return z
73 raise SyntaxError(f"in {text!r}: unexpected character {z!r}")
74
75 t = sum_term()
76 if peek() is not None:
77 raise SyntaxError(f"in {text!r}: unexpected {peek()!r} at the end")
78 return t
79
80
81def equation(text):
82 """'x + x = x' -> (('+', 'x', 'x'), 'x')"""
83 left, right = text.split("=")
84 return term(left), term(right)
85
86
87def show(t, prec=0):
88 """Printing with the fewest parentheses (prec: 0, 1 or 2)."""
89 if isinstance(t, str):
90 return t
91 f = t[0]
92 if f == "n":
93 return f"n({show(t[1])})"
94 if f == "+":
95 s = f"{show(t[1], 0)} + {show(t[2], 1)}"
96 return f"({s})" if prec >= 1 else s
97 if f == "*":
98 s = f"{show(t[1], 1)} * {show(t[2], 2)}"
99 return f"({s})" if prec >= 2 else s
100 return f"{f}({', '.join(show(a) for a in t[1:])})"
101
102
103def show_equation(r):
104 return f"{show(r[0])} = {show(r[1])}"
105
106
107def show_lean(t, prec=0):
108 """A term in Lean notation: the complement is a function, so n x."""
109 if isinstance(t, str):
110 return t
111 f = t[0]
112 if f == "n":
113 s = f"n {show_lean(t[1], 3)}"
114 return f"({s})" if prec >= 3 else s
115 if f == "+":
116 s = f"{show_lean(t[1], 0)} + {show_lean(t[2], 1)}"
117 return f"({s})" if prec >= 1 else s
118 if f == "*":
119 s = f"{show_lean(t[1], 1)} * {show_lean(t[2], 2)}"
120 return f"({s})" if prec >= 2 else s
121 raise ValueError(t)
122
123
124def lean(d):
125 """A proof in Lean notation (Eq.refl, Eq.symm, Eq.trans, congrArg)."""
126 def arg(t):
127 return show_lean(t, 3)
128 match d:
129 case Refl(t):
130 return f"Eq.refl {arg(t)}"
131 case Symm(p):
132 return f"Eq.symm ({lean(p)})"
133 case Trans(p, q):
134 return f"Eq.trans ({lean(p)}) ({lean(q)})"
135 case CongrArg(z, C, p):
136 return f"congrArg (fun {z} => {show_lean(C)}) ({lean(p)})"
137 case Inst(name, args):
138 return " ".join([name] + [arg(a) for a in args])
139 raise ValueError(d)
140
141
142def size(d):
143 """The number of nodes of a proof tree (applications of rules)."""
144 match d:
145 case Refl(_) | Inst(_, _):
146 return 1
147 case Symm(p) | CongrArg(_, _, p):
148 return 1 + size(p)
149 case Trans(p, q):
150 return 1 + size(p) + size(q)
151 raise ValueError(d)