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,173 @@
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', index=1),))
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
+ * ``Variable.index`` numbers the distinct variables of a formula 1, 2, 3 ... in order of
31
+ first appearance, so in ``f(X) | f(Y) | g(X, f(Y))`` every ``X`` has index 1 and every
32
+ ``Y`` index 2. A quantifier counts as the appearance of the variables it binds, and each
33
+ binding is its own variable: the two ``X`` of ``(! [X] : p(X)) & (! [X] : q(X))`` get
34
+ indexes 1 and 2. Numbering starts again for each formula; a variable outside a formula (in
35
+ an annotation, or built by hand) has index 0.
36
+ * ``TPTPFile.symbols`` is the symbol table: a tuple of :class:`Symbol` ``(name, arity)``,
37
+ one for each distinct function, constant or predicate the formulae use, in order of first
38
+ appearance, so ``f/1`` and ``f/2`` are different symbols. Variables, equality, numbers,
39
+ distinct objects, ``$`` and ``$$`` symbols, type declarations and annotations are not
40
+ symbols. Each ``AnnotatedFormula`` has its own ``symbols`` too, and the file's table follows
41
+ ``expand_includes``.
42
+ * Quotes are removed from a word when the result is still a valid lower-case word,
43
+ so ``'cat'`` and ``cat`` compare equal, as the specification requires. Any other
44
+ quoted word keeps its quotes; use :func:`unquote` to get the raw text.
45
+
46
+ This is a syntax parser: it does not check sorts, arities, roles, or that variables
47
+ are bound. Requires Python 3.11+.
48
+
49
+ Problems can be fetched from a TPTP library, given as a folder, a tarball or the TPTP
50
+ website, with :func:`fetch_problem`; see :mod:`thousandproblems.library`.
51
+
52
+ Parsing runs in a C extension when one is available, and in pure Python otherwise;
53
+ both build identical trees and raise identical errors. ``thousandproblems.BACKEND`` is
54
+ ``"c"`` or ``"python"``. Set the environment variable ``THOUSANDPROBLEMS_PURE_PYTHON=1``
55
+ before importing to force the pure-Python parser.
56
+
57
+ The standard comment header of a problem file is available as ``TPTPFile.header``,
58
+ with the expected SZS ``status`` and the difficulty ``rating``::
59
+
60
+ >>> header = parse_file("SET001-1.p").header # doctest: +SKIP
61
+ >>> header.status, header.rating # doctest: +SKIP
62
+ ('Unsatisfiable', 0.0)
63
+
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ import os
69
+ from pathlib import Path
70
+ from typing import Optional, Union
71
+
72
+ from . import _pyparser
73
+ from .nodes import * # noqa: F403
74
+ from .nodes import _error_at, _symbol_table, __all__ as _node_names
75
+
76
+ _LIBRARY_NAMES = ("DirectoryLibrary", "Library", "LibraryError", "OnlineLibrary", "ProblemNotFound",
77
+ "RateLimited", "TarballLibrary", "fetch_problem", "open_library")
78
+
79
+ __all__ = [*_node_names, "BACKEND", "parse", "parse_file", "parse_formula", *_LIBRARY_NAMES]
80
+
81
+ try:
82
+ from importlib.metadata import version as _version
83
+ __version__ = _version("thousandproblems")
84
+ except Exception: # not installed, e.g. running from a source checkout
85
+ __version__ = "0+unknown"
86
+
87
+ _native = None
88
+ if not os.environ.get("THOUSANDPROBLEMS_PURE_PYTHON"):
89
+ try:
90
+ from . import _cparser as _native
91
+ except ImportError:
92
+ _native = None
93
+
94
+ #: ``"c"`` if the compiled parser is in use, otherwise ``"python"``.
95
+ BACKEND = "python" if _native is None else "c"
96
+
97
+
98
+ def parse(text: str, filename: Optional[str] = None) -> TPTPFile:
99
+ """Parse the text of a TPTP file. Includes are kept as :class:`Include` nodes."""
100
+ if _native is not None:
101
+ result = _native.parse(text, filename)
102
+ if result is not NotImplemented:
103
+ return result
104
+ return _pyparser.parse(text, filename)
105
+
106
+
107
+ def parse_formula(text: str, language: str = "fof") -> Node:
108
+ """Parse one bare formula, without the ``fof(name,role,...).`` wrapper."""
109
+ if language not in _LANGUAGES:
110
+ raise ValueError(f"unknown TPTP language {language!r}")
111
+ if _native is not None:
112
+ result = _native.parse_formula(text, language)
113
+ if result is not NotImplemented:
114
+ return result
115
+ return _pyparser.parse_formula(text, language)
116
+
117
+
118
+ def __getattr__(name: str):
119
+ # The library code (tarfile, urllib) is only imported when it is used.
120
+ if name == "library" or name in _LIBRARY_NAMES:
121
+ import importlib
122
+ library = importlib.import_module(".library", __name__)
123
+ return library if name == "library" else getattr(library, name)
124
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
125
+
126
+
127
+ _LANGUAGES = frozenset({"thf", "tff", "tcf", "fof", "cnf", "tpi"})
128
+
129
+
130
+ def parse_file(path: Union[str, os.PathLike], *, expand_includes: bool = False,
131
+ tptp_root: Union[str, os.PathLike, None] = None) -> TPTPFile:
132
+ """Parse a TPTP file.
133
+
134
+ With ``expand_includes``, each include is replaced by the formulae it selects.
135
+ Include paths are tried relative to the including file, then relative to
136
+ ``tptp_root`` (default: the ``$TPTP`` environment variable). The returned
137
+ ``comments`` are those of the top-level file only.
138
+ """
139
+ path = Path(path)
140
+ root = tptp_root if tptp_root is not None else os.environ.get("TPTP")
141
+ return _load(path, Path(root) if root else None, expand_includes, ())
142
+
143
+
144
+ def _load(path: Path, root: Optional[Path], expand: bool, stack: tuple[Path, ...]) -> TPTPFile:
145
+ text = path.read_text(encoding="utf-8", errors="replace")
146
+ parsed = parse(text, str(path))
147
+ if not expand:
148
+ return parsed
149
+ here = path.resolve()
150
+ inputs: list[Union[AnnotatedFormula, Include]] = []
151
+ for item in parsed.inputs:
152
+ if isinstance(item, AnnotatedFormula):
153
+ inputs.append(item)
154
+ continue
155
+ candidates = [path.parent / item.path]
156
+ if root is not None:
157
+ candidates.append(root / item.path)
158
+ target = next((c for c in candidates if c.is_file()), None)
159
+ fail = lambda message: _error_at(message, text, item.line, 1, str(path)) # noqa: E731
160
+ if target is None:
161
+ tried = ", ".join(str(c) for c in candidates)
162
+ raise fail(f"included file {item.path!r} not found (tried {tried})")
163
+ if target.resolve() in (*stack, here):
164
+ raise fail(f"circular include of {item.path!r}")
165
+ formulae = _load(target, root, True, (*stack, here)).formulae
166
+ if isinstance(item.selection, tuple):
167
+ selected = [f for f in formulae if f.name in item.selection]
168
+ missing = set(item.selection) - {f.name for f in selected}
169
+ if missing:
170
+ raise fail(f"{item.path!r} has no formulae named {sorted(missing)}")
171
+ formulae = tuple(selected)
172
+ inputs.extend(formulae)
173
+ return TPTPFile(tuple(inputs), parsed.comments, parsed.filename, _symbol_table(i for i in inputs if isinstance(i, AnnotatedFormula)))
@@ -0,0 +1,7 @@
1
+ """``python -m thousandproblems``: see :mod:`thousandproblems.cli`."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
@@ -0,0 +1,6 @@
1
+ from typing import Optional
2
+
3
+ from .nodes import Node, TPTPFile
4
+
5
+ def parse(text: str, filename: Optional[str]) -> TPTPFile: ...
6
+ def parse_formula(text: str, language: str) -> Node: ...