thousandproblems 0.1.0__cp313-cp313-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.
- thousandproblems/__init__.py +161 -0
- thousandproblems/_cparser.cp313-win_amd64.pyd +0 -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 +12 -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,161 @@
|
|
|
1
|
+
"""Parser for the TPTP problem and solution syntax (grammar v9.3.1.x).
|
|
2
|
+
|
|
3
|
+
Handles every TPTP language -- ``thf``, ``tff``, ``tcf``, ``fof``, ``cnf`` and
|
|
4
|
+
``tpi`` -- including TF1/TH1 polymorphism, TXF/non-classical extensions, ``include``
|
|
5
|
+
directives, and annotations (sources, inference records, useful info).
|
|
6
|
+
|
|
7
|
+
>>> import thousandproblems as tptp
|
|
8
|
+
>>> problem = tptp.parse("fof(ax1, axiom, ! [X] : (p(X) => q(X))).")
|
|
9
|
+
>>> ax = problem.formulae[0]
|
|
10
|
+
>>> ax.language, ax.name, ax.role
|
|
11
|
+
('fof', 'ax1', 'axiom')
|
|
12
|
+
>>> ax.formula.quantifier, ax.formula.variables
|
|
13
|
+
('!', (Variable(name='X'),))
|
|
14
|
+
>>> print(ax)
|
|
15
|
+
fof(ax1,axiom,! [X] : (p(X) => q(X))).
|
|
16
|
+
|
|
17
|
+
Entry points are :func:`parse`, :func:`parse_file` and :func:`parse_formula`. Bad
|
|
18
|
+
input raises :class:`ParseError`, which carries the line and column. ``str(node)``
|
|
19
|
+
prints any node back as valid TPTP, and :func:`walk` iterates over a subtree.
|
|
20
|
+
|
|
21
|
+
The AST is the same for all languages:
|
|
22
|
+
|
|
23
|
+
* ``|``, ``&`` and THF ``@``, ``*``, ``+`` chains are flat :class:`NAry` nodes, as
|
|
24
|
+
they are lists in the grammar. Parentheses are not represented, so ``a | (b | c)``
|
|
25
|
+
is an ``NAry`` nested inside an ``NAry``.
|
|
26
|
+
* Other infix operators (``=>``, ``=``, ``>``, ``==``, ``:=``, ``-->`` ...) are
|
|
27
|
+
:class:`Binary`. ``>`` is right-associative.
|
|
28
|
+
* Constants are :class:`Function` with no arguments. Defined and system symbols keep
|
|
29
|
+
their prefix, as in ``Function('$true')``.
|
|
30
|
+
* Quotes are removed from a word when the result is still a valid lower-case word,
|
|
31
|
+
so ``'cat'`` and ``cat`` compare equal, as the specification requires. Any other
|
|
32
|
+
quoted word keeps its quotes; use :func:`unquote` to get the raw text.
|
|
33
|
+
|
|
34
|
+
This is a syntax parser: it does not check sorts, arities, roles, or that variables
|
|
35
|
+
are bound. Requires Python 3.11+.
|
|
36
|
+
|
|
37
|
+
Problems can be fetched from a TPTP library, given as a folder, a tarball or the TPTP
|
|
38
|
+
website, with :func:`fetch_problem`; see :mod:`thousandproblems.library`.
|
|
39
|
+
|
|
40
|
+
Parsing runs in a C extension when one is available, and in pure Python otherwise;
|
|
41
|
+
both build identical trees and raise identical errors. ``thousandproblems.BACKEND`` is
|
|
42
|
+
``"c"`` or ``"python"``. Set the environment variable ``THOUSANDPROBLEMS_PURE_PYTHON=1``
|
|
43
|
+
before importing to force the pure-Python parser.
|
|
44
|
+
|
|
45
|
+
The standard comment header of a problem file is available as ``TPTPFile.header``,
|
|
46
|
+
with the expected SZS ``status`` and the difficulty ``rating``::
|
|
47
|
+
|
|
48
|
+
>>> header = parse_file("SET001-1.p").header # doctest: +SKIP
|
|
49
|
+
>>> header.status, header.rating # doctest: +SKIP
|
|
50
|
+
('Unsatisfiable', 0.0)
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import os
|
|
57
|
+
from pathlib import Path
|
|
58
|
+
from typing import Optional, Union
|
|
59
|
+
|
|
60
|
+
from . import _pyparser
|
|
61
|
+
from .nodes import * # noqa: F403
|
|
62
|
+
from .nodes import _error_at, __all__ as _node_names
|
|
63
|
+
|
|
64
|
+
_LIBRARY_NAMES = ("DirectoryLibrary", "Library", "LibraryError", "OnlineLibrary", "ProblemNotFound",
|
|
65
|
+
"RateLimited", "TarballLibrary", "fetch_problem", "open_library")
|
|
66
|
+
|
|
67
|
+
__all__ = [*_node_names, "BACKEND", "parse", "parse_file", "parse_formula", *_LIBRARY_NAMES]
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
from importlib.metadata import version as _version
|
|
71
|
+
__version__ = _version("thousandproblems")
|
|
72
|
+
except Exception: # not installed, e.g. running from a source checkout
|
|
73
|
+
__version__ = "0+unknown"
|
|
74
|
+
|
|
75
|
+
_native = None
|
|
76
|
+
if not os.environ.get("THOUSANDPROBLEMS_PURE_PYTHON"):
|
|
77
|
+
try:
|
|
78
|
+
from . import _cparser as _native
|
|
79
|
+
except ImportError:
|
|
80
|
+
_native = None
|
|
81
|
+
|
|
82
|
+
#: ``"c"`` if the compiled parser is in use, otherwise ``"python"``.
|
|
83
|
+
BACKEND = "python" if _native is None else "c"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse(text: str, filename: Optional[str] = None) -> TPTPFile:
|
|
87
|
+
"""Parse the text of a TPTP file. Includes are kept as :class:`Include` nodes."""
|
|
88
|
+
if _native is not None:
|
|
89
|
+
result = _native.parse(text, filename)
|
|
90
|
+
if result is not NotImplemented:
|
|
91
|
+
return result
|
|
92
|
+
return _pyparser.parse(text, filename)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_formula(text: str, language: str = "fof") -> Node:
|
|
96
|
+
"""Parse one bare formula, without the ``fof(name,role,...).`` wrapper."""
|
|
97
|
+
if language not in _LANGUAGES:
|
|
98
|
+
raise ValueError(f"unknown TPTP language {language!r}")
|
|
99
|
+
if _native is not None:
|
|
100
|
+
result = _native.parse_formula(text, language)
|
|
101
|
+
if result is not NotImplemented:
|
|
102
|
+
return result
|
|
103
|
+
return _pyparser.parse_formula(text, language)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def __getattr__(name: str):
|
|
107
|
+
# The library code (tarfile, urllib) is only imported when it is used.
|
|
108
|
+
if name == "library" or name in _LIBRARY_NAMES:
|
|
109
|
+
import importlib
|
|
110
|
+
library = importlib.import_module(".library", __name__)
|
|
111
|
+
return library if name == "library" else getattr(library, name)
|
|
112
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
_LANGUAGES = frozenset({"thf", "tff", "tcf", "fof", "cnf", "tpi"})
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def parse_file(path: Union[str, os.PathLike], *, expand_includes: bool = False,
|
|
119
|
+
tptp_root: Union[str, os.PathLike, None] = None) -> TPTPFile:
|
|
120
|
+
"""Parse a TPTP file.
|
|
121
|
+
|
|
122
|
+
With ``expand_includes``, each include is replaced by the formulae it selects.
|
|
123
|
+
Include paths are tried relative to the including file, then relative to
|
|
124
|
+
``tptp_root`` (default: the ``$TPTP`` environment variable). The returned
|
|
125
|
+
``comments`` are those of the top-level file only.
|
|
126
|
+
"""
|
|
127
|
+
path = Path(path)
|
|
128
|
+
root = tptp_root if tptp_root is not None else os.environ.get("TPTP")
|
|
129
|
+
return _load(path, Path(root) if root else None, expand_includes, ())
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _load(path: Path, root: Optional[Path], expand: bool, stack: tuple[Path, ...]) -> TPTPFile:
|
|
133
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
134
|
+
parsed = parse(text, str(path))
|
|
135
|
+
if not expand:
|
|
136
|
+
return parsed
|
|
137
|
+
here = path.resolve()
|
|
138
|
+
inputs: list[Union[AnnotatedFormula, Include]] = []
|
|
139
|
+
for item in parsed.inputs:
|
|
140
|
+
if isinstance(item, AnnotatedFormula):
|
|
141
|
+
inputs.append(item)
|
|
142
|
+
continue
|
|
143
|
+
candidates = [path.parent / item.path]
|
|
144
|
+
if root is not None:
|
|
145
|
+
candidates.append(root / item.path)
|
|
146
|
+
target = next((c for c in candidates if c.is_file()), None)
|
|
147
|
+
fail = lambda message: _error_at(message, text, item.line, 1, str(path)) # noqa: E731
|
|
148
|
+
if target is None:
|
|
149
|
+
tried = ", ".join(str(c) for c in candidates)
|
|
150
|
+
raise fail(f"included file {item.path!r} not found (tried {tried})")
|
|
151
|
+
if target.resolve() in (*stack, here):
|
|
152
|
+
raise fail(f"circular include of {item.path!r}")
|
|
153
|
+
formulae = _load(target, root, True, (*stack, here)).formulae
|
|
154
|
+
if isinstance(item.selection, tuple):
|
|
155
|
+
selected = [f for f in formulae if f.name in item.selection]
|
|
156
|
+
missing = set(item.selection) - {f.name for f in selected}
|
|
157
|
+
if missing:
|
|
158
|
+
raise fail(f"{item.path!r} has no formulae named {sorted(missing)}")
|
|
159
|
+
formulae = tuple(selected)
|
|
160
|
+
inputs.extend(formulae)
|
|
161
|
+
return TPTPFile(tuple(inputs), parsed.comments, parsed.filename)
|
|
Binary file
|