thousandproblems 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- thousandproblems/__init__.py +161 -0
- thousandproblems/_cparser.pyi +6 -0
- thousandproblems/_pyparser.py +860 -0
- thousandproblems/library.py +463 -0
- thousandproblems/nodes.py +678 -0
- thousandproblems/py.typed +0 -0
- thousandproblems-0.1.0.dist-info/METADATA +848 -0
- thousandproblems-0.1.0.dist-info/RECORD +11 -0
- thousandproblems-0.1.0.dist-info/WHEEL +5 -0
- thousandproblems-0.1.0.dist-info/licenses/LICENSE +674 -0
- thousandproblems-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
"""Pure-Python lexer and recursive-descent parser. Always available; the C extension
|
|
2
|
+
``_cparser`` is a faster port of exactly this module."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from typing import NamedTuple, Optional, Union
|
|
8
|
+
|
|
9
|
+
from .nodes import * # noqa: F403
|
|
10
|
+
from .nodes import _NONASSOC, _TH1_TERMS, _deep_stack, _error_at
|
|
11
|
+
|
|
12
|
+
# ---------------------------------------------------------------------------------
|
|
13
|
+
# Lexer
|
|
14
|
+
# ---------------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
_OPERATORS = [
|
|
17
|
+
"<=>", "<~>", "-->", "@@+", "@@-", "<.>", "[.]", "{.}", "(.)",
|
|
18
|
+
"=>", "<=", "<<", "~|", "~&", "!=", "!!", "!>", "??", "?*", "@+", "@-", "@=", ":=", "==",
|
|
19
|
+
"(", ")", "[", "]", "{", "}", ",", ".", ":", "|", "&", "~", "!", "?", "=", "@", ">",
|
|
20
|
+
"*", "+", "-", "#", "^",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_TOKEN_RE = re.compile(
|
|
24
|
+
r"""
|
|
25
|
+
(?P<ws>[ \t\r\n]+)
|
|
26
|
+
| (?P<line_comment>%[^\r\n]*)
|
|
27
|
+
| (?P<block_comment>/\*.*?\*/)
|
|
28
|
+
| (?P<sq>'(?:[ -&(-\[\]-~]|\\\\|\\')+')
|
|
29
|
+
| (?P<bq>`[A-Z][A-Za-z0-9_]*)
|
|
30
|
+
| (?P<distinct>"(?:[ !#-\[\]-~]|\\\\|\\")+")
|
|
31
|
+
| (?P<real>[+-]?(?:(?:0|[1-9][0-9]*)\.[0-9]+(?:[Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+))
|
|
32
|
+
| (?P<rational>[+-]?(?:0|[1-9][0-9]*)/[1-9][0-9]*)
|
|
33
|
+
| (?P<integer>[+-]?(?:0|[1-9][0-9]*))
|
|
34
|
+
| (?P<system>\$\$[A-Za-z0-9_]*)
|
|
35
|
+
| (?P<defined>\$[A-Za-z0-9_]*)
|
|
36
|
+
| (?P<upper>[A-Z][A-Za-z0-9_]*)
|
|
37
|
+
| (?P<lower>[a-z][A-Za-z0-9_]*)
|
|
38
|
+
| (?P<op>"""
|
|
39
|
+
+ "|".join(re.escape(op) for op in _OPERATORS)
|
|
40
|
+
+ r"""
|
|
41
|
+
)
|
|
42
|
+
""",
|
|
43
|
+
re.VERBOSE | re.DOTALL,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_LOWER_WORD_RE = re.compile(r"[a-z][A-Za-z0-9_]*")
|
|
47
|
+
_NUMBER_KINDS = frozenset({"integer", "rational", "real"})
|
|
48
|
+
_WORD_KINDS = frozenset({"lower", "sq", "bq"})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _Token(NamedTuple):
|
|
52
|
+
kind: str
|
|
53
|
+
text: str
|
|
54
|
+
line: int
|
|
55
|
+
column: int
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _tokenize(text: str, filename: Optional[str]) -> tuple[list[_Token], list[Comment]]:
|
|
59
|
+
tokens: list[_Token] = []
|
|
60
|
+
comments: list[Comment] = []
|
|
61
|
+
match = _TOKEN_RE.match
|
|
62
|
+
pos, line, line_start = 0, 1, 0
|
|
63
|
+
size = len(text)
|
|
64
|
+
while pos < size:
|
|
65
|
+
found = match(text, pos)
|
|
66
|
+
if found is None:
|
|
67
|
+
char = text[pos]
|
|
68
|
+
if char == "'":
|
|
69
|
+
problem = "unterminated or invalid single-quoted word"
|
|
70
|
+
elif char == '"':
|
|
71
|
+
problem = "unterminated or invalid distinct object"
|
|
72
|
+
elif text.startswith("/*", pos):
|
|
73
|
+
problem = "unterminated block comment"
|
|
74
|
+
else:
|
|
75
|
+
problem = f"unexpected character {char!r}"
|
|
76
|
+
raise _error_at(problem, text, line, pos - line_start + 1, filename)
|
|
77
|
+
kind = found.lastgroup
|
|
78
|
+
value = found.group()
|
|
79
|
+
if kind == "ws" or kind == "block_comment":
|
|
80
|
+
if kind == "block_comment":
|
|
81
|
+
comments.append(Comment(value, line))
|
|
82
|
+
newlines = value.count("\n")
|
|
83
|
+
if newlines:
|
|
84
|
+
line += newlines
|
|
85
|
+
line_start = pos + value.rindex("\n") + 1
|
|
86
|
+
elif kind == "line_comment":
|
|
87
|
+
comments.append(Comment(value, line))
|
|
88
|
+
else:
|
|
89
|
+
tokens.append(_Token(kind, value, line, pos - line_start + 1)) # type: ignore[arg-type]
|
|
90
|
+
pos = found.end()
|
|
91
|
+
tokens.append(_Token("eof", "", line, pos - line_start + 1))
|
|
92
|
+
return tokens, comments
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------------------------
|
|
97
|
+
# Parser
|
|
98
|
+
# ---------------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
_SHORT_CONNECTIVES = frozenset({"[.]", "<.>", "{.}", "(.)"})
|
|
101
|
+
_TYPE_QUANTIFIERS = frozenset({"!>", "?*"})
|
|
102
|
+
_QUANTIFIERS = {
|
|
103
|
+
"fof": frozenset({"!", "?"}),
|
|
104
|
+
"tff": frozenset({"!", "?", "#"}),
|
|
105
|
+
"thf": frozenset({"!", "?", "#", "^", "@+", "@-"}) | _TYPE_QUANTIFIERS,
|
|
106
|
+
}
|
|
107
|
+
_UNARY = {
|
|
108
|
+
"fof": frozenset({"~"}),
|
|
109
|
+
"tff": frozenset({"~"}) | _SHORT_CONNECTIVES,
|
|
110
|
+
"thf": frozenset({"~"}) | _SHORT_CONNECTIVES,
|
|
111
|
+
}
|
|
112
|
+
_CHAINS = {
|
|
113
|
+
"fof": frozenset({"|", "&"}),
|
|
114
|
+
"tff": frozenset({"|", "&"}),
|
|
115
|
+
"thf": frozenset({"|", "&", "@"}),
|
|
116
|
+
}
|
|
117
|
+
_THF_CONNECTIVE_TERMS = (_NONASSOC | _SHORT_CONNECTIVES
|
|
118
|
+
| frozenset({"|", "&", "=", "!=", "~"}))
|
|
119
|
+
_THF_DEFINITION_LHS = (Function, Tuple, ConnectiveTerm, LongConnective, Let, Number, DistinctObject)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _Parser:
|
|
123
|
+
def __init__(self, text: str, filename: Optional[str] = None):
|
|
124
|
+
self.text = text
|
|
125
|
+
self.filename = filename
|
|
126
|
+
self.tokens, self.comments = _tokenize(text, filename)
|
|
127
|
+
self.i = 0
|
|
128
|
+
|
|
129
|
+
# --- token helpers ------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def tok(self) -> _Token:
|
|
133
|
+
return self.tokens[self.i]
|
|
134
|
+
|
|
135
|
+
def peek(self, offset: int = 1) -> _Token:
|
|
136
|
+
return self.tokens[min(self.i + offset, len(self.tokens) - 1)]
|
|
137
|
+
|
|
138
|
+
def advance(self) -> _Token:
|
|
139
|
+
tok = self.tokens[self.i]
|
|
140
|
+
if tok.kind != "eof":
|
|
141
|
+
self.i += 1
|
|
142
|
+
return tok
|
|
143
|
+
|
|
144
|
+
def at(self, text: str) -> bool:
|
|
145
|
+
return self.tokens[self.i].text == text
|
|
146
|
+
|
|
147
|
+
def accept(self, text: str) -> bool:
|
|
148
|
+
if self.tokens[self.i].text == text:
|
|
149
|
+
self.i += 1
|
|
150
|
+
return True
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
def expect(self, text: str) -> _Token:
|
|
154
|
+
if self.tokens[self.i].text != text:
|
|
155
|
+
raise self.error(f"expected {text!r}, found {self.describe()}")
|
|
156
|
+
return self.advance()
|
|
157
|
+
|
|
158
|
+
def describe(self, tok: Optional[_Token] = None) -> str:
|
|
159
|
+
tok = tok or self.tok
|
|
160
|
+
return "end of input" if tok.kind == "eof" else repr(tok.text)
|
|
161
|
+
|
|
162
|
+
def error(self, message: str, tok: Optional[_Token] = None) -> ParseError:
|
|
163
|
+
tok = tok or self.tok
|
|
164
|
+
return _error_at(message, self.text, tok.line, tok.column, self.filename)
|
|
165
|
+
|
|
166
|
+
# --- files --------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
def parse_file(self) -> TPTPFile:
|
|
169
|
+
inputs: list[Union[AnnotatedFormula, Include]] = []
|
|
170
|
+
while self.tok.kind != "eof":
|
|
171
|
+
tok = self.tok
|
|
172
|
+
if tok.text == "include" and self.peek().text == "(":
|
|
173
|
+
inputs.append(self.include())
|
|
174
|
+
elif tok.text in _FORMULA_RULES and self.peek().text == "(":
|
|
175
|
+
inputs.append(self.annotated_formula())
|
|
176
|
+
else:
|
|
177
|
+
raise self.error(f"expected an annotated formula or include, found {self.describe()}")
|
|
178
|
+
return TPTPFile(tuple(inputs), tuple(self.comments), self.filename)
|
|
179
|
+
|
|
180
|
+
def annotated_formula(self) -> AnnotatedFormula:
|
|
181
|
+
start = self.advance()
|
|
182
|
+
language = start.text
|
|
183
|
+
self.expect("(")
|
|
184
|
+
name = self.name()
|
|
185
|
+
self.expect(",")
|
|
186
|
+
role, subrole = self.role()
|
|
187
|
+
self.expect(",")
|
|
188
|
+
formula = _FORMULA_RULES[language](self)
|
|
189
|
+
annotations = None
|
|
190
|
+
if self.accept(","):
|
|
191
|
+
source = self.source()
|
|
192
|
+
info = self.general_list() if self.accept(",") else None
|
|
193
|
+
annotations = Annotations(source, info)
|
|
194
|
+
self.expect(")")
|
|
195
|
+
self.expect(".")
|
|
196
|
+
return AnnotatedFormula(language, name, role, formula, annotations, subrole, start.line)
|
|
197
|
+
|
|
198
|
+
def include(self) -> Include:
|
|
199
|
+
start = self.advance()
|
|
200
|
+
self.expect("(")
|
|
201
|
+
file = self.atomic_word()
|
|
202
|
+
selection: Union[None, str, tuple[str, ...]] = None
|
|
203
|
+
space = None
|
|
204
|
+
if self.accept(","):
|
|
205
|
+
if self.accept("*"):
|
|
206
|
+
selection = "*"
|
|
207
|
+
else:
|
|
208
|
+
self.expect("[")
|
|
209
|
+
names = [self.name()]
|
|
210
|
+
while self.accept(","):
|
|
211
|
+
names.append(self.name())
|
|
212
|
+
self.expect("]")
|
|
213
|
+
selection = tuple(names)
|
|
214
|
+
if self.accept(","):
|
|
215
|
+
space = self.name()
|
|
216
|
+
self.expect(")")
|
|
217
|
+
self.expect(".")
|
|
218
|
+
return Include(file, selection, space, start.line)
|
|
219
|
+
|
|
220
|
+
def role(self) -> tuple[str, Optional[Node]]:
|
|
221
|
+
tok = self.tok
|
|
222
|
+
if tok.kind != "lower":
|
|
223
|
+
raise self.error(f"expected a formula role, found {self.describe()}")
|
|
224
|
+
self.advance()
|
|
225
|
+
next_tok = self.tok
|
|
226
|
+
if self.accept("-"):
|
|
227
|
+
return tok.text, self.general_term()
|
|
228
|
+
if next_tok.kind in _NUMBER_KINDS and next_tok.text[0] == "-":
|
|
229
|
+
# "axiom-1" lexes the subrole as a negative number; split the sign off.
|
|
230
|
+
self.tokens[self.i] = next_tok._replace(text=next_tok.text[1:], column=next_tok.column + 1)
|
|
231
|
+
return tok.text, self.general_term()
|
|
232
|
+
return tok.text, None
|
|
233
|
+
|
|
234
|
+
def atomic_word(self) -> str:
|
|
235
|
+
tok = self.tok
|
|
236
|
+
if tok.kind not in _WORD_KINDS:
|
|
237
|
+
raise self.error(f"expected an atomic word, found {self.describe()}")
|
|
238
|
+
self.advance()
|
|
239
|
+
return self.word_text(tok)
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def word_text(tok: _Token) -> str:
|
|
243
|
+
if tok.kind == "sq" and _LOWER_WORD_RE.fullmatch(tok.text, 1, len(tok.text) - 1):
|
|
244
|
+
return tok.text[1:-1]
|
|
245
|
+
return tok.text
|
|
246
|
+
|
|
247
|
+
def name(self) -> str:
|
|
248
|
+
if self.tok.kind == "integer":
|
|
249
|
+
return self.advance().text
|
|
250
|
+
if self.tok.kind not in _WORD_KINDS:
|
|
251
|
+
raise self.error(f"expected a name, found {self.describe()}")
|
|
252
|
+
return self.atomic_word()
|
|
253
|
+
|
|
254
|
+
# --- CNF and TCF --------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
def cnf_formula(self) -> Node:
|
|
257
|
+
if self.accept("("):
|
|
258
|
+
formula = self.cnf_formula()
|
|
259
|
+
self.expect(")")
|
|
260
|
+
return formula
|
|
261
|
+
literals = [self.cnf_literal()]
|
|
262
|
+
while self.accept("|"):
|
|
263
|
+
literals.append(self.cnf_literal())
|
|
264
|
+
return literals[0] if len(literals) == 1 else NAry("|", tuple(literals))
|
|
265
|
+
|
|
266
|
+
def cnf_literal(self) -> Node:
|
|
267
|
+
if not self.accept("~"):
|
|
268
|
+
return self.fof_atomic(allow_inequality=True)
|
|
269
|
+
if self.accept("("):
|
|
270
|
+
atom = self.fof_atomic(allow_inequality=False)
|
|
271
|
+
self.expect(")")
|
|
272
|
+
else:
|
|
273
|
+
atom = self.fof_atomic(allow_inequality=False)
|
|
274
|
+
return Unary("~", atom)
|
|
275
|
+
|
|
276
|
+
def tcf_formula(self) -> Node:
|
|
277
|
+
if self.at_atom_typing():
|
|
278
|
+
return self.atom_typing("tff")
|
|
279
|
+
return self.tcf_logic()
|
|
280
|
+
|
|
281
|
+
def tcf_logic(self) -> Node:
|
|
282
|
+
if self.at("!") and self.peek().text == "[":
|
|
283
|
+
self.advance()
|
|
284
|
+
variables = self.variable_list("tff")
|
|
285
|
+
return Quantified("!", variables, self.tcf_logic())
|
|
286
|
+
return self.cnf_formula()
|
|
287
|
+
|
|
288
|
+
# --- FOF ----------------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
def fof_formula(self) -> Node:
|
|
291
|
+
offset = 0
|
|
292
|
+
while self.peek(offset).text == "(":
|
|
293
|
+
offset += 1
|
|
294
|
+
return self.fof_sequent() if self.peek(offset).text == "[" else self.logic("fof")
|
|
295
|
+
|
|
296
|
+
def fof_sequent(self) -> Node:
|
|
297
|
+
if self.accept("("):
|
|
298
|
+
sequent = self.fof_sequent()
|
|
299
|
+
self.expect(")")
|
|
300
|
+
return sequent
|
|
301
|
+
left = self.fof_tuple()
|
|
302
|
+
self.expect("-->")
|
|
303
|
+
return Binary("-->", left, self.fof_tuple())
|
|
304
|
+
|
|
305
|
+
def fof_tuple(self) -> Tuple:
|
|
306
|
+
self.expect("[")
|
|
307
|
+
items: list[Node] = []
|
|
308
|
+
if not self.at("]"):
|
|
309
|
+
items.append(self.logic("fof"))
|
|
310
|
+
while self.accept(","):
|
|
311
|
+
items.append(self.logic("fof"))
|
|
312
|
+
self.expect("]")
|
|
313
|
+
return Tuple(tuple(items))
|
|
314
|
+
|
|
315
|
+
def fof_atomic(self, *, allow_inequality: bool) -> Node:
|
|
316
|
+
start = self.tok
|
|
317
|
+
left = self.primary("fof")
|
|
318
|
+
op = self.tok.text
|
|
319
|
+
if op == "=" or (op == "!=" and allow_inequality):
|
|
320
|
+
self.advance()
|
|
321
|
+
return Binary(op, left, self.primary("fof"))
|
|
322
|
+
if not isinstance(left, Function):
|
|
323
|
+
raise self.error(f"expected a formula, found the term {self.describe(start)}", start)
|
|
324
|
+
return left
|
|
325
|
+
|
|
326
|
+
# --- shared FOF/TFF/THF logic formulae ----------------------------------------
|
|
327
|
+
|
|
328
|
+
def logic(self, lang: str, *, as_term: bool = False) -> Node:
|
|
329
|
+
"""A logic formula; with ``as_term``, also a TFF term such as a number or tuple."""
|
|
330
|
+
start = self.tok
|
|
331
|
+
left = self.unit(lang)
|
|
332
|
+
op = self.tok.text
|
|
333
|
+
if op in _NONASSOC:
|
|
334
|
+
self.require_formula(lang, left, start)
|
|
335
|
+
self.advance()
|
|
336
|
+
right_start = self.tok
|
|
337
|
+
right = self.unit(lang)
|
|
338
|
+
self.require_formula(lang, right, right_start)
|
|
339
|
+
return Binary(op, left, right)
|
|
340
|
+
if op in _CHAINS[lang]:
|
|
341
|
+
self.require_formula(lang, left, start)
|
|
342
|
+
args = [left]
|
|
343
|
+
while self.accept(op):
|
|
344
|
+
right_start = self.tok
|
|
345
|
+
right = self.unit(lang)
|
|
346
|
+
self.require_formula(lang, right, right_start)
|
|
347
|
+
args.append(right)
|
|
348
|
+
return NAry(op, tuple(args))
|
|
349
|
+
if lang != "fof":
|
|
350
|
+
if op == "==":
|
|
351
|
+
return self.definition(lang, left, start)
|
|
352
|
+
if op == "-->":
|
|
353
|
+
return self.sequent(lang, left, start)
|
|
354
|
+
if lang == "thf" and op in (">", "*", "+"):
|
|
355
|
+
if start.text != "(" and (isinstance(left, Unary) or (
|
|
356
|
+
isinstance(left, Binary) and left.op in ("=", "!="))):
|
|
357
|
+
raise self.error(f"{op!r} needs a unitary left operand; add parentheses", start)
|
|
358
|
+
return self.thf_type_tail(left)
|
|
359
|
+
if not as_term:
|
|
360
|
+
self.require_formula(lang, left, start)
|
|
361
|
+
return left
|
|
362
|
+
|
|
363
|
+
def require_formula(self, lang: str, node: Node, start: _Token) -> None:
|
|
364
|
+
"""Numbers, distinct objects and tuples can't stand alone as TFF formulae."""
|
|
365
|
+
if lang == "tff" and isinstance(node, (Number, DistinctObject, Tuple)):
|
|
366
|
+
raise self.error(f"expected a formula, found the term {self.describe(start)}", start)
|
|
367
|
+
|
|
368
|
+
def definition(self, lang: str, left: Node, start: _Token) -> Node:
|
|
369
|
+
allowed = _THF_DEFINITION_LHS if lang == "thf" else (Function, ModalAtom, Let)
|
|
370
|
+
if not isinstance(left, allowed):
|
|
371
|
+
raise self.error("the left side of '==' must be atomic", start)
|
|
372
|
+
self.expect("==")
|
|
373
|
+
return Binary("==", left, self.logic(lang, as_term=True))
|
|
374
|
+
|
|
375
|
+
def sequent(self, lang: str, left: Node, start: _Token) -> Node:
|
|
376
|
+
if not isinstance(left, Tuple):
|
|
377
|
+
raise self.error("the left side of '-->' must be a tuple", start)
|
|
378
|
+
self.expect("-->")
|
|
379
|
+
if not self.at("["):
|
|
380
|
+
raise self.error(f"expected a tuple after '-->', found {self.describe()}")
|
|
381
|
+
return Binary("-->", left, self.primary(lang))
|
|
382
|
+
|
|
383
|
+
def unit(self, lang: str) -> Node:
|
|
384
|
+
tok = self.tokens[self.i]
|
|
385
|
+
text = tok.text
|
|
386
|
+
if text in _UNARY[lang]:
|
|
387
|
+
self.advance()
|
|
388
|
+
# The grammar requires TFF/THF to write ~ (a = b), but ~ a = b is unambiguous
|
|
389
|
+
# and older TPTP versions allow it, so all languages accept it, as in FOF.
|
|
390
|
+
arg_start = self.tok
|
|
391
|
+
arg = self.unit(lang)
|
|
392
|
+
self.require_formula(lang, arg, arg_start)
|
|
393
|
+
return Unary(text, arg)
|
|
394
|
+
if text in _QUANTIFIERS[lang] and self.peek().text == "[":
|
|
395
|
+
return self.quantified(lang)
|
|
396
|
+
if lang == "fof":
|
|
397
|
+
if self.accept("("):
|
|
398
|
+
formula = self.logic("fof")
|
|
399
|
+
self.expect(")")
|
|
400
|
+
return formula
|
|
401
|
+
return self.fof_atomic(allow_inequality=True)
|
|
402
|
+
left = self.primary(lang)
|
|
403
|
+
op = self.tok.text
|
|
404
|
+
if op == "=" or op == "!=":
|
|
405
|
+
self.advance()
|
|
406
|
+
return Binary(op, left, self.primary(lang))
|
|
407
|
+
return left
|
|
408
|
+
|
|
409
|
+
def quantified(self, lang: str) -> Quantified:
|
|
410
|
+
quantifier = self.advance().text
|
|
411
|
+
variables = self.variable_list(lang)
|
|
412
|
+
body_start = self.tok
|
|
413
|
+
body = self.unit(lang)
|
|
414
|
+
self.require_formula(lang, body, body_start)
|
|
415
|
+
return Quantified(quantifier, variables, body)
|
|
416
|
+
|
|
417
|
+
def variable_list(self, lang: str) -> tuple[Node, ...]:
|
|
418
|
+
self.expect("[")
|
|
419
|
+
variables = [self.variable(lang)]
|
|
420
|
+
while self.accept(","):
|
|
421
|
+
variables.append(self.variable(lang))
|
|
422
|
+
self.expect("]")
|
|
423
|
+
self.expect(":")
|
|
424
|
+
return tuple(variables)
|
|
425
|
+
|
|
426
|
+
def variable(self, lang: str) -> Node:
|
|
427
|
+
tok = self.tok
|
|
428
|
+
if tok.kind != "upper":
|
|
429
|
+
raise self.error(f"expected a variable, found {self.describe()}")
|
|
430
|
+
self.advance()
|
|
431
|
+
if lang == "fof":
|
|
432
|
+
return Variable(tok.text)
|
|
433
|
+
if lang == "thf":
|
|
434
|
+
self.expect(":")
|
|
435
|
+
return TypedVariable(tok.text, self.thf_type())
|
|
436
|
+
if self.accept(":"):
|
|
437
|
+
return TypedVariable(tok.text, self.tff_atomic_type())
|
|
438
|
+
return Variable(tok.text)
|
|
439
|
+
|
|
440
|
+
def primary(self, lang: str) -> Node:
|
|
441
|
+
"""A term, or the atomic formula that has the same shape as one."""
|
|
442
|
+
tok = self.tokens[self.i]
|
|
443
|
+
kind = tok.kind
|
|
444
|
+
if kind == "upper":
|
|
445
|
+
self.i += 1
|
|
446
|
+
return Variable(tok.text)
|
|
447
|
+
if kind in _NUMBER_KINDS:
|
|
448
|
+
self.i += 1
|
|
449
|
+
return Number(tok.text)
|
|
450
|
+
if kind == "distinct":
|
|
451
|
+
self.i += 1
|
|
452
|
+
return DistinctObject(tok.text)
|
|
453
|
+
if kind in _WORD_KINDS or kind == "defined" or kind == "system":
|
|
454
|
+
if tok.text == "$let" and lang != "fof" and self.peek().text == "(":
|
|
455
|
+
return self.let(lang)
|
|
456
|
+
self.i += 1
|
|
457
|
+
name = self.word_text(tok)
|
|
458
|
+
if self.accept("("):
|
|
459
|
+
args = [self.argument(lang)]
|
|
460
|
+
while self.accept(","):
|
|
461
|
+
args.append(self.argument(lang))
|
|
462
|
+
self.expect(")")
|
|
463
|
+
return Function(name, tuple(args))
|
|
464
|
+
return Function(name)
|
|
465
|
+
if lang != "fof":
|
|
466
|
+
text = tok.text
|
|
467
|
+
if text == "(":
|
|
468
|
+
if (lang == "thf" and self.peek().text in _THF_CONNECTIVE_TERMS
|
|
469
|
+
and self.peek(2).text == ")"):
|
|
470
|
+
op = self.peek().text
|
|
471
|
+
self.i += 3
|
|
472
|
+
return ConnectiveTerm(op)
|
|
473
|
+
self.advance()
|
|
474
|
+
formula = self.logic(lang)
|
|
475
|
+
self.expect(")")
|
|
476
|
+
return formula
|
|
477
|
+
if text == "[":
|
|
478
|
+
return self.tuple(lang)
|
|
479
|
+
if text == "{":
|
|
480
|
+
return self.long_connective(lang)
|
|
481
|
+
if lang == "thf" and text in _TH1_TERMS:
|
|
482
|
+
self.advance()
|
|
483
|
+
return ConnectiveTerm(text)
|
|
484
|
+
raise self.error(f"expected a term, found {self.describe()}")
|
|
485
|
+
|
|
486
|
+
def argument(self, lang: str) -> Node:
|
|
487
|
+
if lang == "fof":
|
|
488
|
+
return self.primary("fof")
|
|
489
|
+
return self.logic(lang, as_term=True)
|
|
490
|
+
|
|
491
|
+
def tuple(self, lang: str) -> Tuple:
|
|
492
|
+
self.expect("[")
|
|
493
|
+
items: list[Node] = []
|
|
494
|
+
if not self.at("]"):
|
|
495
|
+
items.append(self.argument(lang))
|
|
496
|
+
while self.accept(","):
|
|
497
|
+
items.append(self.argument(lang))
|
|
498
|
+
self.expect("]")
|
|
499
|
+
return Tuple(tuple(items))
|
|
500
|
+
|
|
501
|
+
def long_connective(self, lang: str) -> Node:
|
|
502
|
+
self.expect("{")
|
|
503
|
+
tok = self.tok
|
|
504
|
+
if tok.kind not in ("defined", "system"):
|
|
505
|
+
raise self.error(f"expected a connective name, found {self.describe()}")
|
|
506
|
+
self.advance()
|
|
507
|
+
params: list[Node] = []
|
|
508
|
+
if self.accept("("):
|
|
509
|
+
params.append(self.connective_parameter(lang))
|
|
510
|
+
while self.accept(","):
|
|
511
|
+
params.append(self.connective_parameter(lang))
|
|
512
|
+
self.expect(")")
|
|
513
|
+
self.expect("}")
|
|
514
|
+
connective = LongConnective(tok.text, tuple(params))
|
|
515
|
+
if lang != "tff":
|
|
516
|
+
return connective
|
|
517
|
+
self.expect("@")
|
|
518
|
+
self.expect("(")
|
|
519
|
+
args = [self.argument("tff")]
|
|
520
|
+
while self.accept(","):
|
|
521
|
+
args.append(self.argument("tff"))
|
|
522
|
+
self.expect(")")
|
|
523
|
+
return ModalAtom(connective, tuple(args))
|
|
524
|
+
|
|
525
|
+
def connective_parameter(self, lang: str) -> Node:
|
|
526
|
+
if self.accept("#"):
|
|
527
|
+
return Index(self.primary("tff"))
|
|
528
|
+
start = self.tok
|
|
529
|
+
param = self.logic(lang, as_term=True)
|
|
530
|
+
if not (isinstance(param, Binary) and param.op == "=="):
|
|
531
|
+
raise self.error("expected '#index' or 'key == value'", start)
|
|
532
|
+
return param
|
|
533
|
+
|
|
534
|
+
def let(self, lang: str) -> Let:
|
|
535
|
+
self.expect("$let")
|
|
536
|
+
self.expect("(")
|
|
537
|
+
if self.accept("["):
|
|
538
|
+
types = [self.atom_typing(lang)]
|
|
539
|
+
while self.accept(","):
|
|
540
|
+
types.append(self.atom_typing(lang))
|
|
541
|
+
self.expect("]")
|
|
542
|
+
else:
|
|
543
|
+
types = [self.atom_typing(lang)]
|
|
544
|
+
self.expect(",")
|
|
545
|
+
if self.at("[") and not self.bracket_is_let_lhs():
|
|
546
|
+
self.advance()
|
|
547
|
+
definitions = [self.let_definition(lang)]
|
|
548
|
+
while self.accept(","):
|
|
549
|
+
definitions.append(self.let_definition(lang))
|
|
550
|
+
self.expect("]")
|
|
551
|
+
else:
|
|
552
|
+
definitions = [self.let_definition(lang)]
|
|
553
|
+
self.expect(",")
|
|
554
|
+
body = self.logic(lang, as_term=lang == "tff")
|
|
555
|
+
self.expect(")")
|
|
556
|
+
return Let(tuple(types), tuple(definitions), body)
|
|
557
|
+
|
|
558
|
+
def bracket_is_let_lhs(self) -> bool:
|
|
559
|
+
"""Tell the tuple in ``[a,b] := t`` from the definition list ``[a := t, ...]``."""
|
|
560
|
+
depth = 0
|
|
561
|
+
for j in range(self.i, len(self.tokens)):
|
|
562
|
+
text = self.tokens[j].text
|
|
563
|
+
if text == "[":
|
|
564
|
+
depth += 1
|
|
565
|
+
elif text == "]":
|
|
566
|
+
depth -= 1
|
|
567
|
+
if depth == 0:
|
|
568
|
+
return self.tokens[j + 1].text == ":="
|
|
569
|
+
return False
|
|
570
|
+
|
|
571
|
+
def let_definition(self, lang: str) -> Binary:
|
|
572
|
+
start = self.tok
|
|
573
|
+
if lang == "thf":
|
|
574
|
+
left = self.logic("thf")
|
|
575
|
+
else:
|
|
576
|
+
left = self.primary("tff")
|
|
577
|
+
if not isinstance(left, (Function, Tuple)):
|
|
578
|
+
raise self.error("the left side of ':=' must be an atom or tuple", start)
|
|
579
|
+
self.expect(":=")
|
|
580
|
+
return Binary(":=", left, self.logic(lang, as_term=lang == "tff"))
|
|
581
|
+
|
|
582
|
+
# --- type declarations --------------------------------------------------------
|
|
583
|
+
|
|
584
|
+
def at_atom_typing(self) -> bool:
|
|
585
|
+
j = self.i
|
|
586
|
+
while self.tokens[j].text == "(":
|
|
587
|
+
j += 1
|
|
588
|
+
tok = self.tokens[j]
|
|
589
|
+
return (tok.kind in _WORD_KINDS or tok.kind == "distinct") and self.tokens[j + 1].text == ":"
|
|
590
|
+
|
|
591
|
+
def atom_typing(self, lang: str) -> Typing:
|
|
592
|
+
if self.accept("("):
|
|
593
|
+
typing = self.atom_typing(lang)
|
|
594
|
+
self.expect(")")
|
|
595
|
+
return typing
|
|
596
|
+
tok = self.tok
|
|
597
|
+
if tok.kind not in _WORD_KINDS and tok.kind != "distinct":
|
|
598
|
+
raise self.error(f"expected an atom to declare a type for, found {self.describe()}")
|
|
599
|
+
self.advance()
|
|
600
|
+
self.expect(":")
|
|
601
|
+
kind_type = self.thf_type() if lang == "thf" else self.tff_type()
|
|
602
|
+
return Typing(self.word_text(tok), kind_type)
|
|
603
|
+
|
|
604
|
+
def at_subtype(self) -> bool:
|
|
605
|
+
tok = self.tok
|
|
606
|
+
return ((tok.kind in _WORD_KINDS or tok.kind in ("defined", "system", "distinct"))
|
|
607
|
+
and self.peek().text == "<<")
|
|
608
|
+
|
|
609
|
+
def subtype(self) -> Binary:
|
|
610
|
+
left = self.subtype_atom()
|
|
611
|
+
self.expect("<<")
|
|
612
|
+
return Binary("<<", left, self.subtype_atom())
|
|
613
|
+
|
|
614
|
+
def subtype_atom(self) -> Node:
|
|
615
|
+
tok = self.tok
|
|
616
|
+
if tok.kind == "distinct":
|
|
617
|
+
self.advance()
|
|
618
|
+
return DistinctObject(tok.text)
|
|
619
|
+
if tok.kind in _WORD_KINDS or tok.kind in ("defined", "system"):
|
|
620
|
+
self.advance()
|
|
621
|
+
return Function(self.word_text(tok))
|
|
622
|
+
raise self.error(f"expected a type name, found {self.describe()}")
|
|
623
|
+
|
|
624
|
+
def tff_formula(self) -> Node:
|
|
625
|
+
if self.at_atom_typing():
|
|
626
|
+
return self.atom_typing("tff")
|
|
627
|
+
if self.at_subtype():
|
|
628
|
+
return self.subtype()
|
|
629
|
+
return self.logic("tff")
|
|
630
|
+
|
|
631
|
+
def thf_formula(self) -> Node:
|
|
632
|
+
if self.at_atom_typing():
|
|
633
|
+
return self.atom_typing("thf")
|
|
634
|
+
if self.at_subtype():
|
|
635
|
+
return self.subtype()
|
|
636
|
+
return self.logic("thf")
|
|
637
|
+
|
|
638
|
+
def tff_type(self, *, in_parens: bool = False) -> Node:
|
|
639
|
+
if self.tok.text in _TYPE_QUANTIFIERS:
|
|
640
|
+
quantifier = self.advance().text
|
|
641
|
+
variables = self.variable_list("tff")
|
|
642
|
+
body_start = self.tok
|
|
643
|
+
body = self.tff_type() if self.tok.text in _TYPE_QUANTIFIERS else self.tff_type_primary()
|
|
644
|
+
if isinstance(body, NAry):
|
|
645
|
+
raise self.error("a product type must be followed by '>'", body_start)
|
|
646
|
+
return Quantified(quantifier, variables, body)
|
|
647
|
+
start = self.tok
|
|
648
|
+
left = self.tff_type_primary()
|
|
649
|
+
if isinstance(left, (Binary, Quantified)) and self.tok.text in (">", "*"):
|
|
650
|
+
raise self.error(f"this type can't be an operand of {self.tok.text!r}", start)
|
|
651
|
+
if self.accept(">"):
|
|
652
|
+
return Binary(">", left, self.tff_atomic_type())
|
|
653
|
+
if in_parens and self.at("*"):
|
|
654
|
+
args = [left]
|
|
655
|
+
while self.accept("*"):
|
|
656
|
+
args.append(self.tff_atomic_type())
|
|
657
|
+
return NAry("*", tuple(args))
|
|
658
|
+
if isinstance(left, NAry):
|
|
659
|
+
raise self.error("a product type must be followed by '>'", start)
|
|
660
|
+
return left
|
|
661
|
+
|
|
662
|
+
def tff_type_primary(self) -> Node:
|
|
663
|
+
tok = self.tok
|
|
664
|
+
if self.accept("("):
|
|
665
|
+
inner = self.tff_type(in_parens=True)
|
|
666
|
+
self.expect(")")
|
|
667
|
+
return inner
|
|
668
|
+
if tok.text == "[":
|
|
669
|
+
self.advance()
|
|
670
|
+
items = [self.tff_type()]
|
|
671
|
+
while self.accept(","):
|
|
672
|
+
items.append(self.tff_type())
|
|
673
|
+
self.expect("]")
|
|
674
|
+
return Tuple(tuple(items))
|
|
675
|
+
if tok.kind == "upper":
|
|
676
|
+
self.advance()
|
|
677
|
+
return Variable(tok.text)
|
|
678
|
+
if tok.kind == "defined":
|
|
679
|
+
self.advance()
|
|
680
|
+
return Function(tok.text)
|
|
681
|
+
if tok.kind in _WORD_KINDS:
|
|
682
|
+
self.advance()
|
|
683
|
+
name = self.word_text(tok)
|
|
684
|
+
if self.accept("("):
|
|
685
|
+
args = [self.tff_atomic_type()]
|
|
686
|
+
while self.accept(","):
|
|
687
|
+
args.append(self.tff_atomic_type())
|
|
688
|
+
self.expect(")")
|
|
689
|
+
return Function(name, tuple(args))
|
|
690
|
+
return Function(name)
|
|
691
|
+
raise self.error(f"expected a type, found {self.describe()}")
|
|
692
|
+
|
|
693
|
+
def tff_atomic_type(self) -> Node:
|
|
694
|
+
start = self.tok
|
|
695
|
+
node = self.tff_type_primary()
|
|
696
|
+
if not isinstance(node, (Variable, Function, Tuple)):
|
|
697
|
+
raise self.error("expected an atomic type", start)
|
|
698
|
+
return node
|
|
699
|
+
|
|
700
|
+
def thf_type(self) -> Node:
|
|
701
|
+
left = self.thf_unitary()
|
|
702
|
+
if self.tok.text in (">", "*", "+", "@"):
|
|
703
|
+
return self.thf_type_tail(left)
|
|
704
|
+
return left
|
|
705
|
+
|
|
706
|
+
def thf_type_tail(self, left: Node) -> Node:
|
|
707
|
+
op = self.tok.text
|
|
708
|
+
if op == ">":
|
|
709
|
+
operands = [left]
|
|
710
|
+
while self.accept(">"):
|
|
711
|
+
operands.append(self.thf_unitary())
|
|
712
|
+
result = operands[-1]
|
|
713
|
+
for operand in reversed(operands[:-1]):
|
|
714
|
+
result = Binary(">", operand, result)
|
|
715
|
+
return result
|
|
716
|
+
args = [left]
|
|
717
|
+
read = self.unit if op == "@" else None
|
|
718
|
+
while self.accept(op):
|
|
719
|
+
args.append(read("thf") if read else self.thf_unitary())
|
|
720
|
+
return NAry(op, tuple(args))
|
|
721
|
+
|
|
722
|
+
def thf_unitary(self) -> Node:
|
|
723
|
+
if self.tok.text in _QUANTIFIERS["thf"] and self.peek().text == "[":
|
|
724
|
+
return self.quantified("thf")
|
|
725
|
+
return self.primary("thf")
|
|
726
|
+
|
|
727
|
+
# --- annotations and non-logical data -----------------------------------------
|
|
728
|
+
|
|
729
|
+
def source(self) -> Node:
|
|
730
|
+
tok = self.tok
|
|
731
|
+
if tok.text == "[":
|
|
732
|
+
self.advance()
|
|
733
|
+
sources = [self.source()]
|
|
734
|
+
while self.accept(","):
|
|
735
|
+
sources.append(self.source())
|
|
736
|
+
self.expect("]")
|
|
737
|
+
return SourceList(tuple(sources))
|
|
738
|
+
if self.peek().text == "(":
|
|
739
|
+
if tok.text == "inference":
|
|
740
|
+
return self.derivation_source(Inference)
|
|
741
|
+
if tok.text == "introduced":
|
|
742
|
+
return self.derivation_source(Introduced)
|
|
743
|
+
if tok.text == "file":
|
|
744
|
+
self.i += 2
|
|
745
|
+
file = self.atomic_word()
|
|
746
|
+
name = self.name() if self.accept(",") else None
|
|
747
|
+
self.expect(")")
|
|
748
|
+
return FileSource(file, name)
|
|
749
|
+
return Name(self.name())
|
|
750
|
+
|
|
751
|
+
def derivation_source(self, node_type: type) -> Node:
|
|
752
|
+
self.i += 2
|
|
753
|
+
word = self.atomic_word()
|
|
754
|
+
self.expect(",")
|
|
755
|
+
info = self.general_list()
|
|
756
|
+
self.expect(",")
|
|
757
|
+
self.expect("[")
|
|
758
|
+
parents: list[Parent] = []
|
|
759
|
+
if not self.at("]"):
|
|
760
|
+
parents.append(self.parent())
|
|
761
|
+
while self.accept(","):
|
|
762
|
+
parents.append(self.parent())
|
|
763
|
+
self.expect("]")
|
|
764
|
+
self.expect(")")
|
|
765
|
+
return node_type(word, info, tuple(parents))
|
|
766
|
+
|
|
767
|
+
def parent(self) -> Parent:
|
|
768
|
+
source = self.source()
|
|
769
|
+
return Parent(source, self.general_term() if self.accept(":") else None)
|
|
770
|
+
|
|
771
|
+
def general_list(self) -> Tuple:
|
|
772
|
+
self.expect("[")
|
|
773
|
+
items: list[Node] = []
|
|
774
|
+
if not self.at("]"):
|
|
775
|
+
items.append(self.general_term())
|
|
776
|
+
while self.accept(","):
|
|
777
|
+
items.append(self.general_term())
|
|
778
|
+
self.expect("]")
|
|
779
|
+
return Tuple(tuple(items))
|
|
780
|
+
|
|
781
|
+
def general_term(self) -> Node:
|
|
782
|
+
if self.at("["):
|
|
783
|
+
return self.general_list()
|
|
784
|
+
data = self.general_data()
|
|
785
|
+
if self.accept(":"):
|
|
786
|
+
return Binary(":", data, self.general_term())
|
|
787
|
+
return data
|
|
788
|
+
|
|
789
|
+
def general_data(self) -> Node:
|
|
790
|
+
tok = self.tok
|
|
791
|
+
kind = tok.kind
|
|
792
|
+
if kind == "upper":
|
|
793
|
+
self.advance()
|
|
794
|
+
return Variable(tok.text)
|
|
795
|
+
if kind in _NUMBER_KINDS:
|
|
796
|
+
self.advance()
|
|
797
|
+
return Number(tok.text)
|
|
798
|
+
if kind == "distinct":
|
|
799
|
+
self.advance()
|
|
800
|
+
return DistinctObject(tok.text)
|
|
801
|
+
if kind in _WORD_KINDS:
|
|
802
|
+
self.advance()
|
|
803
|
+
name = self.word_text(tok)
|
|
804
|
+
if self.accept("("):
|
|
805
|
+
args = [self.general_term()]
|
|
806
|
+
while self.accept(","):
|
|
807
|
+
args.append(self.general_term())
|
|
808
|
+
self.expect(")")
|
|
809
|
+
return Function(name, tuple(args))
|
|
810
|
+
return Function(name)
|
|
811
|
+
if tok.text in _FORMULA_DATA_RULES and self.peek().text == "(":
|
|
812
|
+
self.i += 2
|
|
813
|
+
formula = _FORMULA_DATA_RULES[tok.text](self)
|
|
814
|
+
self.expect(")")
|
|
815
|
+
return FormulaData(tok.text[1:], formula)
|
|
816
|
+
raise self.error(f"expected general data, found {self.describe()}")
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
_FORMULA_RULES = {
|
|
820
|
+
"thf": _Parser.thf_formula,
|
|
821
|
+
"tff": _Parser.tff_formula,
|
|
822
|
+
"tcf": _Parser.tcf_formula,
|
|
823
|
+
"fof": _Parser.fof_formula,
|
|
824
|
+
"cnf": _Parser.cnf_formula,
|
|
825
|
+
"tpi": _Parser.fof_formula,
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
_FORMULA_DATA_RULES = {
|
|
829
|
+
"$thf": _Parser.thf_formula,
|
|
830
|
+
"$tff": _Parser.tff_formula,
|
|
831
|
+
"$fof": _Parser.fof_formula,
|
|
832
|
+
"$cnf": _Parser.cnf_formula,
|
|
833
|
+
"$fot": lambda parser: parser.primary("fof"),
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
# ---------------------------------------------------------------------------------
|
|
838
|
+
# Entry points used by the package's public functions
|
|
839
|
+
# ---------------------------------------------------------------------------------
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def parse(text: str, filename: Optional[str] = None) -> TPTPFile:
|
|
843
|
+
with _deep_stack():
|
|
844
|
+
parser = _Parser(text, filename)
|
|
845
|
+
try:
|
|
846
|
+
return parser.parse_file()
|
|
847
|
+
except RecursionError:
|
|
848
|
+
raise parser.error("formula is too deeply nested") from None
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def parse_formula(text: str, language: str) -> Node:
|
|
852
|
+
with _deep_stack():
|
|
853
|
+
parser = _Parser(text)
|
|
854
|
+
try:
|
|
855
|
+
formula = _FORMULA_RULES[language](parser)
|
|
856
|
+
except RecursionError:
|
|
857
|
+
raise parser.error("formula is too deeply nested") from None
|
|
858
|
+
if parser.tok.kind != "eof":
|
|
859
|
+
raise parser.error(f"unexpected {parser.describe()} after the formula")
|
|
860
|
+
return formula
|