thousandproblems 0.3.0__cp315-cp315-win_amd64.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.
@@ -0,0 +1,946 @@
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, _symbol_table
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
+ # Variable numbering and the symbols used, for the formula being parsed.
129
+ self.numbering = False # only inside a formula, not in annotations
130
+ self.count = 0 # variables numbered so far in this formula
131
+ self.vars: dict[str, int] = {} # name -> index of the binding in scope (0: none)
132
+ self.undo: list[tuple[str, int]] = [] # bindings to restore when a quantifier ends
133
+ self.events: list[Optional[tuple[str, int]]] = [] # (name, arity) of each function use
134
+ self.type_depth = 0 # > 0 while reading a THF type, whose names are not symbols
135
+ self.symtab: dict[tuple[str, int], Symbol] = {} # every symbol of the file
136
+
137
+ # --- token helpers ------------------------------------------------------------
138
+
139
+ @property
140
+ def tok(self) -> _Token:
141
+ return self.tokens[self.i]
142
+
143
+ def peek(self, offset: int = 1) -> _Token:
144
+ return self.tokens[min(self.i + offset, len(self.tokens) - 1)]
145
+
146
+ def advance(self) -> _Token:
147
+ tok = self.tokens[self.i]
148
+ if tok.kind != "eof":
149
+ self.i += 1
150
+ return tok
151
+
152
+ def at(self, text: str) -> bool:
153
+ return self.tokens[self.i].text == text
154
+
155
+ def accept(self, text: str) -> bool:
156
+ if self.tokens[self.i].text == text:
157
+ self.i += 1
158
+ return True
159
+ return False
160
+
161
+ def expect(self, text: str) -> _Token:
162
+ if self.tokens[self.i].text != text:
163
+ raise self.error(f"expected {text!r}, found {self.describe()}")
164
+ return self.advance()
165
+
166
+ def describe(self, tok: Optional[_Token] = None) -> str:
167
+ tok = tok or self.tok
168
+ return "end of input" if tok.kind == "eof" else repr(tok.text)
169
+
170
+ def error(self, message: str, tok: Optional[_Token] = None) -> ParseError:
171
+ tok = tok or self.tok
172
+ return _error_at(message, self.text, tok.line, tok.column, self.filename)
173
+
174
+ # --- variable numbering and symbols ---------------------------------------------
175
+
176
+ def begin_formula(self) -> None:
177
+ self.numbering = True
178
+ self.count = 0
179
+ self.vars.clear()
180
+ self.undo.clear()
181
+ self.events.clear()
182
+ self.type_depth = 0
183
+
184
+ def bind(self, name: str) -> int:
185
+ """A quantifier binds a new variable ``name``."""
186
+ if not self.numbering:
187
+ return 0
188
+ self.count += 1
189
+ self.undo.append((name, self.vars.get(name, 0)))
190
+ self.vars[name] = self.count
191
+ return self.count
192
+
193
+ def use(self, name: str) -> int:
194
+ """The index of the variable ``name`` in scope; a variable not bound is numbered on first use."""
195
+ if not self.numbering:
196
+ return 0
197
+ index = self.vars.get(name, 0)
198
+ if not index:
199
+ self.count += 1
200
+ index = self.vars[name] = self.count
201
+ return index
202
+
203
+ def release(self, mark: int) -> None:
204
+ """A quantifier's scope has ended: restore what its variables shadowed."""
205
+ undo = self.undo
206
+ while len(undo) > mark:
207
+ name, previous = undo.pop()
208
+ self.vars[name] = previous
209
+
210
+ def end_formula(self) -> tuple[Symbol, ...]:
211
+ """Finish the formula: the symbols it used, in order of first appearance."""
212
+ self.numbering = False
213
+ symbols: dict[tuple[str, int], Symbol] = {}
214
+ for key in self.events:
215
+ if key not in symbols:
216
+ symbol = self.symtab.get(key)
217
+ if symbol is None:
218
+ symbol = self.symtab[key] = Symbol(*key)
219
+ symbols[key] = symbol
220
+ self.events.clear()
221
+ return tuple(symbols.values())
222
+
223
+ # --- files --------------------------------------------------------------------
224
+
225
+ def parse_file(self) -> TPTPFile:
226
+ inputs: list[Union[AnnotatedFormula, Include]] = []
227
+ while self.tok.kind != "eof":
228
+ tok = self.tok
229
+ if tok.text == "include" and self.peek().text == "(":
230
+ inputs.append(self.include())
231
+ elif tok.text in _FORMULA_RULES and self.peek().text == "(":
232
+ inputs.append(self.annotated_formula())
233
+ else:
234
+ raise self.error(f"expected an annotated formula or include, found {self.describe()}")
235
+ return TPTPFile(tuple(inputs), tuple(self.comments), self.filename, tuple(self.symtab.values()))
236
+
237
+ def annotated_formula(self) -> AnnotatedFormula:
238
+ start = self.advance()
239
+ language = start.text
240
+ self.expect("(")
241
+ name = self.name()
242
+ self.expect(",")
243
+ role, subrole = self.role()
244
+ self.expect(",")
245
+ self.begin_formula()
246
+ formula = _FORMULA_RULES[language](self)
247
+ symbols = self.end_formula()
248
+ annotations = None
249
+ if self.accept(","):
250
+ source = self.source()
251
+ info = self.general_list() if self.accept(",") else None
252
+ annotations = Annotations(source, info)
253
+ self.expect(")")
254
+ self.expect(".")
255
+ return AnnotatedFormula(language, name, role, formula, annotations, subrole, start.line, symbols)
256
+
257
+ def include(self) -> Include:
258
+ start = self.advance()
259
+ self.expect("(")
260
+ file = self.atomic_word()
261
+ selection: Union[None, str, tuple[str, ...]] = None
262
+ space = None
263
+ if self.accept(","):
264
+ if self.accept("*"):
265
+ selection = "*"
266
+ else:
267
+ self.expect("[")
268
+ names = [self.name()]
269
+ while self.accept(","):
270
+ names.append(self.name())
271
+ self.expect("]")
272
+ selection = tuple(names)
273
+ if self.accept(","):
274
+ space = self.name()
275
+ self.expect(")")
276
+ self.expect(".")
277
+ return Include(file, selection, space, start.line)
278
+
279
+ def role(self) -> tuple[str, Optional[Node]]:
280
+ tok = self.tok
281
+ if tok.kind != "lower":
282
+ raise self.error(f"expected a formula role, found {self.describe()}")
283
+ self.advance()
284
+ next_tok = self.tok
285
+ if self.accept("-"):
286
+ return tok.text, self.general_term()
287
+ if next_tok.kind in _NUMBER_KINDS and next_tok.text[0] == "-":
288
+ # "axiom-1" lexes the subrole as a negative number; split the sign off.
289
+ self.tokens[self.i] = next_tok._replace(text=next_tok.text[1:], column=next_tok.column + 1)
290
+ return tok.text, self.general_term()
291
+ return tok.text, None
292
+
293
+ def atomic_word(self) -> str:
294
+ tok = self.tok
295
+ if tok.kind not in _WORD_KINDS:
296
+ raise self.error(f"expected an atomic word, found {self.describe()}")
297
+ self.advance()
298
+ return self.word_text(tok)
299
+
300
+ @staticmethod
301
+ def word_text(tok: _Token) -> str:
302
+ if tok.kind == "sq" and _LOWER_WORD_RE.fullmatch(tok.text, 1, len(tok.text) - 1):
303
+ return tok.text[1:-1]
304
+ return tok.text
305
+
306
+ def name(self) -> str:
307
+ if self.tok.kind == "integer":
308
+ return self.advance().text
309
+ if self.tok.kind not in _WORD_KINDS:
310
+ raise self.error(f"expected a name, found {self.describe()}")
311
+ return self.atomic_word()
312
+
313
+ # --- CNF and TCF --------------------------------------------------------------
314
+
315
+ def cnf_formula(self) -> Node:
316
+ if self.accept("("):
317
+ formula = self.cnf_formula()
318
+ self.expect(")")
319
+ return formula
320
+ literals = [self.cnf_literal()]
321
+ while self.accept("|"):
322
+ literals.append(self.cnf_literal())
323
+ return literals[0] if len(literals) == 1 else NAry("|", tuple(literals))
324
+
325
+ def cnf_literal(self) -> Node:
326
+ if not self.accept("~"):
327
+ return self.fof_atomic(allow_inequality=True)
328
+ if self.accept("("):
329
+ atom = self.fof_atomic(allow_inequality=False)
330
+ self.expect(")")
331
+ else:
332
+ atom = self.fof_atomic(allow_inequality=False)
333
+ return Unary("~", atom)
334
+
335
+ def tcf_formula(self) -> Node:
336
+ if self.at_atom_typing():
337
+ return self.atom_typing("tff")
338
+ return self.tcf_logic()
339
+
340
+ def tcf_logic(self) -> Node:
341
+ if self.at("!") and self.peek().text == "[":
342
+ self.advance()
343
+ mark = len(self.undo)
344
+ variables = self.variable_list("tff")
345
+ body = self.tcf_logic()
346
+ self.release(mark)
347
+ return Quantified("!", variables, body)
348
+ return self.cnf_formula()
349
+
350
+ # --- FOF ----------------------------------------------------------------------
351
+
352
+ def fof_formula(self) -> Node:
353
+ offset = 0
354
+ while self.peek(offset).text == "(":
355
+ offset += 1
356
+ return self.fof_sequent() if self.peek(offset).text == "[" else self.logic("fof")
357
+
358
+ def fof_sequent(self) -> Node:
359
+ if self.accept("("):
360
+ sequent = self.fof_sequent()
361
+ self.expect(")")
362
+ return sequent
363
+ left = self.fof_tuple()
364
+ self.expect("-->")
365
+ return Binary("-->", left, self.fof_tuple())
366
+
367
+ def fof_tuple(self) -> Tuple:
368
+ self.expect("[")
369
+ items: list[Node] = []
370
+ if not self.at("]"):
371
+ items.append(self.logic("fof"))
372
+ while self.accept(","):
373
+ items.append(self.logic("fof"))
374
+ self.expect("]")
375
+ return Tuple(tuple(items))
376
+
377
+ def fof_atomic(self, *, allow_inequality: bool) -> Node:
378
+ start = self.tok
379
+ left = self.primary("fof")
380
+ op = self.tok.text
381
+ if op == "=" or (op == "!=" and allow_inequality):
382
+ self.advance()
383
+ return Binary(op, left, self.primary("fof"))
384
+ if not isinstance(left, Function):
385
+ raise self.error(f"expected a formula, found the term {self.describe(start)}", start)
386
+ return left
387
+
388
+ # --- shared FOF/TFF/THF logic formulae ----------------------------------------
389
+
390
+ def logic(self, lang: str, *, as_term: bool = False) -> Node:
391
+ """A logic formula; with ``as_term``, also a TFF term such as a number or tuple."""
392
+ start = self.tok
393
+ left = self.unit(lang)
394
+ op = self.tok.text
395
+ if op in _NONASSOC:
396
+ self.require_formula(lang, left, start)
397
+ self.advance()
398
+ right_start = self.tok
399
+ right = self.unit(lang)
400
+ self.require_formula(lang, right, right_start)
401
+ return Binary(op, left, right)
402
+ if op in _CHAINS[lang]:
403
+ self.require_formula(lang, left, start)
404
+ args = [left]
405
+ while self.accept(op):
406
+ right_start = self.tok
407
+ right = self.unit(lang)
408
+ self.require_formula(lang, right, right_start)
409
+ args.append(right)
410
+ return NAry(op, tuple(args))
411
+ if lang != "fof":
412
+ if op == "==":
413
+ return self.definition(lang, left, start)
414
+ if op == "-->":
415
+ return self.sequent(lang, left, start)
416
+ if lang == "thf" and op in (">", "*", "+"):
417
+ if start.text != "(" and (isinstance(left, Unary) or (
418
+ isinstance(left, Binary) and left.op in ("=", "!="))):
419
+ raise self.error(f"{op!r} needs a unitary left operand; add parentheses", start)
420
+ return self.thf_type_tail(left)
421
+ if not as_term:
422
+ self.require_formula(lang, left, start)
423
+ return left
424
+
425
+ def require_formula(self, lang: str, node: Node, start: _Token) -> None:
426
+ """Numbers, distinct objects and tuples can't stand alone as TFF formulae."""
427
+ if lang == "tff" and isinstance(node, (Number, DistinctObject, Tuple)):
428
+ raise self.error(f"expected a formula, found the term {self.describe(start)}", start)
429
+
430
+ def definition(self, lang: str, left: Node, start: _Token) -> Node:
431
+ allowed = _THF_DEFINITION_LHS if lang == "thf" else (Function, ModalAtom, Let)
432
+ if not isinstance(left, allowed):
433
+ raise self.error("the left side of '==' must be atomic", start)
434
+ self.expect("==")
435
+ return Binary("==", left, self.logic(lang, as_term=True))
436
+
437
+ def sequent(self, lang: str, left: Node, start: _Token) -> Node:
438
+ if not isinstance(left, Tuple):
439
+ raise self.error("the left side of '-->' must be a tuple", start)
440
+ self.expect("-->")
441
+ if not self.at("["):
442
+ raise self.error(f"expected a tuple after '-->', found {self.describe()}")
443
+ return Binary("-->", left, self.primary(lang))
444
+
445
+ def unit(self, lang: str) -> Node:
446
+ tok = self.tokens[self.i]
447
+ text = tok.text
448
+ if text in _UNARY[lang]:
449
+ self.advance()
450
+ # The grammar requires TFF/THF to write ~ (a = b), but ~ a = b is unambiguous
451
+ # and older TPTP versions allow it, so all languages accept it, as in FOF.
452
+ arg_start = self.tok
453
+ arg = self.unit(lang)
454
+ self.require_formula(lang, arg, arg_start)
455
+ return Unary(text, arg)
456
+ if text in _QUANTIFIERS[lang] and self.peek().text == "[":
457
+ return self.quantified(lang)
458
+ if lang == "fof":
459
+ if self.accept("("):
460
+ formula = self.logic("fof")
461
+ self.expect(")")
462
+ return formula
463
+ return self.fof_atomic(allow_inequality=True)
464
+ left = self.primary(lang)
465
+ op = self.tok.text
466
+ if op == "=" or op == "!=":
467
+ self.advance()
468
+ return Binary(op, left, self.primary(lang))
469
+ return left
470
+
471
+ def quantified(self, lang: str) -> Quantified:
472
+ quantifier = self.advance().text
473
+ mark = len(self.undo)
474
+ variables = self.variable_list(lang)
475
+ body_start = self.tok
476
+ body = self.unit(lang)
477
+ self.require_formula(lang, body, body_start)
478
+ self.release(mark)
479
+ return Quantified(quantifier, variables, body)
480
+
481
+ def variable_list(self, lang: str) -> tuple[Node, ...]:
482
+ self.expect("[")
483
+ variables = [self.variable(lang)]
484
+ while self.accept(","):
485
+ variables.append(self.variable(lang))
486
+ self.expect("]")
487
+ self.expect(":")
488
+ return tuple(variables)
489
+
490
+ def variable(self, lang: str) -> Node:
491
+ tok = self.tok
492
+ if tok.kind != "upper":
493
+ raise self.error(f"expected a variable, found {self.describe()}")
494
+ self.advance()
495
+ index = self.bind(tok.text)
496
+ if lang == "fof":
497
+ return Variable(tok.text, index)
498
+ if lang == "thf":
499
+ self.expect(":")
500
+ self.type_depth += 1
501
+ var_type = self.thf_type()
502
+ self.type_depth -= 1
503
+ return TypedVariable(tok.text, var_type, index)
504
+ if self.accept(":"):
505
+ return TypedVariable(tok.text, self.tff_atomic_type(), index)
506
+ return Variable(tok.text, index)
507
+
508
+ def primary(self, lang: str) -> Node:
509
+ """A term, or the atomic formula that has the same shape as one."""
510
+ tok = self.tokens[self.i]
511
+ kind = tok.kind
512
+ if kind == "upper":
513
+ self.i += 1
514
+ return Variable(tok.text, self.use(tok.text))
515
+ if kind in _NUMBER_KINDS:
516
+ self.i += 1
517
+ return Number(tok.text)
518
+ if kind == "distinct":
519
+ self.i += 1
520
+ return DistinctObject(tok.text)
521
+ if kind in _WORD_KINDS or kind == "defined" or kind == "system":
522
+ if tok.text == "$let" and lang != "fof" and self.peek().text == "(":
523
+ return self.let(lang)
524
+ self.i += 1
525
+ name = self.word_text(tok)
526
+ # Reserve this use's place in the order of first appearance now, and fill in the
527
+ # arity once the arguments are read. $-symbols are not recorded.
528
+ slot = -1
529
+ if self.numbering and not self.type_depth and kind in _WORD_KINDS:
530
+ slot = len(self.events)
531
+ self.events.append(None)
532
+ if self.accept("("):
533
+ args = [self.argument(lang)]
534
+ while self.accept(","):
535
+ args.append(self.argument(lang))
536
+ self.expect(")")
537
+ if slot >= 0:
538
+ self.events[slot] = (name, len(args))
539
+ return Function(name, tuple(args))
540
+ if slot >= 0:
541
+ self.events[slot] = (name, 0)
542
+ return Function(name)
543
+ if lang != "fof":
544
+ text = tok.text
545
+ if text == "(":
546
+ if (lang == "thf" and self.peek().text in _THF_CONNECTIVE_TERMS
547
+ and self.peek(2).text == ")"):
548
+ op = self.peek().text
549
+ self.i += 3
550
+ return ConnectiveTerm(op)
551
+ self.advance()
552
+ formula = self.logic(lang)
553
+ self.expect(")")
554
+ return formula
555
+ if text == "[":
556
+ return self.tuple(lang)
557
+ if text == "{":
558
+ return self.long_connective(lang)
559
+ if lang == "thf" and text in _TH1_TERMS:
560
+ self.advance()
561
+ return ConnectiveTerm(text)
562
+ raise self.error(f"expected a term, found {self.describe()}")
563
+
564
+ def argument(self, lang: str) -> Node:
565
+ if lang == "fof":
566
+ return self.primary("fof")
567
+ return self.logic(lang, as_term=True)
568
+
569
+ def tuple(self, lang: str) -> Tuple:
570
+ self.expect("[")
571
+ items: list[Node] = []
572
+ if not self.at("]"):
573
+ items.append(self.argument(lang))
574
+ while self.accept(","):
575
+ items.append(self.argument(lang))
576
+ self.expect("]")
577
+ return Tuple(tuple(items))
578
+
579
+ def long_connective(self, lang: str) -> Node:
580
+ self.expect("{")
581
+ tok = self.tok
582
+ if tok.kind not in ("defined", "system"):
583
+ raise self.error(f"expected a connective name, found {self.describe()}")
584
+ self.advance()
585
+ params: list[Node] = []
586
+ if self.accept("("):
587
+ params.append(self.connective_parameter(lang))
588
+ while self.accept(","):
589
+ params.append(self.connective_parameter(lang))
590
+ self.expect(")")
591
+ self.expect("}")
592
+ connective = LongConnective(tok.text, tuple(params))
593
+ if lang != "tff":
594
+ return connective
595
+ self.expect("@")
596
+ self.expect("(")
597
+ args = [self.argument("tff")]
598
+ while self.accept(","):
599
+ args.append(self.argument("tff"))
600
+ self.expect(")")
601
+ return ModalAtom(connective, tuple(args))
602
+
603
+ def connective_parameter(self, lang: str) -> Node:
604
+ if self.accept("#"):
605
+ return Index(self.primary("tff"))
606
+ start = self.tok
607
+ param = self.logic(lang, as_term=True)
608
+ if not (isinstance(param, Binary) and param.op == "=="):
609
+ raise self.error("expected '#index' or 'key == value'", start)
610
+ return param
611
+
612
+ def let(self, lang: str) -> Let:
613
+ self.expect("$let")
614
+ self.expect("(")
615
+ if self.accept("["):
616
+ types = [self.atom_typing(lang)]
617
+ while self.accept(","):
618
+ types.append(self.atom_typing(lang))
619
+ self.expect("]")
620
+ else:
621
+ types = [self.atom_typing(lang)]
622
+ self.expect(",")
623
+ if self.at("[") and not self.bracket_is_let_lhs():
624
+ self.advance()
625
+ definitions = [self.let_definition(lang)]
626
+ while self.accept(","):
627
+ definitions.append(self.let_definition(lang))
628
+ self.expect("]")
629
+ else:
630
+ definitions = [self.let_definition(lang)]
631
+ self.expect(",")
632
+ body = self.logic(lang, as_term=lang == "tff")
633
+ self.expect(")")
634
+ return Let(tuple(types), tuple(definitions), body)
635
+
636
+ def bracket_is_let_lhs(self) -> bool:
637
+ """Tell the tuple in ``[a,b] := t`` from the definition list ``[a := t, ...]``."""
638
+ depth = 0
639
+ for j in range(self.i, len(self.tokens)):
640
+ text = self.tokens[j].text
641
+ if text == "[":
642
+ depth += 1
643
+ elif text == "]":
644
+ depth -= 1
645
+ if depth == 0:
646
+ return self.tokens[j + 1].text == ":="
647
+ return False
648
+
649
+ def let_definition(self, lang: str) -> Binary:
650
+ start = self.tok
651
+ if lang == "thf":
652
+ left = self.logic("thf")
653
+ else:
654
+ left = self.primary("tff")
655
+ if not isinstance(left, (Function, Tuple)):
656
+ raise self.error("the left side of ':=' must be an atom or tuple", start)
657
+ self.expect(":=")
658
+ return Binary(":=", left, self.logic(lang, as_term=lang == "tff"))
659
+
660
+ # --- type declarations --------------------------------------------------------
661
+
662
+ def at_atom_typing(self) -> bool:
663
+ j = self.i
664
+ while self.tokens[j].text == "(":
665
+ j += 1
666
+ tok = self.tokens[j]
667
+ return (tok.kind in _WORD_KINDS or tok.kind == "distinct") and self.tokens[j + 1].text == ":"
668
+
669
+ def atom_typing(self, lang: str) -> Typing:
670
+ if self.accept("("):
671
+ typing = self.atom_typing(lang)
672
+ self.expect(")")
673
+ return typing
674
+ tok = self.tok
675
+ if tok.kind not in _WORD_KINDS and tok.kind != "distinct":
676
+ raise self.error(f"expected an atom to declare a type for, found {self.describe()}")
677
+ self.advance()
678
+ self.expect(":")
679
+ if lang == "thf":
680
+ self.type_depth += 1
681
+ kind_type = self.thf_type()
682
+ self.type_depth -= 1
683
+ else:
684
+ kind_type = self.tff_type()
685
+ return Typing(self.word_text(tok), kind_type)
686
+
687
+ def at_subtype(self) -> bool:
688
+ tok = self.tok
689
+ return ((tok.kind in _WORD_KINDS or tok.kind in ("defined", "system", "distinct"))
690
+ and self.peek().text == "<<")
691
+
692
+ def subtype(self) -> Binary:
693
+ left = self.subtype_atom()
694
+ self.expect("<<")
695
+ return Binary("<<", left, self.subtype_atom())
696
+
697
+ def subtype_atom(self) -> Node:
698
+ tok = self.tok
699
+ if tok.kind == "distinct":
700
+ self.advance()
701
+ return DistinctObject(tok.text)
702
+ if tok.kind in _WORD_KINDS or tok.kind in ("defined", "system"):
703
+ self.advance()
704
+ return Function(self.word_text(tok))
705
+ raise self.error(f"expected a type name, found {self.describe()}")
706
+
707
+ def tff_formula(self) -> Node:
708
+ if self.at_atom_typing():
709
+ return self.atom_typing("tff")
710
+ if self.at_subtype():
711
+ return self.subtype()
712
+ return self.logic("tff")
713
+
714
+ def thf_formula(self) -> Node:
715
+ if self.at_atom_typing():
716
+ return self.atom_typing("thf")
717
+ if self.at_subtype():
718
+ return self.subtype()
719
+ return self.logic("thf")
720
+
721
+ def tff_type(self, *, in_parens: bool = False) -> Node:
722
+ if self.tok.text in _TYPE_QUANTIFIERS:
723
+ quantifier = self.advance().text
724
+ mark = len(self.undo)
725
+ variables = self.variable_list("tff")
726
+ body_start = self.tok
727
+ body = self.tff_type() if self.tok.text in _TYPE_QUANTIFIERS else self.tff_type_primary()
728
+ if isinstance(body, NAry):
729
+ raise self.error("a product type must be followed by '>'", body_start)
730
+ self.release(mark)
731
+ return Quantified(quantifier, variables, body)
732
+ start = self.tok
733
+ left = self.tff_type_primary()
734
+ if isinstance(left, (Binary, Quantified)) and self.tok.text in (">", "*"):
735
+ raise self.error(f"this type can't be an operand of {self.tok.text!r}", start)
736
+ if self.accept(">"):
737
+ return Binary(">", left, self.tff_atomic_type())
738
+ if in_parens and self.at("*"):
739
+ args = [left]
740
+ while self.accept("*"):
741
+ args.append(self.tff_atomic_type())
742
+ return NAry("*", tuple(args))
743
+ if isinstance(left, NAry):
744
+ raise self.error("a product type must be followed by '>'", start)
745
+ return left
746
+
747
+ def tff_type_primary(self) -> Node:
748
+ tok = self.tok
749
+ if self.accept("("):
750
+ inner = self.tff_type(in_parens=True)
751
+ self.expect(")")
752
+ return inner
753
+ if tok.text == "[":
754
+ self.advance()
755
+ items = [self.tff_type()]
756
+ while self.accept(","):
757
+ items.append(self.tff_type())
758
+ self.expect("]")
759
+ return Tuple(tuple(items))
760
+ if tok.kind == "upper":
761
+ self.advance()
762
+ return Variable(tok.text, self.use(tok.text))
763
+ if tok.kind == "defined":
764
+ self.advance()
765
+ return Function(tok.text)
766
+ if tok.kind in _WORD_KINDS:
767
+ self.advance()
768
+ name = self.word_text(tok)
769
+ if self.accept("("):
770
+ args = [self.tff_atomic_type()]
771
+ while self.accept(","):
772
+ args.append(self.tff_atomic_type())
773
+ self.expect(")")
774
+ return Function(name, tuple(args))
775
+ return Function(name)
776
+ raise self.error(f"expected a type, found {self.describe()}")
777
+
778
+ def tff_atomic_type(self) -> Node:
779
+ start = self.tok
780
+ node = self.tff_type_primary()
781
+ if not isinstance(node, (Variable, Function, Tuple)):
782
+ raise self.error("expected an atomic type", start)
783
+ return node
784
+
785
+ def thf_type(self) -> Node:
786
+ left = self.thf_unitary()
787
+ if self.tok.text in (">", "*", "+", "@"):
788
+ return self.thf_type_tail(left)
789
+ return left
790
+
791
+ def thf_type_tail(self, left: Node) -> Node:
792
+ op = self.tok.text
793
+ if op == ">":
794
+ operands = [left]
795
+ while self.accept(">"):
796
+ operands.append(self.thf_unitary())
797
+ result = operands[-1]
798
+ for operand in reversed(operands[:-1]):
799
+ result = Binary(">", operand, result)
800
+ return result
801
+ args = [left]
802
+ read = self.unit if op == "@" else None
803
+ while self.accept(op):
804
+ args.append(read("thf") if read else self.thf_unitary())
805
+ return NAry(op, tuple(args))
806
+
807
+ def thf_unitary(self) -> Node:
808
+ if self.tok.text in _QUANTIFIERS["thf"] and self.peek().text == "[":
809
+ return self.quantified("thf")
810
+ return self.primary("thf")
811
+
812
+ # --- annotations and non-logical data -----------------------------------------
813
+
814
+ def source(self) -> Node:
815
+ tok = self.tok
816
+ if tok.text == "[":
817
+ self.advance()
818
+ sources = [self.source()]
819
+ while self.accept(","):
820
+ sources.append(self.source())
821
+ self.expect("]")
822
+ return SourceList(tuple(sources))
823
+ if self.peek().text == "(":
824
+ if tok.text == "inference":
825
+ return self.derivation_source(Inference)
826
+ if tok.text == "introduced":
827
+ return self.derivation_source(Introduced)
828
+ if tok.text == "file":
829
+ self.i += 2
830
+ file = self.atomic_word()
831
+ name = self.name() if self.accept(",") else None
832
+ self.expect(")")
833
+ return FileSource(file, name)
834
+ return Name(self.name())
835
+
836
+ def derivation_source(self, node_type: type) -> Node:
837
+ self.i += 2
838
+ word = self.atomic_word()
839
+ self.expect(",")
840
+ info = self.general_list()
841
+ self.expect(",")
842
+ self.expect("[")
843
+ parents: list[Parent] = []
844
+ if not self.at("]"):
845
+ parents.append(self.parent())
846
+ while self.accept(","):
847
+ parents.append(self.parent())
848
+ self.expect("]")
849
+ self.expect(")")
850
+ return node_type(word, info, tuple(parents))
851
+
852
+ def parent(self) -> Parent:
853
+ source = self.source()
854
+ return Parent(source, self.general_term() if self.accept(":") else None)
855
+
856
+ def general_list(self) -> Tuple:
857
+ self.expect("[")
858
+ items: list[Node] = []
859
+ if not self.at("]"):
860
+ items.append(self.general_term())
861
+ while self.accept(","):
862
+ items.append(self.general_term())
863
+ self.expect("]")
864
+ return Tuple(tuple(items))
865
+
866
+ def general_term(self) -> Node:
867
+ if self.at("["):
868
+ return self.general_list()
869
+ data = self.general_data()
870
+ if self.accept(":"):
871
+ return Binary(":", data, self.general_term())
872
+ return data
873
+
874
+ def general_data(self) -> Node:
875
+ tok = self.tok
876
+ kind = tok.kind
877
+ if kind == "upper":
878
+ self.advance()
879
+ return Variable(tok.text, self.use(tok.text))
880
+ if kind in _NUMBER_KINDS:
881
+ self.advance()
882
+ return Number(tok.text)
883
+ if kind == "distinct":
884
+ self.advance()
885
+ return DistinctObject(tok.text)
886
+ if kind in _WORD_KINDS:
887
+ self.advance()
888
+ name = self.word_text(tok)
889
+ if self.accept("("):
890
+ args = [self.general_term()]
891
+ while self.accept(","):
892
+ args.append(self.general_term())
893
+ self.expect(")")
894
+ return Function(name, tuple(args))
895
+ return Function(name)
896
+ if tok.text in _FORMULA_DATA_RULES and self.peek().text == "(":
897
+ self.i += 2
898
+ formula = _FORMULA_DATA_RULES[tok.text](self)
899
+ self.expect(")")
900
+ return FormulaData(tok.text[1:], formula)
901
+ raise self.error(f"expected general data, found {self.describe()}")
902
+
903
+
904
+ _FORMULA_RULES = {
905
+ "thf": _Parser.thf_formula,
906
+ "tff": _Parser.tff_formula,
907
+ "tcf": _Parser.tcf_formula,
908
+ "fof": _Parser.fof_formula,
909
+ "cnf": _Parser.cnf_formula,
910
+ "tpi": _Parser.fof_formula,
911
+ }
912
+
913
+ _FORMULA_DATA_RULES = {
914
+ "$thf": _Parser.thf_formula,
915
+ "$tff": _Parser.tff_formula,
916
+ "$fof": _Parser.fof_formula,
917
+ "$cnf": _Parser.cnf_formula,
918
+ "$fot": lambda parser: parser.primary("fof"),
919
+ }
920
+
921
+
922
+ # ---------------------------------------------------------------------------------
923
+ # Entry points used by the package's public functions
924
+ # ---------------------------------------------------------------------------------
925
+
926
+
927
+ def parse(text: str, filename: Optional[str] = None) -> TPTPFile:
928
+ with _deep_stack():
929
+ parser = _Parser(text, filename)
930
+ try:
931
+ return parser.parse_file()
932
+ except RecursionError:
933
+ raise parser.error("formula is too deeply nested") from None
934
+
935
+
936
+ def parse_formula(text: str, language: str) -> Node:
937
+ with _deep_stack():
938
+ parser = _Parser(text)
939
+ parser.begin_formula()
940
+ try:
941
+ formula = _FORMULA_RULES[language](parser)
942
+ except RecursionError:
943
+ raise parser.error("formula is too deeply nested") from None
944
+ if parser.tok.kind != "eof":
945
+ raise parser.error(f"unexpected {parser.describe()} after the formula")
946
+ return formula