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,678 @@
|
|
|
1
|
+
"""AST node classes, :class:`ParseError` and the helpers shared by every parser backend."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass, field, fields
|
|
10
|
+
from fractions import Fraction
|
|
11
|
+
from typing import Optional, Union
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"And", "Annotations", "AnnotatedFormula", "Apply", "Arrow", "Assignment", "Binary",
|
|
15
|
+
"Box", "Choice", "Colon", "Definition", "Description", "Diamond", "Equals", "Exists",
|
|
16
|
+
"ForAll", "Iff", "Implies", "ImpliedBy", "Lambda", "Nand", "Nor", "Not", "NotEquals",
|
|
17
|
+
"Or", "Product", "Sequent", "Subtype", "Sum", "TypeExists", "TypeForAll", "Xor",
|
|
18
|
+
"Comment", "ConnectiveTerm", "DistinctObject", "FileSource", "FormulaData", "Function", "Header", "Include", "Index",
|
|
19
|
+
"Inference", "Introduced", "Let", "LongConnective", "ModalAtom", "NAry", "Name",
|
|
20
|
+
"Node", "Number", "ParseError", "Parent", "Quantified", "SourceList", "TPTPFile",
|
|
21
|
+
"Tuple", "TypedVariable", "Typing", "Unary", "Variable",
|
|
22
|
+
"unquote", "walk",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
_NONASSOC = frozenset({"<=>", "=>", "<=", "<~>", "~|", "~&"})
|
|
26
|
+
_TH1_TERMS = frozenset({"!!", "??", "@@+", "@@-", "@="})
|
|
27
|
+
|
|
28
|
+
#: Python frames allowed while parsing or printing. Deeply nested terms do occur in
|
|
29
|
+
#: real problems, and the default limit of 1000 is only a few hundred levels of them.
|
|
30
|
+
_RECURSION_LIMIT = 100_000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@contextmanager
|
|
34
|
+
def _deep_stack() -> Iterator[None]:
|
|
35
|
+
# The limit is interpreter-wide, so this isn't safe alongside other threads that
|
|
36
|
+
# depend on hitting it, but it is restored as soon as the call finishes.
|
|
37
|
+
previous = sys.getrecursionlimit()
|
|
38
|
+
sys.setrecursionlimit(max(previous, _RECURSION_LIMIT))
|
|
39
|
+
try:
|
|
40
|
+
yield
|
|
41
|
+
finally:
|
|
42
|
+
sys.setrecursionlimit(previous)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ParseError(ValueError):
|
|
46
|
+
"""Invalid TPTP input. ``line`` and ``column`` are 1-based."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, message: str, *, line: int = 0, column: int = 0,
|
|
49
|
+
filename: Optional[str] = None, source_line: Optional[str] = None):
|
|
50
|
+
self.message = message
|
|
51
|
+
self.line = line
|
|
52
|
+
self.column = column
|
|
53
|
+
self.filename = filename
|
|
54
|
+
self.source_line = source_line
|
|
55
|
+
where = f"{filename or '<string>'}:{line}:{column}: " if line else ""
|
|
56
|
+
text = where + message
|
|
57
|
+
if source_line is not None:
|
|
58
|
+
text += f"\n {source_line}\n {' ' * (column - 1)}^"
|
|
59
|
+
super().__init__(text)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------------------------
|
|
63
|
+
# AST
|
|
64
|
+
# ---------------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Node:
|
|
68
|
+
"""Base class of all AST nodes. ``str(node)`` gives valid TPTP."""
|
|
69
|
+
|
|
70
|
+
__slots__ = ()
|
|
71
|
+
|
|
72
|
+
def __str__(self) -> str:
|
|
73
|
+
with _deep_stack():
|
|
74
|
+
return self._tptp()
|
|
75
|
+
|
|
76
|
+
def _tptp(self) -> str:
|
|
77
|
+
raise NotImplementedError
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _specialise(cls: type, base: type, table: dict, key: str, args: tuple, kwargs: dict) -> Node:
|
|
81
|
+
"""Allocate the operator subclass for ``base(op, ...)``, so that ``NAry('|', xs)``
|
|
82
|
+
and ``Or.of(*xs)`` are the same value. Subclasses and unknown operators stay as is."""
|
|
83
|
+
if cls is base:
|
|
84
|
+
cls = table.get(args[0] if args else kwargs.get(key), base)
|
|
85
|
+
return object.__new__(cls)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class Variable(Node):
|
|
90
|
+
name: str
|
|
91
|
+
|
|
92
|
+
def _tptp(self) -> str:
|
|
93
|
+
return self.name
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True, slots=True)
|
|
97
|
+
class Function(Node):
|
|
98
|
+
"""A function or predicate application; a constant if ``args`` is empty."""
|
|
99
|
+
|
|
100
|
+
name: str
|
|
101
|
+
args: tuple[Node, ...] = ()
|
|
102
|
+
|
|
103
|
+
def _tptp(self) -> str:
|
|
104
|
+
if not self.args:
|
|
105
|
+
return self.name
|
|
106
|
+
return f"{self.name}({_commas(self.args)})"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True, slots=True)
|
|
110
|
+
class Number(Node):
|
|
111
|
+
"""A numeric literal, compared by its source text (``1.0`` differs from ``1.00``)."""
|
|
112
|
+
|
|
113
|
+
text: str
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def kind(self) -> str:
|
|
117
|
+
"""``'integer'``, ``'rational'`` or ``'real'``."""
|
|
118
|
+
if "/" in self.text:
|
|
119
|
+
return "rational"
|
|
120
|
+
return "integer" if self.text.lstrip("+-").isdigit() else "real"
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def value(self) -> Union[int, Fraction, float]:
|
|
124
|
+
return {"integer": int, "rational": Fraction, "real": float}[self.kind](self.text)
|
|
125
|
+
|
|
126
|
+
def _tptp(self) -> str:
|
|
127
|
+
return self.text
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True, slots=True)
|
|
131
|
+
class DistinctObject(Node):
|
|
132
|
+
"""A double-quoted distinct object; ``text`` includes the quotes."""
|
|
133
|
+
|
|
134
|
+
text: str
|
|
135
|
+
|
|
136
|
+
def _tptp(self) -> str:
|
|
137
|
+
return self.text
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True, slots=True)
|
|
141
|
+
class Tuple(Node):
|
|
142
|
+
"""``[a, b, c]``: a THF/TXF tuple, tuple type, or general list."""
|
|
143
|
+
|
|
144
|
+
items: tuple[Node, ...] = ()
|
|
145
|
+
|
|
146
|
+
def _tptp(self) -> str:
|
|
147
|
+
return f"[{_commas(self.items)}]"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(frozen=True, slots=True)
|
|
151
|
+
class Unary(Node):
|
|
152
|
+
"""``~ a``, or a short non-classical connective: ``[.]``, ``<.>``, ``{.}``, ``(.)``."""
|
|
153
|
+
|
|
154
|
+
op: str
|
|
155
|
+
arg: Node
|
|
156
|
+
|
|
157
|
+
def __new__(cls, *args, **kwargs):
|
|
158
|
+
return _specialise(cls, Unary, _UNARY_OPS, "op", args, kwargs)
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def of(cls, arg: Node):
|
|
162
|
+
"""Build the node for this operator class, e.g. ``Not.of(a)``."""
|
|
163
|
+
return cls(cls.OP, arg)
|
|
164
|
+
|
|
165
|
+
def _tptp(self) -> str:
|
|
166
|
+
arg = self.arg
|
|
167
|
+
text = arg._tptp()
|
|
168
|
+
return f"{self.op} {text if isinstance(arg, (*_ATOMIC, Unary)) else f'({text})'}"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass(frozen=True, slots=True)
|
|
172
|
+
class Binary(Node):
|
|
173
|
+
"""A non-chaining infix operator."""
|
|
174
|
+
|
|
175
|
+
op: str
|
|
176
|
+
left: Node
|
|
177
|
+
right: Node
|
|
178
|
+
|
|
179
|
+
def __new__(cls, *args, **kwargs):
|
|
180
|
+
return _specialise(cls, Binary, _BINARY_OPS, "op", args, kwargs)
|
|
181
|
+
|
|
182
|
+
@classmethod
|
|
183
|
+
def of(cls, left: Node, right: Node):
|
|
184
|
+
"""Build the node for this operator class, e.g. ``Implies.of(a, b)``."""
|
|
185
|
+
return cls(cls.OP, left, right)
|
|
186
|
+
|
|
187
|
+
def _tptp(self) -> str:
|
|
188
|
+
op = self.op
|
|
189
|
+
if op in _NONASSOC:
|
|
190
|
+
return f"{_operand(self.left)} {op} {_operand(self.right)}"
|
|
191
|
+
if op in ("=", "!="):
|
|
192
|
+
return f"{_tight(self.left)} {op} {_tight(self.right)}"
|
|
193
|
+
if op == ">":
|
|
194
|
+
right = self.right
|
|
195
|
+
rhs = right._tptp() if isinstance(right, Binary) and right.op == ">" else _tight(right)
|
|
196
|
+
return f"{_tight(self.left)} > {rhs}"
|
|
197
|
+
if op == "==":
|
|
198
|
+
return f"{_tight(self.left)} == {self.right._tptp()}"
|
|
199
|
+
if op == ":": # general_data:general_term
|
|
200
|
+
return f"{self.left._tptp()}:{self.right._tptp()}"
|
|
201
|
+
return f"{self.left._tptp()} {op} {self.right._tptp()}" # := --> <<
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass(frozen=True, slots=True)
|
|
205
|
+
class NAry(Node):
|
|
206
|
+
"""A flat chain: ``|``, ``&``, or THF ``@``, ``*``, ``+``."""
|
|
207
|
+
|
|
208
|
+
op: str
|
|
209
|
+
args: tuple[Node, ...]
|
|
210
|
+
|
|
211
|
+
def __new__(cls, *args, **kwargs):
|
|
212
|
+
return _specialise(cls, NAry, _NARY_OPS, "op", args, kwargs)
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def of(cls, *operands: Node):
|
|
216
|
+
"""Build the node for this operator class, e.g. ``Or.of(a, b)``."""
|
|
217
|
+
return cls(cls.OP, operands)
|
|
218
|
+
|
|
219
|
+
def _tptp(self) -> str:
|
|
220
|
+
render = _operand if self.op in ("|", "&") else _tight
|
|
221
|
+
return f" {self.op} ".join([render(arg) for arg in self.args])
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass(frozen=True, slots=True)
|
|
225
|
+
class TypedVariable(Node):
|
|
226
|
+
name: str
|
|
227
|
+
type: Node
|
|
228
|
+
|
|
229
|
+
def _tptp(self) -> str:
|
|
230
|
+
return f"{self.name}: {self.type._tptp()}"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass(frozen=True, slots=True)
|
|
234
|
+
class Quantified(Node):
|
|
235
|
+
"""``quantifier [variables] : body``. ``variables`` holds Variable or TypedVariable."""
|
|
236
|
+
|
|
237
|
+
quantifier: str
|
|
238
|
+
variables: tuple[Node, ...]
|
|
239
|
+
body: Node
|
|
240
|
+
|
|
241
|
+
def __new__(cls, *args, **kwargs):
|
|
242
|
+
return _specialise(cls, Quantified, _QUANTIFIERS_BY_SYMBOL, "quantifier", args, kwargs)
|
|
243
|
+
|
|
244
|
+
@classmethod
|
|
245
|
+
def of(cls, variables: tuple[Node, ...], body: Node):
|
|
246
|
+
"""Build the node for this quantifier class, e.g. ``ForAll.of((X,), body)``."""
|
|
247
|
+
return cls(cls.OP, tuple(variables), body)
|
|
248
|
+
|
|
249
|
+
def _tptp(self) -> str:
|
|
250
|
+
body = self.body
|
|
251
|
+
if isinstance(body, Quantified):
|
|
252
|
+
text = body._tptp()
|
|
253
|
+
else:
|
|
254
|
+
text = _operand(body)
|
|
255
|
+
return f"{self.quantifier} [{_commas(self.variables)}] : {text}"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# --- operator subclasses --------------------------------------------------------------
|
|
259
|
+
# Each is a Binary/NAry/Unary/Quantified whose operator symbol is fixed. They add no
|
|
260
|
+
# fields, so they print and compare like their base, and the parser returns them.
|
|
261
|
+
# ``OP`` is the TPTP symbol. Operators without a class here (``{.}``, ``(.)``, ``#``)
|
|
262
|
+
# stay plain Unary/Quantified nodes.
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class Not(Unary): __slots__ = (); OP = "~"
|
|
266
|
+
class Box(Unary): __slots__ = (); OP = "[.]"
|
|
267
|
+
class Diamond(Unary): __slots__ = (); OP = "<.>"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class Or(NAry): __slots__ = (); OP = "|"
|
|
271
|
+
class And(NAry): __slots__ = (); OP = "&"
|
|
272
|
+
class Apply(NAry): __slots__ = (); OP = "@" # THF application
|
|
273
|
+
class Product(NAry): __slots__ = (); OP = "*" # THF product type
|
|
274
|
+
class Sum(NAry): __slots__ = (); OP = "+" # THF union type
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class Implies(Binary): __slots__ = (); OP = "=>"
|
|
278
|
+
class ImpliedBy(Binary): __slots__ = (); OP = "<="
|
|
279
|
+
class Iff(Binary): __slots__ = (); OP = "<=>"
|
|
280
|
+
class Xor(Binary): __slots__ = (); OP = "<~>"
|
|
281
|
+
class Nor(Binary): __slots__ = (); OP = "~|"
|
|
282
|
+
class Nand(Binary): __slots__ = (); OP = "~&"
|
|
283
|
+
class Equals(Binary): __slots__ = (); OP = "="
|
|
284
|
+
class NotEquals(Binary): __slots__ = (); OP = "!="
|
|
285
|
+
class Arrow(Binary): __slots__ = (); OP = ">" # mapping type, right-associative
|
|
286
|
+
class Definition(Binary): __slots__ = (); OP = "=="
|
|
287
|
+
class Assignment(Binary): __slots__ = (); OP = ":="
|
|
288
|
+
class Sequent(Binary): __slots__ = (); OP = "-->"
|
|
289
|
+
class Subtype(Binary): __slots__ = (); OP = "<<"
|
|
290
|
+
class Colon(Binary): __slots__ = (); OP = ":" # key:value in general data
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class ForAll(Quantified): __slots__ = (); OP = "!"
|
|
294
|
+
class Exists(Quantified): __slots__ = (); OP = "?"
|
|
295
|
+
class Lambda(Quantified): __slots__ = (); OP = "^"
|
|
296
|
+
class Choice(Quantified): __slots__ = (); OP = "@+"
|
|
297
|
+
class Description(Quantified): __slots__ = (); OP = "@-"
|
|
298
|
+
class TypeForAll(Quantified): __slots__ = (); OP = "!>"
|
|
299
|
+
class TypeExists(Quantified): __slots__ = (); OP = "?*"
|
|
300
|
+
|
|
301
|
+
_UNARY_OPS = {c.OP: c for c in (Not, Box, Diamond)}
|
|
302
|
+
_NARY_OPS = {c.OP: c for c in (Or, And, Apply, Product, Sum)}
|
|
303
|
+
_BINARY_OPS = {c.OP: c for c in (
|
|
304
|
+
Implies, ImpliedBy, Iff, Xor, Nor, Nand, Equals, NotEquals, Arrow, Definition,
|
|
305
|
+
Assignment, Sequent, Subtype, Colon)}
|
|
306
|
+
_QUANTIFIERS_BY_SYMBOL = {c.OP: c for c in (
|
|
307
|
+
ForAll, Exists, Lambda, Choice, Description, TypeForAll, TypeExists)}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@dataclass(frozen=True, slots=True)
|
|
311
|
+
class Typing(Node):
|
|
312
|
+
"""A type declaration, ``atom : type``."""
|
|
313
|
+
|
|
314
|
+
atom: str
|
|
315
|
+
type: Node
|
|
316
|
+
|
|
317
|
+
def _tptp(self) -> str:
|
|
318
|
+
return f"{self.atom}: {self.type._tptp()}"
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@dataclass(frozen=True, slots=True)
|
|
322
|
+
class ConnectiveTerm(Node):
|
|
323
|
+
"""THF connective used as a term, as in ``(&)``, or a TH1 constant such as ``!!``."""
|
|
324
|
+
|
|
325
|
+
op: str
|
|
326
|
+
|
|
327
|
+
def _tptp(self) -> str:
|
|
328
|
+
return self.op if self.op in _TH1_TERMS else f"({self.op})"
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
@dataclass(frozen=True, slots=True)
|
|
332
|
+
class Index(Node):
|
|
333
|
+
"""``#term``, a parameter of a long connective."""
|
|
334
|
+
|
|
335
|
+
term: Node
|
|
336
|
+
|
|
337
|
+
def _tptp(self) -> str:
|
|
338
|
+
return f"#{_tight(self.term)}"
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
@dataclass(frozen=True, slots=True)
|
|
342
|
+
class LongConnective(Node):
|
|
343
|
+
"""``{$box}`` or ``{$box(#a, $key == value)}``."""
|
|
344
|
+
|
|
345
|
+
name: str
|
|
346
|
+
params: tuple[Node, ...] = ()
|
|
347
|
+
|
|
348
|
+
def _tptp(self) -> str:
|
|
349
|
+
return f"{{{self.name}({_commas(self.params)})}}" if self.params else f"{{{self.name}}}"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@dataclass(frozen=True, slots=True)
|
|
353
|
+
class ModalAtom(Node):
|
|
354
|
+
"""TXF connective application, ``{$box} @ (a, b)``."""
|
|
355
|
+
|
|
356
|
+
connective: LongConnective
|
|
357
|
+
args: tuple[Node, ...]
|
|
358
|
+
|
|
359
|
+
def _tptp(self) -> str:
|
|
360
|
+
return f"{self.connective._tptp()} @ ({_commas(self.args)})"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
@dataclass(frozen=True, slots=True)
|
|
364
|
+
class Let(Node):
|
|
365
|
+
"""``$let(types, definitions, body)``. Definitions are ``:=`` Binary nodes."""
|
|
366
|
+
|
|
367
|
+
types: tuple[Typing, ...]
|
|
368
|
+
definitions: tuple[Binary, ...]
|
|
369
|
+
body: Node
|
|
370
|
+
|
|
371
|
+
def _tptp(self) -> str:
|
|
372
|
+
return f"$let([{_commas(self.types)}],[{_commas(self.definitions)}],{self.body._tptp()})"
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@dataclass(frozen=True, slots=True)
|
|
376
|
+
class FormulaData(Node):
|
|
377
|
+
"""Formula quoted in non-logical data: ``$fof(...)``, ``$fot(...)``, etc."""
|
|
378
|
+
|
|
379
|
+
language: str # thf, tff, fof, cnf or fot
|
|
380
|
+
formula: Node
|
|
381
|
+
|
|
382
|
+
def _tptp(self) -> str:
|
|
383
|
+
return f"${self.language}({self.formula._tptp()})"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@dataclass(frozen=True, slots=True)
|
|
387
|
+
class Name(Node):
|
|
388
|
+
"""A source that refers to another annotated formula by name."""
|
|
389
|
+
|
|
390
|
+
name: str
|
|
391
|
+
|
|
392
|
+
def _tptp(self) -> str:
|
|
393
|
+
return self.name
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@dataclass(frozen=True, slots=True)
|
|
397
|
+
class Parent(Node):
|
|
398
|
+
"""An entry in the parents of an inference: ``source`` or ``source:details``."""
|
|
399
|
+
|
|
400
|
+
source: Node
|
|
401
|
+
details: Optional[Node] = None
|
|
402
|
+
|
|
403
|
+
def _tptp(self) -> str:
|
|
404
|
+
if self.details is None:
|
|
405
|
+
return self.source._tptp()
|
|
406
|
+
return f"{self.source._tptp()}:{self.details._tptp()}"
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@dataclass(frozen=True, slots=True)
|
|
410
|
+
class Inference(Node):
|
|
411
|
+
"""``inference(rule, info, parents)``. ``info`` is a general list (Tuple)."""
|
|
412
|
+
|
|
413
|
+
rule: str
|
|
414
|
+
info: Tuple
|
|
415
|
+
parents: tuple[Parent, ...]
|
|
416
|
+
|
|
417
|
+
def _tptp(self) -> str:
|
|
418
|
+
return f"inference({self.rule},{self.info._tptp()},[{_commas(self.parents)}])"
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
@dataclass(frozen=True, slots=True)
|
|
422
|
+
class Introduced(Node):
|
|
423
|
+
"""``introduced(kind, info, parents)``."""
|
|
424
|
+
|
|
425
|
+
kind: str
|
|
426
|
+
info: Tuple
|
|
427
|
+
parents: tuple[Parent, ...]
|
|
428
|
+
|
|
429
|
+
def _tptp(self) -> str:
|
|
430
|
+
return f"introduced({self.kind},{self.info._tptp()},[{_commas(self.parents)}])"
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
@dataclass(frozen=True, slots=True)
|
|
434
|
+
class FileSource(Node):
|
|
435
|
+
"""``file(file_name)`` or ``file(file_name, name)``."""
|
|
436
|
+
|
|
437
|
+
file: str
|
|
438
|
+
name: Optional[str] = None
|
|
439
|
+
|
|
440
|
+
def _tptp(self) -> str:
|
|
441
|
+
return f"file({self.file},{self.name})" if self.name else f"file({self.file})"
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
@dataclass(frozen=True, slots=True)
|
|
445
|
+
class SourceList(Node):
|
|
446
|
+
"""Alternative sources: ``[source, source]``."""
|
|
447
|
+
|
|
448
|
+
sources: tuple[Node, ...]
|
|
449
|
+
|
|
450
|
+
def _tptp(self) -> str:
|
|
451
|
+
return f"[{_commas(self.sources)}]"
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@dataclass(frozen=True, slots=True)
|
|
455
|
+
class Annotations(Node):
|
|
456
|
+
source: Node
|
|
457
|
+
info: Optional[Tuple] = None
|
|
458
|
+
|
|
459
|
+
def _tptp(self) -> str:
|
|
460
|
+
if self.info is None:
|
|
461
|
+
return self.source._tptp()
|
|
462
|
+
return f"{self.source._tptp()},{self.info._tptp()}"
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
@dataclass(frozen=True, slots=True)
|
|
466
|
+
class AnnotatedFormula(Node):
|
|
467
|
+
language: str
|
|
468
|
+
name: str
|
|
469
|
+
role: str
|
|
470
|
+
formula: Node
|
|
471
|
+
annotations: Optional[Annotations] = None
|
|
472
|
+
subrole: Optional[Node] = None # the term in role-term
|
|
473
|
+
line: int = field(default=0, compare=False, repr=False)
|
|
474
|
+
|
|
475
|
+
def _tptp(self) -> str:
|
|
476
|
+
role = self.role if self.subrole is None else f"{self.role}-{self.subrole._tptp()}"
|
|
477
|
+
tail = "" if self.annotations is None else f",{self.annotations._tptp()}"
|
|
478
|
+
return f"{self.language}({self.name},{role},{self.formula._tptp()}{tail})."
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@dataclass(frozen=True, slots=True)
|
|
482
|
+
class Include(Node):
|
|
483
|
+
"""An include directive. ``selection`` is ``None``, ``'*'``, or a tuple of names."""
|
|
484
|
+
|
|
485
|
+
file: str
|
|
486
|
+
selection: Union[None, str, tuple[str, ...]] = None
|
|
487
|
+
space: Optional[str] = None
|
|
488
|
+
line: int = field(default=0, compare=False, repr=False)
|
|
489
|
+
|
|
490
|
+
@property
|
|
491
|
+
def path(self) -> str:
|
|
492
|
+
"""The file name without quotes."""
|
|
493
|
+
return unquote(self.file)
|
|
494
|
+
|
|
495
|
+
def _tptp(self) -> str:
|
|
496
|
+
parts = [self.file]
|
|
497
|
+
if self.selection == "*":
|
|
498
|
+
parts.append("*")
|
|
499
|
+
elif self.selection is not None:
|
|
500
|
+
parts.append(f"[{','.join(self.selection)}]")
|
|
501
|
+
if self.space is not None:
|
|
502
|
+
parts.append(self.space)
|
|
503
|
+
return f"include({','.join(parts)})."
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
@dataclass(frozen=True, slots=True)
|
|
507
|
+
class Comment:
|
|
508
|
+
"""A comment, with its delimiters. ``%$`` and ``/*$`` pragmas are comments too."""
|
|
509
|
+
|
|
510
|
+
text: str
|
|
511
|
+
line: int
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
_HEADER_FIELD_RE = re.compile(r"%\s(\S[^:\n]*?)\s*:\s?(.*)")
|
|
515
|
+
_HEADER_CONTINUATION_RE = re.compile(r"%\s{2,}(\S.*)")
|
|
516
|
+
_HEADER_RULE_RE = re.compile(r"%-{5,}")
|
|
517
|
+
_RATING_RE = re.compile(r"(\d+(?:\.\d+)?|\?)(?:\s+v(\d[\w.]*))?")
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@dataclass(frozen=True, slots=True)
|
|
521
|
+
class Header:
|
|
522
|
+
"""The standard comment header of a TPTP problem (``% Key : value`` lines).
|
|
523
|
+
|
|
524
|
+
``entries`` holds every field in file order as ``(key, value)``; a value that
|
|
525
|
+
continues over several lines has them joined by single spaces. A key that occurs
|
|
526
|
+
twice (``Refs`` for example) is listed twice. Use :meth:`get` for lookup.
|
|
527
|
+
"""
|
|
528
|
+
|
|
529
|
+
entries: tuple[tuple[str, str], ...] = ()
|
|
530
|
+
|
|
531
|
+
def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
|
|
532
|
+
"""The first value for ``key`` (case-insensitive), or ``default``."""
|
|
533
|
+
key = key.lower()
|
|
534
|
+
return next((v for k, v in self.entries if k.lower() == key), default)
|
|
535
|
+
|
|
536
|
+
@property
|
|
537
|
+
def problem(self) -> Optional[str]:
|
|
538
|
+
"""The problem name from the ``File`` field, e.g. ``'SET001-1'``."""
|
|
539
|
+
file = self.get("File")
|
|
540
|
+
return file.split(":")[0].strip() or None if file else None
|
|
541
|
+
|
|
542
|
+
@property
|
|
543
|
+
def status(self) -> Optional[str]:
|
|
544
|
+
"""The expected SZS status: ``'Theorem'``, ``'Unsatisfiable'``,
|
|
545
|
+
``'Satisfiable'``, ``'CounterSatisfiable'``, ``'Open'``, ... or ``None``."""
|
|
546
|
+
return self.get("Status") or None
|
|
547
|
+
|
|
548
|
+
@property
|
|
549
|
+
def spc(self) -> Optional[str]:
|
|
550
|
+
"""The problem class, e.g. ``'CNF_UNS_RFO_SEQ_NHN'``."""
|
|
551
|
+
return self.get("SPC") or None
|
|
552
|
+
|
|
553
|
+
@property
|
|
554
|
+
def ratings(self) -> tuple[tuple[float, Optional[str]], ...]:
|
|
555
|
+
"""Difficulty history as ``(rating, TPTP version)``, newest first.
|
|
556
|
+
|
|
557
|
+
0.0 means every ATP system solves it and 1.0 that none does. Entries whose
|
|
558
|
+
rating is unknown (``?``) are left out.
|
|
559
|
+
"""
|
|
560
|
+
text = self.get("Rating") or ""
|
|
561
|
+
return tuple((float(m[1]), m[2] or None) for m in _RATING_RE.finditer(text)
|
|
562
|
+
if m[1] != "?")
|
|
563
|
+
|
|
564
|
+
@property
|
|
565
|
+
def rating(self) -> Optional[float]:
|
|
566
|
+
"""The most recent difficulty rating in [0, 1], or ``None`` if unrated."""
|
|
567
|
+
ratings = self.ratings
|
|
568
|
+
return ratings[0][0] if ratings else None
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _parse_header(comments: tuple[Comment, ...]) -> Optional[Header]:
|
|
572
|
+
# A problem's header sits between two ``%-----`` rules and has blank lines between its
|
|
573
|
+
# sections. Without the rules, it is the first run of consecutive ``%`` lines.
|
|
574
|
+
run: list[Comment] = []
|
|
575
|
+
ruled = False
|
|
576
|
+
for comment in comments:
|
|
577
|
+
if not comment.text.startswith("%"):
|
|
578
|
+
continue
|
|
579
|
+
is_rule = _HEADER_RULE_RE.fullmatch(comment.text.rstrip()) is not None
|
|
580
|
+
if not run:
|
|
581
|
+
ruled = is_rule
|
|
582
|
+
elif ruled:
|
|
583
|
+
if is_rule:
|
|
584
|
+
break
|
|
585
|
+
elif comment.line != run[-1].line + 1:
|
|
586
|
+
break
|
|
587
|
+
run.append(comment)
|
|
588
|
+
entries: list[list[str]] = []
|
|
589
|
+
for comment in run:
|
|
590
|
+
text = comment.text.rstrip()
|
|
591
|
+
if (field_match := _HEADER_FIELD_RE.fullmatch(text)):
|
|
592
|
+
entries.append([field_match[1], field_match[2].strip()])
|
|
593
|
+
elif entries and (more := _HEADER_CONTINUATION_RE.fullmatch(text)):
|
|
594
|
+
entries[-1][1] = f"{entries[-1][1]} {more[1].strip()}".strip()
|
|
595
|
+
return Header(tuple((k, v) for k, v in entries)) if entries else None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
@dataclass(frozen=True, slots=True)
|
|
599
|
+
class TPTPFile(Node):
|
|
600
|
+
inputs: tuple[Union[AnnotatedFormula, Include], ...] = ()
|
|
601
|
+
comments: tuple[Comment, ...] = ()
|
|
602
|
+
filename: Optional[str] = field(default=None, compare=False)
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def formulae(self) -> tuple[AnnotatedFormula, ...]:
|
|
606
|
+
return tuple(i for i in self.inputs if isinstance(i, AnnotatedFormula))
|
|
607
|
+
|
|
608
|
+
@property
|
|
609
|
+
def includes(self) -> tuple[Include, ...]:
|
|
610
|
+
return tuple(i for i in self.inputs if isinstance(i, Include))
|
|
611
|
+
|
|
612
|
+
@property
|
|
613
|
+
def header(self) -> Optional[Header]:
|
|
614
|
+
"""The standard problem header parsed from the leading ``%`` comments, if any."""
|
|
615
|
+
return _parse_header(self.comments)
|
|
616
|
+
|
|
617
|
+
@property
|
|
618
|
+
def dialect(self) -> list[str]:
|
|
619
|
+
"""The languages used by the formulae, once each, in order of first appearance.
|
|
620
|
+
|
|
621
|
+
Unexpanded includes aren't read, so they don't contribute.
|
|
622
|
+
"""
|
|
623
|
+
return list(dict.fromkeys(f.language for f in self.formulae))
|
|
624
|
+
|
|
625
|
+
def _tptp(self) -> str:
|
|
626
|
+
return "\n".join([i._tptp() for i in self.inputs])
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
_ATOMIC = (Variable, Function, Number, DistinctObject, Tuple, ConnectiveTerm,
|
|
630
|
+
LongConnective, ModalAtom, Let, FormulaData)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _commas(nodes: tuple[Node, ...]) -> str:
|
|
634
|
+
return ",".join([n._tptp() for n in nodes])
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def _tight(node: Node) -> str:
|
|
638
|
+
"""Render an operand of an operator that takes only atomic operands."""
|
|
639
|
+
text = node._tptp()
|
|
640
|
+
return text if isinstance(node, _ATOMIC) else f"({text})"
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _operand(node: Node) -> str:
|
|
644
|
+
"""Render an operand of a logical connective, or a quantifier body."""
|
|
645
|
+
text = node._tptp()
|
|
646
|
+
# Equations stay bare because CNF forbids parentheses around literals.
|
|
647
|
+
bare = isinstance(node, (*_ATOMIC, Unary)) or (isinstance(node, Binary) and node.op in ("=", "!="))
|
|
648
|
+
return text if bare else f"({text})"
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def unquote(word: str) -> str:
|
|
652
|
+
"""Return the text of a single-quoted word; other words are returned unchanged."""
|
|
653
|
+
if len(word) >= 2 and word[0] == "'" and word[-1] == "'":
|
|
654
|
+
return re.sub(r"\\(.)", r"\1", word[1:-1])
|
|
655
|
+
return word
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def walk(node: Node) -> Iterator[Node]:
|
|
659
|
+
"""Yield ``node`` and all nodes beneath it, in depth-first pre-order."""
|
|
660
|
+
stack: list[Node] = [node]
|
|
661
|
+
while stack:
|
|
662
|
+
current = stack.pop()
|
|
663
|
+
yield current
|
|
664
|
+
children: list[Node] = []
|
|
665
|
+
for f in fields(current): # type: ignore[arg-type]
|
|
666
|
+
value = getattr(current, f.name)
|
|
667
|
+
if isinstance(value, Node):
|
|
668
|
+
children.append(value)
|
|
669
|
+
elif isinstance(value, tuple):
|
|
670
|
+
children.extend(v for v in value if isinstance(v, Node))
|
|
671
|
+
stack.extend(reversed(children))
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def _error_at(message: str, text: str, line: int, column: int, filename: Optional[str]) -> ParseError:
|
|
676
|
+
lines = text.split("\n")
|
|
677
|
+
source_line = lines[line - 1].rstrip("\r") if 0 < line <= len(lines) else None
|
|
678
|
+
return ParseError(message, line=line, column=column, filename=filename, source_line=source_line)
|
|
File without changes
|