opreof 0.1.0__tar.gz

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,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .ruff_cache/
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ build/
7
+ dist/
8
+ *.egg-info/
9
+ .venv/
10
+ venv/
11
+ .DS_Store
12
+ *.log
opreof-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cpyte
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
opreof-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.5
2
+ Name: opreof
3
+ Version: 0.1.0
4
+ Summary: Bit-exact machine-integer equivalence proving by rewriting, equality saturation, and exhaustive solving
5
+ Project-URL: Homepage, https://github.com/Cpyte/OProof
6
+ Project-URL: Repository, https://github.com/Cpyte/OProof
7
+ Project-URL: Source, https://gitea.5gnew.io.vn/Cpyte-Project/Oproof
8
+ Author: Cpyte
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: bit-exact,bitvector,e-graph,equivalence,machine-integer,rewriting,smt,theorem-prover,verification
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
21
+ Classifier: Topic :: Software Development :: Compilers
22
+ Classifier: Topic :: Software Development :: Quality Assurance
23
+ Classifier: Topic :: Software Development :: Testing
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+
27
+ # OProof
28
+
29
+ Bit-exact equivalence proving for machine integers. OProof decides whether two
30
+ computation blocks over `bool`, `int8`…`int64`, and `uint8`…`uint64` compute the
31
+ same outputs, using the arithmetic the target machine actually performs —
32
+ truncation, wraparound, sign extension, and defined shifts.
33
+
34
+ It is not a floating-point or real-arithmetic prover. `x + 1` overflowing
35
+ `int8` is a different function from unbounded `x + 1`, and OProof reports the
36
+ overflow rather than proving something convenient.
37
+
38
+ ## Install
39
+
40
+ ```sh
41
+ pip install opreof
42
+ ```
43
+
44
+ Pure Python, no dependencies, requires Python 3.11+.
45
+
46
+ ## Prove an equivalence
47
+
48
+ ```python
49
+ from opreof import Block, Assign, Var, int8, prove
50
+
51
+ a = Block("a", [Assign(Var("x", int8), Var("y", int8))])
52
+ b = Block("b", [Assign(Var("x", int8), Var("y", int8))])
53
+
54
+ r = prove(a, b, outputs={"x"})
55
+ print(r.status) # proven
56
+ ```
57
+
58
+ `status` is one of:
59
+
60
+ | status | meaning |
61
+ | --- | --- |
62
+ | `proven` | a derivation was found and every step checked |
63
+ | `not_proven` | the prover stopped without finding one |
64
+ | `rejected` | the question is ill-posed (e.g. `200` is not an `int8`) |
65
+
66
+ `not_proven` is not a refutation. Only `proven` is a positive answer, and the
67
+ kernel re-verifies each step of the derivation it returns.
68
+
69
+ ## What it understands
70
+
71
+ Rules live in plain Python files under `axioms/`, so the fact base is data you
72
+ can read, narrow, or replace:
73
+
74
+ Theories are files; axioms are the individual named rules inside them.
75
+ Curation selects **axiom names**, and an unknown name is an error rather than
76
+ a silently ignored typo:
77
+
78
+ ```python
79
+ from opreof import list_theories, theory_rules, list_axioms, with_axioms, prove
80
+
81
+ list_theories() # ['arithmetic', 'foundational', 'logic', 'pow2']
82
+ theory_rules("logic") # every rule from that file
83
+ list_axioms() # 109 names, e.g. 'add_assoc'
84
+
85
+ with with_axioms("add_self_is_shl1"): # only that fact is available
86
+ prove(a, b, outputs={"x"})
87
+
88
+ prove(a, b, outputs={"x"}, axioms=("add_assoc", "add_self_is_shl1")) # per call
89
+ ```
90
+
91
+ Facts proven during a session are generalized and promoted to new axioms,
92
+ persisted back to `axioms/`, so a proof you already paid for is reused.
93
+
94
+ A rule declared with `equational=True` (associativity, distributivity, De
95
+ Morgan) is deliberately kept out of directed normalization. A rewriter that
96
+ fired those would loop or pick arbitrary orientations. OProof hands them to the
97
+ e-graph instead.
98
+
99
+ ## Equality saturation
100
+
101
+ Directed rewriting answers "can `a` become `b`". Equality saturation builds an
102
+ e-graph, applies every rule in both directions until nothing new merges, then
103
+ extracts the cheapest representative:
104
+
105
+ The e-graph entry points take kernel expressions (`Op`/`Var`), plus the
106
+ input-type map, rather than `Block`s:
107
+
108
+ ```python
109
+ from opreof import Var, Op, int8, egraph_normalize, egraph_prove
110
+
111
+ I = {"x": int8, "y": int8, "z": int8}
112
+ x, y, z = Var("x", int8), Var("y", int8), Var("z", int8)
113
+
114
+ # associativity is equational, so only saturation can use it
115
+ left = Op("add", (Op("add", (x, y)), z))
116
+ right = Op("add", (x, Op("add", (y, z))))
117
+ print(egraph_prove(left, right, I).status) # proven, via add_assoc
118
+
119
+ # extraction returns the smallest member, so a sum of products comes back factored
120
+ f = Op("add", (Op("mul", (x, y)), Op("mul", (x, z))))
121
+ print(egraph_normalize(f, I).sugar()) # mul(add(y, z), x)
122
+ ```
123
+
124
+ Extraction is a min-plus relaxation over the final equivalence classes, and each
125
+ extracted term is checked locally against the class it came from. Saturation
126
+ runs under node and work budgets; when a budget cuts the search short the
127
+ result carries `truncated=True` and is a saturated *subset* — fewer merges,
128
+ never a wrong one.
129
+
130
+ ## What it will not do
131
+
132
+ - A rule whose side is a bare variable is rejected, because e-matching it would
133
+ bind an unconstrained placeholder and merge arbitrary terms.
134
+ - Shifts that lose bits or start negative are `rejected` as undefined, not
135
+ silently modelled.
136
+ - Literals outside the range of their declared type are `rejected`.
137
+ - Budget exhaustion is reported, never rounded down to a confident `proven`.
138
+
139
+ ## Run the tests
140
+
141
+ ```sh
142
+ python test_kernel.py
143
+ ```
144
+
145
+ 41 tests, including an exhaustive bit-exact sweep of every axiom over
146
+ concrete inputs for the small types.
147
+
148
+ ## Examples
149
+
150
+ ```sh
151
+ python examples/egraph.py # equality saturation
152
+ python examples/solve.py # synthesis
153
+ python examples/fib.py # block equivalence
154
+ ```
155
+
156
+ ## License
157
+
158
+ MIT. See [LICENSE](LICENSE).
opreof-0.1.0/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # OProof
2
+
3
+ Bit-exact equivalence proving for machine integers. OProof decides whether two
4
+ computation blocks over `bool`, `int8`…`int64`, and `uint8`…`uint64` compute the
5
+ same outputs, using the arithmetic the target machine actually performs —
6
+ truncation, wraparound, sign extension, and defined shifts.
7
+
8
+ It is not a floating-point or real-arithmetic prover. `x + 1` overflowing
9
+ `int8` is a different function from unbounded `x + 1`, and OProof reports the
10
+ overflow rather than proving something convenient.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pip install opreof
16
+ ```
17
+
18
+ Pure Python, no dependencies, requires Python 3.11+.
19
+
20
+ ## Prove an equivalence
21
+
22
+ ```python
23
+ from opreof import Block, Assign, Var, int8, prove
24
+
25
+ a = Block("a", [Assign(Var("x", int8), Var("y", int8))])
26
+ b = Block("b", [Assign(Var("x", int8), Var("y", int8))])
27
+
28
+ r = prove(a, b, outputs={"x"})
29
+ print(r.status) # proven
30
+ ```
31
+
32
+ `status` is one of:
33
+
34
+ | status | meaning |
35
+ | --- | --- |
36
+ | `proven` | a derivation was found and every step checked |
37
+ | `not_proven` | the prover stopped without finding one |
38
+ | `rejected` | the question is ill-posed (e.g. `200` is not an `int8`) |
39
+
40
+ `not_proven` is not a refutation. Only `proven` is a positive answer, and the
41
+ kernel re-verifies each step of the derivation it returns.
42
+
43
+ ## What it understands
44
+
45
+ Rules live in plain Python files under `axioms/`, so the fact base is data you
46
+ can read, narrow, or replace:
47
+
48
+ Theories are files; axioms are the individual named rules inside them.
49
+ Curation selects **axiom names**, and an unknown name is an error rather than
50
+ a silently ignored typo:
51
+
52
+ ```python
53
+ from opreof import list_theories, theory_rules, list_axioms, with_axioms, prove
54
+
55
+ list_theories() # ['arithmetic', 'foundational', 'logic', 'pow2']
56
+ theory_rules("logic") # every rule from that file
57
+ list_axioms() # 109 names, e.g. 'add_assoc'
58
+
59
+ with with_axioms("add_self_is_shl1"): # only that fact is available
60
+ prove(a, b, outputs={"x"})
61
+
62
+ prove(a, b, outputs={"x"}, axioms=("add_assoc", "add_self_is_shl1")) # per call
63
+ ```
64
+
65
+ Facts proven during a session are generalized and promoted to new axioms,
66
+ persisted back to `axioms/`, so a proof you already paid for is reused.
67
+
68
+ A rule declared with `equational=True` (associativity, distributivity, De
69
+ Morgan) is deliberately kept out of directed normalization. A rewriter that
70
+ fired those would loop or pick arbitrary orientations. OProof hands them to the
71
+ e-graph instead.
72
+
73
+ ## Equality saturation
74
+
75
+ Directed rewriting answers "can `a` become `b`". Equality saturation builds an
76
+ e-graph, applies every rule in both directions until nothing new merges, then
77
+ extracts the cheapest representative:
78
+
79
+ The e-graph entry points take kernel expressions (`Op`/`Var`), plus the
80
+ input-type map, rather than `Block`s:
81
+
82
+ ```python
83
+ from opreof import Var, Op, int8, egraph_normalize, egraph_prove
84
+
85
+ I = {"x": int8, "y": int8, "z": int8}
86
+ x, y, z = Var("x", int8), Var("y", int8), Var("z", int8)
87
+
88
+ # associativity is equational, so only saturation can use it
89
+ left = Op("add", (Op("add", (x, y)), z))
90
+ right = Op("add", (x, Op("add", (y, z))))
91
+ print(egraph_prove(left, right, I).status) # proven, via add_assoc
92
+
93
+ # extraction returns the smallest member, so a sum of products comes back factored
94
+ f = Op("add", (Op("mul", (x, y)), Op("mul", (x, z))))
95
+ print(egraph_normalize(f, I).sugar()) # mul(add(y, z), x)
96
+ ```
97
+
98
+ Extraction is a min-plus relaxation over the final equivalence classes, and each
99
+ extracted term is checked locally against the class it came from. Saturation
100
+ runs under node and work budgets; when a budget cuts the search short the
101
+ result carries `truncated=True` and is a saturated *subset* — fewer merges,
102
+ never a wrong one.
103
+
104
+ ## What it will not do
105
+
106
+ - A rule whose side is a bare variable is rejected, because e-matching it would
107
+ bind an unconstrained placeholder and merge arbitrary terms.
108
+ - Shifts that lose bits or start negative are `rejected` as undefined, not
109
+ silently modelled.
110
+ - Literals outside the range of their declared type are `rejected`.
111
+ - Budget exhaustion is reported, never rounded down to a confident `proven`.
112
+
113
+ ## Run the tests
114
+
115
+ ```sh
116
+ python test_kernel.py
117
+ ```
118
+
119
+ 41 tests, including an exhaustive bit-exact sweep of every axiom over
120
+ concrete inputs for the small types.
121
+
122
+ ## Examples
123
+
124
+ ```sh
125
+ python examples/egraph.py # equality saturation
126
+ python examples/solve.py # synthesis
127
+ python examples/fib.py # block equivalence
128
+ ```
129
+
130
+ ## License
131
+
132
+ MIT. See [LICENSE](LICENSE).
opreof-0.1.0/api.py ADDED
@@ -0,0 +1,346 @@
1
+ import inspect
2
+ from typing import Any, get_args, get_origin
3
+
4
+
5
+ def _definition_name(value: Any) -> str:
6
+ if isinstance(value, Term):
7
+ return value.name
8
+ if isinstance(value, str):
9
+ return value.lower()
10
+ origin = get_origin(value)
11
+ if origin is not None:
12
+ args = ", ".join(_definition_name(arg) for arg in get_args(value))
13
+ return f"{_definition_name(origin)}[{args}]"
14
+ name = getattr(value, "__name__", None) or getattr(value, "__qualname__", None)
15
+ if name:
16
+ return str(name).rsplit(".", 1)[-1].lower()
17
+ return type(value).__name__.lower()
18
+
19
+ class Term:
20
+ """Runtime type/callable descriptor.
21
+
22
+ A term may represent a bare type name, a Python type, a function, a lambda,
23
+ or any object implementing ``__call__``. It retains the resolved
24
+ signature and annotations so callers can inspect and validate it without
25
+ invoking the definition.
26
+ """
27
+
28
+ __slots__ = (
29
+ "annotations",
30
+ "definition",
31
+ "kind",
32
+ "metadata",
33
+ "name",
34
+ "params",
35
+ "return_term",
36
+ )
37
+
38
+ def __init__(
39
+ self,
40
+ definition: Any = None,
41
+ params: Any = None,
42
+ *,
43
+ name: str | None = None,
44
+ metadata: dict[str, Any] | None = None,
45
+ ):
46
+ resolved_name, resolved = _resolve_definition(definition)
47
+ self.definition = resolved
48
+ self.name = str(name or resolved_name or "type").lower()
49
+ self.kind = self._kind_of(resolved)
50
+ self.params = _normalize_params(params, resolved)
51
+ self.annotations = dict(getattr(resolved, "__annotations__", {}) or {})
52
+ return_annotation = self.annotations.get("return")
53
+ self.return_term = _annotation_term(return_annotation)
54
+ self.metadata = dict(metadata or {})
55
+
56
+ @staticmethod
57
+ def _kind_of(definition: Any) -> str:
58
+ if definition is None:
59
+ return "bare"
60
+ if isinstance(definition, Term):
61
+ return "term"
62
+ if isinstance(definition, type):
63
+ return "type"
64
+ if get_origin(definition) is not None:
65
+ return "type"
66
+ if all(hasattr(definition, a) for a in ("name", "width", "signed")):
67
+ return "type"
68
+ if getattr(definition, "__name__", None) == "<lambda>":
69
+ return "lambda"
70
+ return "callable"
71
+
72
+ @property
73
+ def signature(self) -> inspect.Signature | None:
74
+ if self.definition is None:
75
+ return None
76
+ if isinstance(self.definition, Term):
77
+ return self.definition.signature
78
+ try:
79
+ return inspect.signature(self.definition)
80
+ except (TypeError, ValueError):
81
+ return None
82
+
83
+ @property
84
+ def is_callable(self) -> bool:
85
+ return isinstance(self.definition, Term) or callable(self.definition)
86
+
87
+ def resolve(self) -> Any:
88
+ """Return the underlying definition, or this term for a bare term."""
89
+ return self.definition if self.definition is not None else self
90
+
91
+ def accepts(self, *args: Any, **kwargs: Any) -> bool:
92
+ signature = self.signature
93
+ if signature is None:
94
+ return not self.is_callable
95
+ try:
96
+ signature.bind(*args, **kwargs)
97
+ except TypeError:
98
+ return False
99
+ return True
100
+
101
+ def bind(self, *args: Any, **kwargs: Any) -> inspect.BoundArguments:
102
+ signature = self.signature
103
+ if signature is None:
104
+ raise TypeError(f"term {self.name!r} has no callable signature")
105
+ return signature.bind(*args, **kwargs)
106
+
107
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
108
+ return Call(self, args, kwargs)
109
+
110
+ def __repr__(self) -> str:
111
+ return f"Term({self.name!r}, kind={self.kind!r}, params={self.params!r})"
112
+
113
+ def __hash__(self) -> int:
114
+ return hash((self.name, self.kind, _value_key(self.definition),
115
+ _value_key(self.params)))
116
+
117
+ def __eq__(self, other: object) -> bool:
118
+ if not isinstance(other, Term):
119
+ return NotImplemented
120
+ return (
121
+ self.name,
122
+ self.kind,
123
+ _value_key(self.definition),
124
+ _value_key(self.params),
125
+ ) == (
126
+ other.name,
127
+ other.kind,
128
+ _value_key(other.definition),
129
+ _value_key(other.params),
130
+ )
131
+
132
+ def _callable_name(value: Any) -> str:
133
+ """Return a stable, lowered name for a type or callable definition."""
134
+ name = getattr(value, "__name__", None)
135
+ if not name:
136
+ name = getattr(value, "__qualname__", None)
137
+ if not name:
138
+ name = type(value).__name__
139
+ return str(name).rsplit(".", 1)[-1].lower()
140
+
141
+ def _resolve_definition(definition: Any) -> tuple[str, Any]:
142
+ """Resolve aliases and callable objects without requiring a function type."""
143
+ if isinstance(definition, Term):
144
+ return definition.name, definition
145
+ if definition is None:
146
+ return "", None
147
+ if isinstance(definition, str):
148
+ return definition.lower(), None
149
+ if isinstance(definition, type) or get_origin(definition) is not None:
150
+ return _definition_name(definition), definition
151
+ # OProof kernel type descriptor (a Type carrying name/width/signed).
152
+ # Admitted here so ``Term(int32)`` can resolve to the kernel's ``int32``
153
+ # through the OProof bridge -- the two layers stay separate, this just
154
+ # lets the api *denote* a kernel machine type.
155
+ if (
156
+ not callable(definition)
157
+ and all(hasattr(definition, a) for a in ("name", "width", "signed"))
158
+ ):
159
+ return str(definition.name).lower(), definition
160
+ if not callable(definition):
161
+ raise TypeError(
162
+ "definition must be None, a Term, a type, a parameterized type, "
163
+ "or a callable object"
164
+ )
165
+ return _callable_name(definition), definition
166
+
167
+ def _annotation_term(annotation: Any) -> Term | None:
168
+ if annotation is None or annotation is inspect.Signature.empty:
169
+ return None
170
+ if isinstance(annotation, Term):
171
+ return annotation
172
+ if isinstance(annotation, type) or get_origin(annotation) is not None:
173
+ return Term(annotation)
174
+ if callable(annotation):
175
+ return Term(annotation)
176
+ return Term(name=_definition_name(annotation), metadata={"annotation": annotation})
177
+
178
+ def _value_key(value: Any) -> Any:
179
+ """Build a hash-safe key without invoking arbitrary equality methods."""
180
+ if isinstance(value, Term):
181
+ return (
182
+ type(value),
183
+ value.name,
184
+ value.kind,
185
+ _value_key(value.definition),
186
+ _value_key(value.params),
187
+ )
188
+ if isinstance(value, tuple):
189
+ return tuple(_value_key(item) for item in value)
190
+ if isinstance(value, list):
191
+ return ("list", tuple(_value_key(item) for item in value))
192
+ try:
193
+ hash(value)
194
+ except TypeError:
195
+ return ("identity", type(value), id(value))
196
+ return ("value", type(value), value)
197
+
198
+ def _normalize_params(params: Any, definition: Any) -> tuple:
199
+ if params is None:
200
+ if definition is None:
201
+ return ()
202
+ if isinstance(definition, Term):
203
+ return definition.params
204
+ try:
205
+ return tuple(inspect.signature(definition).parameters.values())
206
+ except (TypeError, ValueError):
207
+ return ()
208
+ if isinstance(params, str):
209
+ return (params,)
210
+ if isinstance(params, tuple):
211
+ return params
212
+ if isinstance(params, list):
213
+ return tuple(params)
214
+ return (params,)
215
+
216
+ class Call(Term):
217
+ """Proof-term representation of applying a term to arguments."""
218
+
219
+ __slots__ = ("args", "callee", "kwargs")
220
+
221
+ def __init__(
222
+ self,
223
+ callee: Term,
224
+ args: tuple[Any, ...] = (),
225
+ kwargs: dict[str, Any] | None = None,
226
+ ):
227
+ if not isinstance(callee, Term):
228
+ raise TypeError("Call callee must be a Term")
229
+ super().__init__(name=f"{callee.name}()")
230
+ self.kind = "call"
231
+ self.return_term = callee.return_term
232
+ self.callee = callee
233
+ self.args = tuple(args)
234
+ self.kwargs = dict(kwargs or {})
235
+
236
+ @property
237
+ def term(self) -> Term:
238
+ return self.callee
239
+
240
+ def __repr__(self) -> str:
241
+ suffix = ", ".join(
242
+ [*(repr(arg) for arg in self.args), *(
243
+ f"{key}={value!r}" for key, value in self.kwargs.items()
244
+ )]
245
+ )
246
+ return f"Call({self.callee!r}{', ' if suffix else ''}{suffix})"
247
+
248
+ def __hash__(self) -> int:
249
+ return hash((
250
+ type(self),
251
+ _value_key(self.callee),
252
+ _value_key(self.args),
253
+ _value_key(self.kwargs),
254
+ ))
255
+
256
+ def __eq__(self, other: object) -> bool:
257
+ if not isinstance(other, Call):
258
+ return NotImplemented
259
+ return (
260
+ _value_key(self.callee),
261
+ _value_key(self.args),
262
+ _value_key(self.kwargs),
263
+ ) == (
264
+ _value_key(other.callee),
265
+ _value_key(other.args),
266
+ _value_key(other.kwargs),
267
+ )
268
+
269
+ class Literal(Term):
270
+ """A concrete literal value at the api layer.
271
+
272
+ ``7`` is a value, not a type: a literal Term carries ``kind == 'literal'``
273
+ with its value directly in ``definition`` (and, when known, the kernel
274
+ ``Type`` it belongs to in ``type``). This is what ``term_of_expr``
275
+ produces for kernel ``Lit`` nodes, so the round-trip
276
+ ``expr_of_term(term_of_expr(Lit))`` is lossless instead of mislabelling
277
+ the constant as ``kind='type'``.
278
+ """
279
+
280
+ __slots__ = ("type", "value")
281
+
282
+ def __init__(self, value: Any, type_: "Type | None" = None):
283
+ super().__init__(definition=None, name=str(value))
284
+ self.value = value
285
+ self.type = type_
286
+ self.definition = value
287
+ self.kind = "literal"
288
+
289
+ def __repr__(self) -> str:
290
+ suffix = "" if self.type is None else f", {self.type.name}"
291
+ return f"Literal({self.value!r}{suffix})"
292
+
293
+ def __str__(self) -> str:
294
+ return str(self.value)
295
+
296
+ def __hash__(self) -> int:
297
+ return hash(("literal", self.value, self.type))
298
+
299
+ def __eq__(self, other: object) -> bool:
300
+ return (
301
+ isinstance(other, Literal)
302
+ and self.value == other.value
303
+ and self.type == other.type
304
+ )
305
+
306
+ def parse_parms(
307
+ definition: Any = None,
308
+ params: Any = None,
309
+ *,
310
+ name: str | None = None,
311
+ ) -> Term:
312
+ """Lower any definition into a fully introspectable :class:`Term`.
313
+
314
+ ``definition`` may be absent, a normal type, a lambda, a function, or any
315
+ object implementing ``__call__``. ``params`` may be omitted, in which case
316
+ callable signatures are resolved with :func:`inspect.signature`.
317
+
318
+ Examples::
319
+
320
+ parse_parms() # bare/anonymous type
321
+ parse_parms(int) # type definition
322
+ parse_parms(Term(lambda x: x + 1)) # callable term
323
+ parse_parms(handler_object) # arbitrary callable instance
324
+ parse_parms(int, ("value",)) # explicit parameters
325
+ """
326
+ if isinstance(definition, Term) and params is None and name is None:
327
+ return definition
328
+ return Term(
329
+ definition,
330
+ params,
331
+ name=name,
332
+ )
333
+
334
+ # Backward-compatible constructor retained for callers using the previous API:
335
+ # Type("name", params, definition).
336
+
337
+ class Type(Term):
338
+ def __init__(
339
+ self,
340
+ name: str,
341
+ params: Any = None,
342
+ definition: Any = None,
343
+ ):
344
+ super().__init__(definition, params, name=name)
345
+
346
+ _parse_parms = parse_parms