egglog 11.2.0__cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.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.

Potentially problematic release.


This version of egglog might be problematic. Click here for more details.

Files changed (46) hide show
  1. egglog/__init__.py +13 -0
  2. egglog/bindings.cpython-314-x86_64-linux-gnu.so +0 -0
  3. egglog/bindings.pyi +734 -0
  4. egglog/builtins.py +1133 -0
  5. egglog/config.py +8 -0
  6. egglog/conversion.py +286 -0
  7. egglog/declarations.py +912 -0
  8. egglog/deconstruct.py +173 -0
  9. egglog/egraph.py +1875 -0
  10. egglog/egraph_state.py +680 -0
  11. egglog/examples/README.rst +5 -0
  12. egglog/examples/__init__.py +3 -0
  13. egglog/examples/bignum.py +32 -0
  14. egglog/examples/bool.py +38 -0
  15. egglog/examples/eqsat_basic.py +44 -0
  16. egglog/examples/fib.py +28 -0
  17. egglog/examples/higher_order_functions.py +42 -0
  18. egglog/examples/jointree.py +67 -0
  19. egglog/examples/lambda_.py +287 -0
  20. egglog/examples/matrix.py +175 -0
  21. egglog/examples/multiset.py +60 -0
  22. egglog/examples/ndarrays.py +144 -0
  23. egglog/examples/resolution.py +84 -0
  24. egglog/examples/schedule_demo.py +34 -0
  25. egglog/exp/__init__.py +3 -0
  26. egglog/exp/array_api.py +2019 -0
  27. egglog/exp/array_api_jit.py +51 -0
  28. egglog/exp/array_api_loopnest.py +74 -0
  29. egglog/exp/array_api_numba.py +69 -0
  30. egglog/exp/array_api_program_gen.py +510 -0
  31. egglog/exp/program_gen.py +425 -0
  32. egglog/exp/siu_examples.py +32 -0
  33. egglog/ipython_magic.py +41 -0
  34. egglog/pretty.py +509 -0
  35. egglog/py.typed +0 -0
  36. egglog/runtime.py +712 -0
  37. egglog/thunk.py +97 -0
  38. egglog/type_constraint_solver.py +113 -0
  39. egglog/version_compat.py +87 -0
  40. egglog/visualizer.css +1 -0
  41. egglog/visualizer.js +35777 -0
  42. egglog/visualizer_widget.py +39 -0
  43. egglog-11.2.0.dist-info/METADATA +74 -0
  44. egglog-11.2.0.dist-info/RECORD +46 -0
  45. egglog-11.2.0.dist-info/WHEEL +4 -0
  46. egglog-11.2.0.dist-info/licenses/LICENSE +21 -0
egglog/egraph.py ADDED
@@ -0,0 +1,1875 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import inspect
5
+ import pathlib
6
+ import tempfile
7
+ from collections.abc import Callable, Generator, Iterable
8
+ from contextvars import ContextVar, Token
9
+ from dataclasses import InitVar, dataclass, field
10
+ from functools import partial
11
+ from inspect import Parameter, currentframe, signature
12
+ from types import FrameType, FunctionType
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ ClassVar,
17
+ Generic,
18
+ Literal,
19
+ TypeAlias,
20
+ TypedDict,
21
+ TypeVar,
22
+ cast,
23
+ get_type_hints,
24
+ overload,
25
+ )
26
+ from warnings import warn
27
+
28
+ import graphviz
29
+ from typing_extensions import Never, ParamSpec, Self, Unpack, assert_never
30
+
31
+ from . import bindings
32
+ from .conversion import *
33
+ from .conversion import convert_to_same_type, resolve_literal
34
+ from .declarations import *
35
+ from .egraph_state import *
36
+ from .ipython_magic import IN_IPYTHON
37
+ from .pretty import pretty_decl
38
+ from .runtime import *
39
+ from .thunk import *
40
+ from .version_compat import *
41
+
42
+ if TYPE_CHECKING:
43
+ from .builtins import String, Unit, i64Like
44
+
45
+
46
+ __all__ = [
47
+ "Action",
48
+ "BaseExpr",
49
+ "BuiltinExpr",
50
+ "Command",
51
+ "Command",
52
+ "EGraph",
53
+ "Expr",
54
+ "Fact",
55
+ "Fact",
56
+ "GraphvizKwargs",
57
+ "RewriteOrRule",
58
+ "Ruleset",
59
+ "Schedule",
60
+ "_BirewriteBuilder",
61
+ "_EqBuilder",
62
+ "_NeBuilder",
63
+ "_RewriteBuilder",
64
+ "_SetBuilder",
65
+ "_UnionBuilder",
66
+ "birewrite",
67
+ "check",
68
+ "check_eq",
69
+ "constant",
70
+ "delete",
71
+ "eq",
72
+ "expr_action",
73
+ "expr_fact",
74
+ "expr_parts",
75
+ "function",
76
+ "let",
77
+ "method",
78
+ "ne",
79
+ "panic",
80
+ "relation",
81
+ "rewrite",
82
+ "rule",
83
+ "ruleset",
84
+ "run",
85
+ "seq",
86
+ "set_",
87
+ "set_cost",
88
+ "subsume",
89
+ "union",
90
+ "unstable_combine_rulesets",
91
+ "var",
92
+ "vars_",
93
+ ]
94
+
95
+ T = TypeVar("T")
96
+ P = ParamSpec("P")
97
+ EXPR_TYPE = TypeVar("EXPR_TYPE", bound="type[Expr]")
98
+ BASE_EXPR_TYPE = TypeVar("BASE_EXPR_TYPE", bound="type[BaseExpr]")
99
+ EXPR = TypeVar("EXPR", bound="Expr")
100
+ BASE_EXPR = TypeVar("BASE_EXPR", bound="BaseExpr")
101
+ BE1 = TypeVar("BE1", bound="BaseExpr")
102
+ BE2 = TypeVar("BE2", bound="BaseExpr")
103
+ BE3 = TypeVar("BE3", bound="BaseExpr")
104
+ BE4 = TypeVar("BE4", bound="BaseExpr")
105
+ # Attributes which are sometimes added to classes by the interpreter or the dataclass decorator, or by ipython.
106
+ # We ignore these when inspecting the class.
107
+
108
+ IGNORED_ATTRIBUTES = {
109
+ "__module__",
110
+ "__doc__",
111
+ "__dict__",
112
+ "__weakref__",
113
+ "__orig_bases__",
114
+ "__annotations__",
115
+ "__qualname__",
116
+ "__firstlineno__",
117
+ "__static_attributes__",
118
+ "__match_args__",
119
+ # Ignore all reflected binary method
120
+ *(f"__r{m[2:]}" for m in NUMERIC_BINARY_METHODS),
121
+ }
122
+
123
+
124
+ # special methods that return none and mutate self
125
+ ALWAYS_MUTATES_SELF = {"__setitem__", "__delitem__"}
126
+ # special methods which must return real python values instead of lazy expressions
127
+ ALWAYS_PRESERVED = {
128
+ "__repr__",
129
+ "__str__",
130
+ "__bytes__",
131
+ "__format__",
132
+ "__hash__",
133
+ "__bool__",
134
+ "__len__",
135
+ "__length_hint__",
136
+ "__iter__",
137
+ "__reversed__",
138
+ "__contains__",
139
+ "__index__",
140
+ "__bufer__",
141
+ }
142
+
143
+
144
+ def check_eq(x: BASE_EXPR, y: BASE_EXPR, schedule: Schedule | None = None, *, add_second=True, display=False) -> EGraph:
145
+ """
146
+ Verifies that two expressions are equal after running the schedule.
147
+
148
+ If add_second is true, then the second expression is added to the egraph before running the schedule.
149
+ """
150
+ egraph = EGraph()
151
+ x_var = egraph.let("__check_eq_x", x)
152
+ y_var: BASE_EXPR = egraph.let("__check_eq_y", y) if add_second else y
153
+ if schedule:
154
+ try:
155
+ egraph.run(schedule)
156
+ finally:
157
+ if display:
158
+ egraph.display()
159
+ fact = eq(x_var).to(y_var)
160
+ try:
161
+ egraph.check(fact)
162
+ except bindings.EggSmolError as err:
163
+ if display:
164
+ egraph.display()
165
+ raise add_note(
166
+ f"Failed:\n{eq(x).to(y)}\n\nExtracted:\n {eq(egraph.extract(x)).to(egraph.extract(y))})", err
167
+ ) from None
168
+ return egraph
169
+
170
+
171
+ def check(x: FactLike, schedule: Schedule | None = None, *given: ActionLike) -> None:
172
+ """
173
+ Verifies that the fact is true given some assumptions and after running the schedule.
174
+ """
175
+ egraph = EGraph()
176
+ if given:
177
+ egraph.register(*given)
178
+ if schedule:
179
+ egraph.run(schedule)
180
+ egraph.check(x)
181
+
182
+
183
+ # We seperate the function and method overloads to make it simpler to know if we are modifying a function or method,
184
+ # So that we can add the functions eagerly to the registry and wait on the methods till we process the class.
185
+
186
+
187
+ CALLABLE = TypeVar("CALLABLE", bound=Callable)
188
+ CONSTRUCTOR_CALLABLE = TypeVar("CONSTRUCTOR_CALLABLE", bound=Callable[..., "Expr | None"])
189
+
190
+ EXPR_NONE = TypeVar("EXPR_NONE", bound="Expr | None")
191
+ BASE_EXPR_NONE = TypeVar("BASE_EXPR_NONE", bound="BaseExpr | None")
192
+
193
+
194
+ @overload
195
+ def method(
196
+ *,
197
+ preserve: Literal[True],
198
+ ) -> Callable[[CALLABLE], CALLABLE]: ...
199
+
200
+
201
+ # function wihout merge
202
+ @overload
203
+ def method(
204
+ *,
205
+ egg_fn: str | None = ...,
206
+ reverse_args: bool = ...,
207
+ mutates_self: bool = ...,
208
+ ) -> Callable[[CALLABLE], CALLABLE]: ...
209
+
210
+
211
+ # function
212
+ @overload
213
+ def method(
214
+ *,
215
+ egg_fn: str | None = ...,
216
+ merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = ...,
217
+ mutates_self: bool = ...,
218
+ ) -> Callable[[Callable[P, BASE_EXPR]], Callable[P, BASE_EXPR]]: ...
219
+
220
+
221
+ # constructor
222
+ @overload
223
+ def method(
224
+ *,
225
+ egg_fn: str | None = ...,
226
+ cost: int | None = ...,
227
+ mutates_self: bool = ...,
228
+ unextractable: bool = ...,
229
+ subsume: bool = ...,
230
+ ) -> Callable[[Callable[P, EXPR_NONE]], Callable[P, EXPR_NONE]]: ...
231
+
232
+
233
+ def method(
234
+ *,
235
+ egg_fn: str | None = None,
236
+ cost: int | None = None,
237
+ merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = None,
238
+ preserve: bool = False,
239
+ mutates_self: bool = False,
240
+ unextractable: bool = False,
241
+ subsume: bool = False,
242
+ reverse_args: bool = False,
243
+ ) -> Callable[[Callable[P, BASE_EXPR_NONE]], Callable[P, BASE_EXPR_NONE]]:
244
+ """
245
+ Any method can be decorated with this to customize it's behavior. This is only supported in classes which subclass :class:`Expr`.
246
+ """
247
+ merge = cast("Callable[[object, object], object]", merge)
248
+ return lambda fn: _WrappedMethod(
249
+ egg_fn, cost, merge, fn, preserve, mutates_self, unextractable, subsume, reverse_args
250
+ )
251
+
252
+
253
+ @overload
254
+ def function(fn: CALLABLE, /) -> CALLABLE: ...
255
+
256
+
257
+ # function without merge
258
+ @overload
259
+ def function(
260
+ *,
261
+ egg_fn: str | None = ...,
262
+ builtin: bool = ...,
263
+ mutates_first_arg: bool = ...,
264
+ ) -> Callable[[CALLABLE], CALLABLE]: ...
265
+
266
+
267
+ # function
268
+ @overload
269
+ def function(
270
+ *,
271
+ egg_fn: str | None = ...,
272
+ merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = ...,
273
+ builtin: bool = ...,
274
+ mutates_first_arg: bool = ...,
275
+ ) -> Callable[[Callable[P, BASE_EXPR]], Callable[P, BASE_EXPR]]: ...
276
+
277
+
278
+ # constructor
279
+ @overload
280
+ def function(
281
+ *,
282
+ egg_fn: str | None = ...,
283
+ cost: int | None = ...,
284
+ mutates_first_arg: bool = ...,
285
+ unextractable: bool = ...,
286
+ ruleset: Ruleset | None = ...,
287
+ subsume: bool = ...,
288
+ ) -> Callable[[CONSTRUCTOR_CALLABLE], CONSTRUCTOR_CALLABLE]: ...
289
+
290
+
291
+ def function(*args, **kwargs) -> Any:
292
+ """
293
+ Decorate a function typing stub to create an egglog function for it.
294
+
295
+ If a body is included, it will be added to the `ruleset` passed in as a default rewrite.
296
+
297
+ This will default to creating a "constructor" in egglog, unless a merge function is passed in or the return
298
+ type is a primtive, then it will be a "function".
299
+ """
300
+ fn_locals = currentframe().f_back.f_locals # type: ignore[union-attr]
301
+
302
+ # If we have any positional args, then we are calling it directly on a function
303
+ if args:
304
+ assert len(args) == 1
305
+ return _FunctionConstructor(fn_locals)(args[0])
306
+ # otherwise, we are passing some keyword args, so save those, and then return a partial
307
+ return _FunctionConstructor(fn_locals, **kwargs)
308
+
309
+
310
+ class _ExprMetaclass(type):
311
+ """
312
+ Metaclass of Expr.
313
+
314
+ Used to override isistance checks, so that runtime expressions are instances of Expr at runtime.
315
+ """
316
+
317
+ def __new__( # type: ignore[misc]
318
+ cls: type[_ExprMetaclass],
319
+ name: str,
320
+ bases: tuple[type, ...],
321
+ namespace: dict[str, Any],
322
+ egg_sort: str | None = None,
323
+ ruleset: Ruleset | None = None,
324
+ ) -> RuntimeClass | type:
325
+ # If this is the Expr subclass, just return the class
326
+ if not bases or bases == (BaseExpr,):
327
+ return super().__new__(cls, name, bases, namespace)
328
+ builtin = BuiltinExpr in bases
329
+ # TODO: Raise error on subclassing or multiple inheritence
330
+
331
+ frame = currentframe()
332
+ assert frame
333
+ prev_frame = frame.f_back
334
+ assert prev_frame
335
+
336
+ # Pass in an instance of the class so that when we are generating the decls
337
+ # we can update them eagerly so that we can access the methods in the class body
338
+ runtime_cls = RuntimeClass(None, TypeRefWithVars(name)) # type: ignore[arg-type]
339
+
340
+ # Store frame so that we can get live access to updated locals/globals
341
+ # Otherwise, f_locals returns a copy
342
+ # https://peps.python.org/pep-0667/
343
+ runtime_cls.__egg_decls_thunk__ = Thunk.fn(
344
+ _generate_class_decls,
345
+ namespace,
346
+ prev_frame,
347
+ builtin,
348
+ egg_sort,
349
+ name,
350
+ ruleset,
351
+ runtime_cls,
352
+ )
353
+ return runtime_cls
354
+
355
+ def __instancecheck__(cls, instance: object) -> bool:
356
+ return isinstance(instance, RuntimeExpr)
357
+
358
+
359
+ class BaseExpr(metaclass=_ExprMetaclass):
360
+ """
361
+ Either a builtin or a user defined expression type.
362
+ """
363
+
364
+ def __ne__(self, other: Self) -> Unit: ... # type: ignore[override, empty-body]
365
+
366
+ # not currently dissalowing other types of equality https://github.com/python/typeshed/issues/8217#issuecomment-3140873292
367
+ def __eq__(self, other: Self) -> Fact: ... # type: ignore[override, empty-body]
368
+
369
+
370
+ class BuiltinExpr(BaseExpr, metaclass=_ExprMetaclass):
371
+ """
372
+ A builtin expr type, not an eqsort.
373
+ """
374
+
375
+
376
+ class Expr(BaseExpr, metaclass=_ExprMetaclass):
377
+ """
378
+ Subclass this to define a custom expression type.
379
+ """
380
+
381
+
382
+ def _generate_class_decls( # noqa: C901,PLR0912
383
+ namespace: dict[str, Any],
384
+ frame: FrameType,
385
+ builtin: bool,
386
+ egg_sort: str | None,
387
+ cls_name: str,
388
+ ruleset: Ruleset | None,
389
+ runtime_cls: RuntimeClass,
390
+ ) -> Declarations:
391
+ """
392
+ Lazy constructor for class declerations to support classes with methods whose types are not yet defined.
393
+ """
394
+ parameters: list[TypeVar] = (
395
+ # Get the generic params from the orig bases generic class
396
+ namespace["__orig_bases__"][1].__parameters__ if "__orig_bases__" in namespace else []
397
+ )
398
+ type_vars = tuple(ClassTypeVarRef.from_type_var(p) for p in parameters)
399
+ del parameters
400
+ cls_decl = ClassDecl(egg_sort, type_vars, builtin, match_args=namespace.pop("__match_args__", ()))
401
+ decls = Declarations(_classes={cls_name: cls_decl})
402
+ # Update class think eagerly when resolving so that lookups work in methods
403
+ runtime_cls.__egg_decls_thunk__ = Thunk.value(decls)
404
+
405
+ ##
406
+ # Register class variables
407
+ ##
408
+ # Create a dummy type to pass to get_type_hints to resolve the annotations we have
409
+ _Dummytype = type("_DummyType", (), {"__annotations__": namespace.get("__annotations__", {})})
410
+ for k, v in get_type_hints(_Dummytype, globalns=frame.f_globals, localns=frame.f_locals).items():
411
+ if getattr(v, "__origin__", None) == ClassVar:
412
+ (inner_tp,) = v.__args__
413
+ type_ref = resolve_type_annotation_mutate(decls, inner_tp)
414
+ cls_decl.class_variables[k] = ConstantDecl(type_ref.to_just())
415
+ _add_default_rewrite(
416
+ decls, ClassVariableRef(cls_name, k), type_ref, namespace.pop(k, None), ruleset, subsume=False
417
+ )
418
+ else:
419
+ msg = f"On class {cls_name}, for attribute '{k}', expected a ClassVar, but got {v}"
420
+ raise NotImplementedError(msg)
421
+
422
+ ##
423
+ # Register methods, classmethods, preserved methods, and properties
424
+ ##
425
+ # Get all the methods from the class
426
+ filtered_namespace: list[tuple[str, Any]] = [
427
+ (k, v) for k, v in namespace.items() if k not in IGNORED_ATTRIBUTES or isinstance(v, _WrappedMethod)
428
+ ]
429
+
430
+ # all methods we should try adding default functions for
431
+ add_default_funcs: list[Callable[[], None]] = []
432
+ # Then register each of its methods
433
+ for method_name, method in filtered_namespace:
434
+ is_init = method_name == "__init__"
435
+ # Don't register the init methods for literals, since those don't use the type checking mechanisms
436
+ if is_init and cls_name in LIT_CLASS_NAMES:
437
+ continue
438
+ match method:
439
+ case _WrappedMethod(egg_fn, cost, merge, fn, preserve, mutates, unextractable, subsume, reverse_args):
440
+ pass
441
+ case _:
442
+ egg_fn, cost, merge = None, None, None
443
+ fn = method
444
+ unextractable, preserve, subsume = False, False, False
445
+ mutates = method_name in ALWAYS_MUTATES_SELF
446
+ reverse_args = False
447
+ if preserve:
448
+ cls_decl.preserved_methods[method_name] = fn
449
+ continue
450
+ locals = frame.f_locals
451
+ ref: ClassMethodRef | MethodRef | PropertyRef | InitRef
452
+ # TODO: Store deprecated message so we can print at runtime
453
+ if (getattr(fn, "__deprecated__", None)) is not None:
454
+ fn = fn.__wrapped__ # type: ignore[attr-defined]
455
+ match fn:
456
+ case classmethod():
457
+ ref = ClassMethodRef(cls_name, method_name)
458
+ fn = fn.__func__
459
+ case property():
460
+ ref = PropertyRef(cls_name, method_name)
461
+ fn = fn.fget
462
+ case _:
463
+ ref = InitRef(cls_name) if is_init else MethodRef(cls_name, method_name)
464
+ if isinstance(fn, _WrappedMethod):
465
+ msg = f"{cls_name}.{method_name} Add the @method(...) decorator above @classmethod or @property"
466
+
467
+ raise ValueError(msg) # noqa: TRY004
468
+ special_function_name: SpecialFunctions | None = (
469
+ "fn-partial" if egg_fn == "unstable-fn" else "fn-app" if egg_fn == "unstable-app" else None
470
+ )
471
+ if special_function_name:
472
+ decl = FunctionDecl(special_function_name, builtin=True, egg_name=egg_fn)
473
+ decls.set_function_decl(ref, decl)
474
+ continue
475
+ try:
476
+ add_rewrite = _fn_decl(
477
+ decls,
478
+ egg_fn,
479
+ ref,
480
+ fn,
481
+ locals,
482
+ cost,
483
+ merge,
484
+ mutates,
485
+ builtin,
486
+ ruleset=ruleset,
487
+ unextractable=unextractable,
488
+ subsume=subsume,
489
+ reverse_args=reverse_args,
490
+ )
491
+ except Exception as e:
492
+ raise add_note(f"Error processing {cls_name}.{method_name}", e) from None
493
+
494
+ if not builtin and not isinstance(ref, InitRef) and not mutates:
495
+ add_default_funcs.append(add_rewrite)
496
+
497
+ # Add all rewrite methods at the end so that all methods are registered first and can be accessed
498
+ # in the bodies
499
+ for add_rewrite in add_default_funcs:
500
+ add_rewrite()
501
+ return decls
502
+
503
+
504
+ @dataclass
505
+ class _FunctionConstructor:
506
+ hint_locals: dict[str, Any]
507
+ builtin: bool = False
508
+ mutates_first_arg: bool = False
509
+ egg_fn: str | None = None
510
+ cost: int | None = None
511
+ merge: Callable[[object, object], object] | None = None
512
+ unextractable: bool = False
513
+ ruleset: Ruleset | None = None
514
+ subsume: bool = False
515
+
516
+ def __call__(self, fn: Callable) -> RuntimeFunction:
517
+ return RuntimeFunction(*split_thunk(Thunk.fn(self.create_decls, fn)))
518
+
519
+ def create_decls(self, fn: Callable) -> tuple[Declarations, CallableRef]:
520
+ decls = Declarations()
521
+ add_rewrite = _fn_decl(
522
+ decls,
523
+ self.egg_fn,
524
+ ref := FunctionRef(fn.__name__),
525
+ fn,
526
+ self.hint_locals,
527
+ self.cost,
528
+ self.merge,
529
+ self.mutates_first_arg,
530
+ self.builtin,
531
+ ruleset=self.ruleset,
532
+ subsume=self.subsume,
533
+ unextractable=self.unextractable,
534
+ )
535
+ add_rewrite()
536
+ return decls, ref
537
+
538
+
539
+ def _fn_decl(
540
+ decls: Declarations,
541
+ egg_name: str | None,
542
+ ref: FunctionRef | MethodRef | PropertyRef | ClassMethodRef | InitRef,
543
+ fn: object,
544
+ # Pass in the locals, retrieved from the frame when wrapping,
545
+ # so that we support classes and function defined inside of other functions (which won't show up in the globals)
546
+ hint_locals: dict[str, Any],
547
+ cost: int | None,
548
+ merge: Callable[[object, object], object] | None,
549
+ mutates_first_arg: bool,
550
+ is_builtin: bool,
551
+ subsume: bool,
552
+ ruleset: Ruleset | None = None,
553
+ unextractable: bool = False,
554
+ reverse_args: bool = False,
555
+ ) -> Callable[[], None]:
556
+ """
557
+ Sets the function decl for the function object and returns the ref as well as a thunk that sets the default callable.
558
+ """
559
+ if isinstance(fn, RuntimeFunction):
560
+ msg = "Inside of classes, wrap methods with the `method` decorator, not `function`"
561
+ raise ValueError(msg) # noqa: TRY004
562
+ if not isinstance(fn, FunctionType):
563
+ raise NotImplementedError(f"Can only generate function decls for functions not {fn} {type(fn)}")
564
+
565
+ # Instead of passing both globals and locals, just pass the globals. Otherwise, for some reason forward references
566
+ # won't be resolved correctly
567
+ # We need this to be false so it returns "__forward_value__" https://github.com/python/cpython/blob/440ed18e08887b958ad50db1b823e692a747b671/Lib/typing.py#L919
568
+ # https://github.com/egraphs-good/egglog-python/issues/210
569
+ hint_globals = {**fn.__globals__, **hint_locals}
570
+ hints = get_type_hints(fn, hint_globals)
571
+
572
+ params = list(signature(fn).parameters.values())
573
+
574
+ # If this is an init function, or a classmethod, the first arg is not used
575
+ if isinstance(ref, ClassMethodRef | InitRef):
576
+ params = params[1:]
577
+
578
+ if _last_param_variable(params):
579
+ *params, var_arg_param = params
580
+ # For now, we don't use the variable arg name
581
+ var_arg_type = resolve_type_annotation_mutate(decls, hints[var_arg_param.name])
582
+ else:
583
+ var_arg_type = None
584
+ arg_types = tuple(
585
+ decls.get_paramaterized_class(ref.class_name)
586
+ if i == 0 and isinstance(ref, MethodRef | PropertyRef)
587
+ else resolve_type_annotation_mutate(decls, hints[t.name])
588
+ for i, t in enumerate(params)
589
+ )
590
+
591
+ # Resolve all default values as arg types
592
+ arg_defaults = [
593
+ resolve_literal(t, p.default, Thunk.value(decls)) if p.default is not Parameter.empty else None
594
+ for (t, p) in zip(arg_types, params, strict=True)
595
+ ]
596
+
597
+ decls.update(*arg_defaults)
598
+
599
+ return_type = (
600
+ decls.get_paramaterized_class(ref.class_name)
601
+ if isinstance(ref, InitRef)
602
+ else arg_types[0]
603
+ if mutates_first_arg
604
+ else resolve_type_annotation_mutate(decls, hints["return"])
605
+ )
606
+
607
+ arg_names = tuple(t.name for t in params)
608
+
609
+ merged = (
610
+ None
611
+ if merge is None
612
+ else resolve_literal(
613
+ return_type,
614
+ merge(
615
+ RuntimeExpr.__from_values__(decls, TypedExprDecl(return_type.to_just(), UnboundVarDecl("old", "old"))),
616
+ RuntimeExpr.__from_values__(decls, TypedExprDecl(return_type.to_just(), UnboundVarDecl("new", "new"))),
617
+ ),
618
+ lambda: decls,
619
+ )
620
+ )
621
+ decls |= merged
622
+
623
+ # defer this in generator so it doesn't resolve for builtins eagerly
624
+ args = (TypedExprDecl(tp.to_just(), UnboundVarDecl(name)) for name, tp in zip(arg_names, arg_types, strict=True))
625
+
626
+ return_type_is_eqsort = (
627
+ not decls._classes[return_type.name].builtin if isinstance(return_type, TypeRefWithVars) else False
628
+ )
629
+ is_constructor = not is_builtin and return_type_is_eqsort and merged is None
630
+ signature_ = FunctionSignature(
631
+ return_type=None if mutates_first_arg else return_type,
632
+ var_arg_type=var_arg_type,
633
+ arg_types=arg_types,
634
+ arg_names=arg_names,
635
+ arg_defaults=tuple(a.__egg_typed_expr__.expr if a is not None else None for a in arg_defaults),
636
+ reverse_args=reverse_args,
637
+ )
638
+ decl: ConstructorDecl | FunctionDecl
639
+ if is_constructor:
640
+ decl = ConstructorDecl(signature_, egg_name, cost, unextractable)
641
+ else:
642
+ if cost is not None:
643
+ msg = "Cost can only be set for constructors"
644
+ raise ValueError(msg)
645
+ if unextractable:
646
+ msg = "Unextractable can only be set for constructors"
647
+ raise ValueError(msg)
648
+ decl = FunctionDecl(
649
+ signature=signature_,
650
+ egg_name=egg_name,
651
+ merge=merged.__egg_typed_expr__.expr if merged is not None else None,
652
+ builtin=is_builtin,
653
+ )
654
+ decls.set_function_decl(ref, decl)
655
+ return Thunk.fn(
656
+ _add_default_rewrite_function, decls, ref, fn, args, ruleset, subsume, return_type, context=f"creating {ref}"
657
+ )
658
+
659
+
660
+ # Overload to support aritys 0-4 until variadic generic support map, so we can map from type to value
661
+ @overload
662
+ def relation(
663
+ name: str, tp1: type[BE1], tp2: type[BE2], tp3: type[BE3], tp4: type[BE4], /
664
+ ) -> Callable[[BE1, BE2, BE3, BE4], Unit]: ...
665
+
666
+
667
+ @overload
668
+ def relation(name: str, tp1: type[BE1], tp2: type[BE2], tp3: type[BE3], /) -> Callable[[BE1, BE2, BE3], Unit]: ...
669
+
670
+
671
+ @overload
672
+ def relation(name: str, tp1: type[BE1], tp2: type[BE2], /) -> Callable[[BE1, BE2], Unit]: ...
673
+
674
+
675
+ @overload
676
+ def relation(name: str, tp1: type[BE1], /, *, egg_fn: str | None = None) -> Callable[[BE1], Unit]: ...
677
+
678
+
679
+ @overload
680
+ def relation(name: str, /, *, egg_fn: str | None = None) -> Callable[[], Unit]: ...
681
+
682
+
683
+ def relation(name: str, /, *tps: type, egg_fn: str | None = None) -> Callable[..., Unit]:
684
+ """
685
+ Creates a function whose return type is `Unit` and has a default value.
686
+ """
687
+ decls_thunk = Thunk.fn(_relation_decls, name, tps, egg_fn)
688
+ return cast("Callable[..., Unit]", RuntimeFunction(decls_thunk, Thunk.value(FunctionRef(name))))
689
+
690
+
691
+ def _relation_decls(name: str, tps: tuple[type, ...], egg_fn: str | None) -> Declarations:
692
+ from .builtins import Unit # noqa: PLC0415
693
+
694
+ decls = Declarations()
695
+ decls |= cast("RuntimeClass", Unit)
696
+ arg_types = tuple(resolve_type_annotation_mutate(decls, tp).to_just() for tp in tps)
697
+ decls._functions[name] = RelationDecl(arg_types, tuple(None for _ in tps), egg_fn)
698
+ return decls
699
+
700
+
701
+ def constant(
702
+ name: str,
703
+ tp: type[BASE_EXPR],
704
+ default_replacement: BASE_EXPR | None = None,
705
+ /,
706
+ *,
707
+ egg_name: str | None = None,
708
+ ruleset: Ruleset | None = None,
709
+ ) -> BASE_EXPR:
710
+ """
711
+ A "constant" is implemented as the instantiation of a value that takes no args.
712
+ This creates a function with `name` and return type `tp` and returns a value of it being called.
713
+ """
714
+ return cast(
715
+ "BASE_EXPR",
716
+ RuntimeExpr(*split_thunk(Thunk.fn(_constant_thunk, name, tp, egg_name, default_replacement, ruleset))),
717
+ )
718
+
719
+
720
+ def _constant_thunk(
721
+ name: str, tp: type, egg_name: str | None, default_replacement: object, ruleset: Ruleset | None
722
+ ) -> tuple[Declarations, TypedExprDecl]:
723
+ decls = Declarations()
724
+ type_ref = resolve_type_annotation_mutate(decls, tp)
725
+ callable_ref = ConstantRef(name)
726
+ decls._constants[name] = ConstantDecl(type_ref.to_just(), egg_name)
727
+ _add_default_rewrite(decls, callable_ref, type_ref, default_replacement, ruleset, subsume=False)
728
+ return decls, TypedExprDecl(type_ref.to_just(), CallDecl(callable_ref))
729
+
730
+
731
+ def _add_default_rewrite_function(
732
+ decls: Declarations,
733
+ ref: FunctionRef | MethodRef | PropertyRef | ClassMethodRef | InitRef,
734
+ fn: Callable,
735
+ args: Iterable[TypedExprDecl],
736
+ ruleset: Ruleset | None,
737
+ subsume: bool,
738
+ res_type: TypeOrVarRef,
739
+ ) -> None:
740
+ args: list[object] = [RuntimeExpr.__from_values__(decls, a) for a in args]
741
+
742
+ # If this is a classmethod, add the class as the first arg
743
+ if isinstance(ref, ClassMethodRef):
744
+ tp = decls.get_paramaterized_class(ref.class_name)
745
+ args.insert(0, RuntimeClass(Thunk.value(decls), tp))
746
+ with set_current_ruleset(ruleset):
747
+ res = fn(*args)
748
+ _add_default_rewrite(decls, ref, res_type, res, ruleset, subsume)
749
+
750
+
751
+ def _add_default_rewrite(
752
+ decls: Declarations,
753
+ ref: CallableRef,
754
+ type_ref: TypeOrVarRef,
755
+ default_rewrite: object,
756
+ ruleset: Ruleset | None,
757
+ subsume: bool,
758
+ ) -> None:
759
+ """
760
+ Adds a default rewrite for the callable, if the default rewrite is not None
761
+
762
+ Will add it to the ruleset if it is passed in, or add it to the default ruleset on the passed in decls if not.
763
+ """
764
+ if default_rewrite is None:
765
+ return
766
+ resolved_value = resolve_literal(type_ref, default_rewrite, Thunk.value(decls))
767
+ rewrite_decl = DefaultRewriteDecl(ref, resolved_value.__egg_typed_expr__.expr, subsume)
768
+ ruleset_decls = _add_default_rewrite_inner(decls, rewrite_decl, ruleset)
769
+ ruleset_decls |= resolved_value
770
+
771
+
772
+ def _add_default_rewrite_inner(
773
+ decls: Declarations, rewrite_decl: DefaultRewriteDecl, ruleset: Ruleset | None
774
+ ) -> Declarations:
775
+ if ruleset:
776
+ ruleset_decls = ruleset._current_egg_decls
777
+ ruleset_decl = ruleset.__egg_ruleset__
778
+ else:
779
+ ruleset_decls = decls
780
+ ruleset_decl = decls.default_ruleset
781
+ ruleset_decl.rules.append(rewrite_decl)
782
+ return ruleset_decls
783
+
784
+
785
+ def _last_param_variable(params: list[Parameter]) -> bool:
786
+ """
787
+ Checks if the last paramater is a variable arg.
788
+
789
+ Raises an error if any of the other params are not positional or keyword.
790
+ """
791
+ found_var_arg = False
792
+ for param in params:
793
+ if found_var_arg:
794
+ msg = "Can only have a single var arg at the end"
795
+ raise ValueError(msg)
796
+ kind = param.kind
797
+ if kind == Parameter.VAR_POSITIONAL:
798
+ found_var_arg = True
799
+ elif kind != Parameter.POSITIONAL_OR_KEYWORD:
800
+ raise ValueError(f"Can only register functions with positional or keyword args, not {param.kind}")
801
+ return found_var_arg
802
+
803
+
804
+ class GraphvizKwargs(TypedDict, total=False):
805
+ max_functions: int | None
806
+ max_calls_per_function: int | None
807
+ n_inline_leaves: int
808
+ split_primitive_outputs: bool
809
+ split_functions: list[ExprCallable]
810
+ include_temporary_functions: bool
811
+
812
+
813
+ @dataclass
814
+ class EGraph:
815
+ """
816
+ A collection of expressions where each expression is part of a distinct equivalence class.
817
+
818
+ Can run actions, check facts, run schedules, or extract minimal cost expressions.
819
+ """
820
+
821
+ seminaive: InitVar[bool] = True
822
+ save_egglog_string: InitVar[bool] = False
823
+
824
+ _state: EGraphState = field(init=False, repr=False)
825
+ # For pushing/popping with egglog
826
+ _state_stack: list[EGraphState] = field(default_factory=list, repr=False)
827
+ # For storing the global "current" egraph
828
+ _token_stack: list[EGraph] = field(default_factory=list, repr=False)
829
+
830
+ def __post_init__(self, seminaive: bool, save_egglog_string: bool) -> None:
831
+ egraph = bindings.EGraph(GLOBAL_PY_OBJECT_SORT, seminaive=seminaive, record=save_egglog_string)
832
+ self._state = EGraphState(egraph)
833
+
834
+ def _add_decls(self, *decls: DeclerationsLike) -> None:
835
+ for d in decls:
836
+ self._state.__egg_decls__ |= d
837
+
838
+ @property
839
+ def as_egglog_string(self) -> str:
840
+ """
841
+ Returns the egglog string for this module.
842
+ """
843
+ cmds = self._egraph.commands()
844
+ if cmds is None:
845
+ msg = "Can't get egglog string unless EGraph created with save_egglog_string=True"
846
+ raise ValueError(msg)
847
+ return cmds
848
+
849
+ def _ipython_display_(self) -> None:
850
+ self.display()
851
+
852
+ def input(self, fn: Callable[..., String], path: str) -> None:
853
+ """
854
+ Loads a CSV file and sets it as *input, output of the function.
855
+ """
856
+ self._egraph.run_program(bindings.Input(span(1), self._callable_to_egg(fn)[1], path))
857
+
858
+ def _callable_to_egg(self, fn: ExprCallable) -> tuple[CallableRef, str]:
859
+ ref, decls = resolve_callable(fn)
860
+ self._add_decls(decls)
861
+ return ref, self._state.callable_ref_to_egg(ref)[0]
862
+
863
+ # TODO: Change let to be action...
864
+ def let(self, name: str, expr: BASE_EXPR) -> BASE_EXPR:
865
+ """
866
+ Define a new expression in the egraph and return a reference to it.
867
+ """
868
+ action = let(name, expr)
869
+ self.register(action)
870
+ runtime_expr = to_runtime_expr(expr)
871
+ self._add_decls(runtime_expr)
872
+ return cast(
873
+ "BASE_EXPR",
874
+ RuntimeExpr.__from_values__(
875
+ self.__egg_decls__, TypedExprDecl(runtime_expr.__egg_typed_expr__.tp, LetRefDecl(name))
876
+ ),
877
+ )
878
+
879
+ def include(self, path: str) -> None:
880
+ """
881
+ Include a file of rules.
882
+ """
883
+ msg = "Not implemented yet, because we don't have a way of registering the types with Python"
884
+ raise NotImplementedError(msg)
885
+
886
+ def output(self) -> None:
887
+ msg = "Not imeplemented yet, because there are no examples in the egglog repo"
888
+ raise NotImplementedError(msg)
889
+
890
+ @overload
891
+ def run(self, limit: int, /, *until: Fact, ruleset: Ruleset | None = None) -> bindings.RunReport: ...
892
+
893
+ @overload
894
+ def run(self, schedule: Schedule, /) -> bindings.RunReport: ...
895
+
896
+ def run(
897
+ self, limit_or_schedule: int | Schedule, /, *until: Fact, ruleset: Ruleset | None = None
898
+ ) -> bindings.RunReport:
899
+ """
900
+ Run the egraph until the given limit or until the given facts are true.
901
+ """
902
+ if isinstance(limit_or_schedule, int):
903
+ limit_or_schedule = run(ruleset, *until) * limit_or_schedule
904
+ return self._run_schedule(limit_or_schedule)
905
+
906
+ def _run_schedule(self, schedule: Schedule) -> bindings.RunReport:
907
+ self._add_decls(schedule)
908
+ egg_schedule = self._state.schedule_to_egg(schedule.schedule)
909
+ (command_output,) = self._egraph.run_program(bindings.RunSchedule(egg_schedule))
910
+ assert isinstance(command_output, bindings.RunScheduleOutput)
911
+ return command_output.report
912
+
913
+ def stats(self) -> bindings.RunReport:
914
+ """
915
+ Returns the overall run report for the egraph.
916
+ """
917
+ (output,) = self._egraph.run_program(bindings.PrintOverallStatistics())
918
+ assert isinstance(output, bindings.OverallStatistics)
919
+ return output.report
920
+
921
+ def check_bool(self, *facts: FactLike) -> bool:
922
+ """
923
+ Returns true if the facts are true in the egraph.
924
+ """
925
+ try:
926
+ self.check(*facts)
927
+ # TODO: Make a separate exception class for this
928
+ except Exception as e:
929
+ if "Check failed" in str(e):
930
+ return False
931
+ raise
932
+ return True
933
+
934
+ def check(self, *facts: FactLike) -> None:
935
+ """
936
+ Check if a fact is true in the egraph.
937
+ """
938
+ self._egraph.run_program(self._facts_to_check(facts))
939
+
940
+ def check_fail(self, *facts: FactLike) -> None:
941
+ """
942
+ Checks that one of the facts is not true
943
+ """
944
+ self._egraph.run_program(bindings.Fail(span(1), self._facts_to_check(facts)))
945
+
946
+ def _facts_to_check(self, fact_likes: Iterable[FactLike]) -> bindings.Check:
947
+ facts = _fact_likes(fact_likes)
948
+ self._add_decls(*facts)
949
+ egg_facts = [self._state.fact_to_egg(f.fact) for f in _fact_likes(facts)]
950
+ return bindings.Check(span(2), egg_facts)
951
+
952
+ @overload
953
+ def extract(self, expr: BASE_EXPR, /, include_cost: Literal[False] = False) -> BASE_EXPR: ...
954
+
955
+ @overload
956
+ def extract(self, expr: BASE_EXPR, /, include_cost: Literal[True]) -> tuple[BASE_EXPR, int]: ...
957
+
958
+ def extract(self, expr: BASE_EXPR, include_cost: bool = False) -> BASE_EXPR | tuple[BASE_EXPR, int]:
959
+ """
960
+ Extract the lowest cost expression from the egraph.
961
+ """
962
+ runtime_expr = to_runtime_expr(expr)
963
+ extract_report = self._run_extract(runtime_expr, 0)
964
+ assert isinstance(extract_report, bindings.ExtractBest)
965
+ res = self._from_termdag(extract_report.termdag, extract_report.term, runtime_expr.__egg_typed_expr__.tp)
966
+ if include_cost:
967
+ return res, extract_report.cost
968
+ return res
969
+
970
+ def _from_termdag(self, termdag: bindings.TermDag, term: bindings._Term, tp: JustTypeRef) -> Any:
971
+ (new_typed_expr,) = self._state.exprs_from_egg(termdag, [term], tp)
972
+ return RuntimeExpr.__from_values__(self.__egg_decls__, new_typed_expr)
973
+
974
+ def extract_multiple(self, expr: BASE_EXPR, n: int) -> list[BASE_EXPR]:
975
+ """
976
+ Extract multiple expressions from the egraph.
977
+ """
978
+ runtime_expr = to_runtime_expr(expr)
979
+ extract_report = self._run_extract(runtime_expr, n)
980
+ assert isinstance(extract_report, bindings.ExtractVariants)
981
+ new_exprs = self._state.exprs_from_egg(
982
+ extract_report.termdag, extract_report.terms, runtime_expr.__egg_typed_expr__.tp
983
+ )
984
+ return [cast("BASE_EXPR", RuntimeExpr.__from_values__(self.__egg_decls__, expr)) for expr in new_exprs]
985
+
986
+ def _run_extract(self, expr: RuntimeExpr, n: int) -> bindings._CommandOutput:
987
+ self._add_decls(expr)
988
+ expr = self._state.typed_expr_to_egg(expr.__egg_typed_expr__)
989
+ # If we have defined any cost tables use the custom extraction
990
+ args = (expr, bindings.Lit(span(2), bindings.Int(n)))
991
+ if self._state.cost_callables:
992
+ cmd: bindings._Command = bindings.UserDefined(span(2), "extract", list(args))
993
+ else:
994
+ cmd = bindings.Extract(span(2), *args)
995
+ try:
996
+ return self._egraph.run_program(cmd)[0]
997
+ except BaseException as e:
998
+ raise add_note("Extracting: " + str(expr), e) # noqa: B904
999
+
1000
+ def push(self) -> None:
1001
+ """
1002
+ Push the current state of the egraph, so that it can be popped later and reverted back.
1003
+ """
1004
+ self._egraph.run_program(bindings.Push(1))
1005
+ self._state_stack.append(self._state)
1006
+ self._state = self._state.copy()
1007
+
1008
+ def pop(self) -> None:
1009
+ """
1010
+ Pop the current state of the egraph, reverting back to the previous state.
1011
+ """
1012
+ self._egraph.run_program(bindings.Pop(span(1), 1))
1013
+ self._state = self._state_stack.pop()
1014
+
1015
+ def __enter__(self) -> Self:
1016
+ """
1017
+ Copy the egraph state, so that it can be reverted back to the original state at the end.
1018
+
1019
+ Also sets the current egraph to this one.
1020
+ """
1021
+ self.push()
1022
+ return self
1023
+
1024
+ def __exit__(self, exc_type, exc, exc_tb) -> None:
1025
+ self.pop()
1026
+
1027
+ def _serialize(
1028
+ self,
1029
+ **kwargs: Unpack[GraphvizKwargs],
1030
+ ) -> bindings.SerializedEGraph:
1031
+ max_functions = kwargs.pop("max_functions", None)
1032
+ max_calls_per_function = kwargs.pop("max_calls_per_function", None)
1033
+ split_primitive_outputs = kwargs.pop("split_primitive_outputs", True)
1034
+ split_functions = kwargs.pop("split_functions", [])
1035
+ include_temporary_functions = kwargs.pop("include_temporary_functions", False)
1036
+ n_inline_leaves = kwargs.pop("n_inline_leaves", 1)
1037
+ serialized = self._egraph.serialize(
1038
+ [],
1039
+ max_functions=max_functions,
1040
+ max_calls_per_function=max_calls_per_function,
1041
+ include_temporary_functions=include_temporary_functions,
1042
+ )
1043
+ if serialized.discarded_functions:
1044
+ msg = ", ".join(set(self._state.possible_egglog_functions(serialized.discarded_functions)))
1045
+ warn(f"Omitted: {msg}", stacklevel=3)
1046
+ if serialized.truncated_functions:
1047
+ msg = ", ".join(set(self._state.possible_egglog_functions(serialized.truncated_functions)))
1048
+ warn(f"Truncated: {msg}", stacklevel=3)
1049
+ if split_primitive_outputs or split_functions:
1050
+ additional_ops = {self._callable_to_egg(f)[1] for f in split_functions}
1051
+ serialized.split_classes(self._egraph, additional_ops)
1052
+ serialized.map_ops(self._state.op_mapping())
1053
+
1054
+ for _ in range(n_inline_leaves):
1055
+ serialized.inline_leaves()
1056
+
1057
+ return serialized
1058
+
1059
+ def _graphviz(self, **kwargs: Unpack[GraphvizKwargs]) -> graphviz.Source:
1060
+ serialized = self._serialize(**kwargs)
1061
+
1062
+ original = serialized.to_dot()
1063
+ # Add link to stylesheet to the graph, so that edges light up on hover
1064
+ # https://gist.github.com/sverweij/93e324f67310f66a8f5da5c2abe94682
1065
+ styles = """/* the lines within the edges */
1066
+ .edge:active path,
1067
+ .edge:hover path {
1068
+ stroke: fuchsia;
1069
+ stroke-width: 3;
1070
+ stroke-opacity: 1;
1071
+ }
1072
+ /* arrows are typically drawn with a polygon */
1073
+ .edge:active polygon,
1074
+ .edge:hover polygon {
1075
+ stroke: fuchsia;
1076
+ stroke-width: 3;
1077
+ fill: fuchsia;
1078
+ stroke-opacity: 1;
1079
+ fill-opacity: 1;
1080
+ }
1081
+ /* If you happen to have text and want to color that as well... */
1082
+ .edge:active text,
1083
+ .edge:hover text {
1084
+ fill: fuchsia;
1085
+ }"""
1086
+ p = pathlib.Path(tempfile.gettempdir()) / "graphviz-styles.css"
1087
+ p.write_text(styles)
1088
+ with_stylesheet = original.replace("{", f'{{stylesheet="{p!s}"', 1)
1089
+ return graphviz.Source(with_stylesheet)
1090
+
1091
+ def display(self, graphviz: bool = False, **kwargs: Unpack[GraphvizKwargs]) -> None:
1092
+ """
1093
+ Displays the e-graph.
1094
+
1095
+ If in IPython it will display it inline, otherwise it will write it to a file and open it.
1096
+ """
1097
+ from IPython.display import SVG, display # noqa: PLC0415
1098
+
1099
+ from .visualizer_widget import VisualizerWidget # noqa: PLC0415
1100
+
1101
+ if graphviz:
1102
+ if IN_IPYTHON:
1103
+ svg = self._graphviz(**kwargs).pipe(format="svg", quiet=True, encoding="utf-8")
1104
+ display(SVG(svg))
1105
+ else:
1106
+ self._graphviz(**kwargs).render(view=True, format="svg", quiet=True)
1107
+ else:
1108
+ serialized = self._serialize(**kwargs)
1109
+ VisualizerWidget(egraphs=[serialized.to_json()]).display_or_open()
1110
+
1111
+ def saturate(
1112
+ self,
1113
+ schedule: Schedule | None = None,
1114
+ *,
1115
+ expr: Expr | None = None,
1116
+ max: int = 1000,
1117
+ visualize: bool = True,
1118
+ **kwargs: Unpack[GraphvizKwargs],
1119
+ ) -> None:
1120
+ """
1121
+ Saturate the egraph, running the given schedule until the egraph is saturated.
1122
+ It serializes the egraph at each step and returns a widget to visualize the egraph.
1123
+
1124
+ If an `expr` is passed, it's also extracted after each run and printed
1125
+ """
1126
+ from .visualizer_widget import VisualizerWidget # noqa: PLC0415
1127
+
1128
+ def to_json() -> str:
1129
+ if expr is not None:
1130
+ print(self.extract(expr), "\n")
1131
+ return self._serialize(**kwargs).to_json()
1132
+
1133
+ if visualize:
1134
+ egraphs = [to_json()]
1135
+ i = 0
1136
+ # Always visualize, even if we encounter an error
1137
+ try:
1138
+ while (self.run(schedule or 1).updated) and i < max:
1139
+ i += 1
1140
+ if visualize:
1141
+ egraphs.append(to_json())
1142
+ except:
1143
+ if visualize:
1144
+ egraphs.append(to_json())
1145
+ raise
1146
+ finally:
1147
+ if visualize:
1148
+ VisualizerWidget(egraphs=egraphs).display_or_open()
1149
+
1150
+ @property
1151
+ def _egraph(self) -> bindings.EGraph:
1152
+ return self._state.egraph
1153
+
1154
+ @property
1155
+ def __egg_decls__(self) -> Declarations:
1156
+ return self._state.__egg_decls__
1157
+
1158
+ def register(
1159
+ self,
1160
+ /,
1161
+ command_or_generator: ActionLike | RewriteOrRule | RewriteOrRuleGenerator,
1162
+ *command_likes: ActionLike | RewriteOrRule,
1163
+ ) -> None:
1164
+ """
1165
+ Registers any number of rewrites or rules.
1166
+ """
1167
+ if isinstance(command_or_generator, FunctionType):
1168
+ assert not command_likes
1169
+ current_frame = inspect.currentframe()
1170
+ assert current_frame
1171
+ original_frame = current_frame.f_back
1172
+ assert original_frame
1173
+ command_likes = tuple(_rewrite_or_rule_generator(command_or_generator, original_frame))
1174
+ else:
1175
+ command_likes = (cast("CommandLike", command_or_generator), *command_likes)
1176
+ commands = [_command_like(c) for c in command_likes]
1177
+ self._register_commands(commands)
1178
+
1179
+ def _register_commands(self, cmds: list[Command]) -> None:
1180
+ self._add_decls(*cmds)
1181
+ egg_cmds = [egg_cmd for cmd in cmds if (egg_cmd := self._command_to_egg(cmd)) is not None]
1182
+ self._egraph.run_program(*egg_cmds)
1183
+
1184
+ def _command_to_egg(self, cmd: Command) -> bindings._Command | None:
1185
+ ruleset_name = ""
1186
+ cmd_decl: CommandDecl
1187
+ match cmd:
1188
+ case RewriteOrRule(_, cmd_decl, ruleset):
1189
+ if ruleset:
1190
+ ruleset_name = ruleset.__egg_name__
1191
+ case Action(_, action):
1192
+ cmd_decl = ActionCommandDecl(action)
1193
+ case _:
1194
+ assert_never(cmd)
1195
+ return self._state.command_to_egg(cmd_decl, ruleset_name)
1196
+
1197
+ def function_size(self, fn: ExprCallable) -> int:
1198
+ """
1199
+ Returns the number of rows in a certain function
1200
+ """
1201
+ egg_name = self._callable_to_egg(fn)[1]
1202
+ (output,) = self._egraph.run_program(bindings.PrintSize(span(1), egg_name))
1203
+ assert isinstance(output, bindings.PrintFunctionSize)
1204
+ return output.size
1205
+
1206
+ def all_function_sizes(self) -> list[tuple[ExprCallable, int]]:
1207
+ """
1208
+ Returns a list of all functions and their sizes.
1209
+ """
1210
+ (output,) = self._egraph.run_program(bindings.PrintSize(span(1), None))
1211
+ assert isinstance(output, bindings.PrintAllFunctionsSize)
1212
+ return [
1213
+ (
1214
+ cast(
1215
+ "ExprCallable",
1216
+ create_callable(self._state.__egg_decls__, next(iter(refs))),
1217
+ ),
1218
+ size,
1219
+ )
1220
+ for (name, size) in output.sizes
1221
+ if (refs := self._state.egg_fn_to_callable_refs[name])
1222
+ ]
1223
+
1224
+ def function_values(
1225
+ self, fn: Callable[..., BASE_EXPR] | BASE_EXPR, length: int | None = None
1226
+ ) -> dict[BASE_EXPR, BASE_EXPR]:
1227
+ """
1228
+ Given a callable that is a "function", meaning it returns a primitive or has a merge set,
1229
+ returns a mapping of the function applied with its arguments to its values
1230
+
1231
+ If length is specified, only the first `length` values will be returned.
1232
+ """
1233
+ ref, egg_name = self._callable_to_egg(fn)
1234
+ cmd = bindings.PrintFunction(span(1), egg_name, length, None, bindings.DefaultPrintFunctionMode())
1235
+ (output,) = self._egraph.run_program(cmd)
1236
+ assert isinstance(output, bindings.PrintFunctionOutput)
1237
+ signature = self.__egg_decls__.get_callable_decl(ref).signature
1238
+ assert isinstance(signature, FunctionSignature)
1239
+ tp = signature.semantic_return_type.to_just()
1240
+ return {
1241
+ self._from_termdag(output.termdag, call, tp): self._from_termdag(output.termdag, res, tp)
1242
+ for (call, res) in output.terms
1243
+ }
1244
+
1245
+
1246
+ # Either a constant or a function.
1247
+ ExprCallable: TypeAlias = Callable[..., BaseExpr] | BaseExpr
1248
+
1249
+
1250
+ @dataclass(frozen=True)
1251
+ class _WrappedMethod:
1252
+ """
1253
+ Used to wrap a method and store some extra options on it before processing it when processing the class.
1254
+ """
1255
+
1256
+ egg_fn: str | None
1257
+ cost: int | None
1258
+ merge: Callable[[object, object], object] | None
1259
+ fn: Callable
1260
+ preserve: bool
1261
+ mutates_self: bool
1262
+ unextractable: bool
1263
+ subsume: bool
1264
+ reverse_args: bool
1265
+
1266
+ def __call__(self, *args, **kwargs) -> Never:
1267
+ msg = "We should never call a wrapped method. Did you forget to wrap the class?"
1268
+ raise NotImplementedError(msg)
1269
+
1270
+
1271
+ def ruleset(
1272
+ rule_or_generator: RewriteOrRule | RewriteOrRuleGenerator | None = None,
1273
+ *rules: RewriteOrRule,
1274
+ name: None | str = None,
1275
+ ) -> Ruleset:
1276
+ """
1277
+ Creates a ruleset with the following rules.
1278
+
1279
+ If no name is provided, try using the name of the funciton.
1280
+ """
1281
+ if isinstance(rule_or_generator, FunctionType):
1282
+ name = name or rule_or_generator.__name__
1283
+ r = Ruleset(name)
1284
+ if rule_or_generator is not None:
1285
+ r.register(rule_or_generator, *rules, _increase_frame=True)
1286
+ return r
1287
+
1288
+
1289
+ @dataclass
1290
+ class Schedule(DelayedDeclerations):
1291
+ """
1292
+ A composition of some rulesets, either composing them sequentially, running them repeatedly, running them till saturation, or running until some facts are met
1293
+ """
1294
+
1295
+ # Defer declerations so that we can have rule generators that used not yet defined yet
1296
+ schedule: ScheduleDecl
1297
+
1298
+ def __str__(self) -> str:
1299
+ return pretty_decl(self.__egg_decls__, self.schedule)
1300
+
1301
+ def __repr__(self) -> str:
1302
+ return str(self)
1303
+
1304
+ def __mul__(self, length: int) -> Schedule:
1305
+ """
1306
+ Repeat the schedule a number of times.
1307
+ """
1308
+ return Schedule(self.__egg_decls_thunk__, RepeatDecl(self.schedule, length))
1309
+
1310
+ def saturate(self) -> Schedule:
1311
+ """
1312
+ Run the schedule until the e-graph is saturated.
1313
+ """
1314
+ return Schedule(self.__egg_decls_thunk__, SaturateDecl(self.schedule))
1315
+
1316
+ def __add__(self, other: Schedule) -> Schedule:
1317
+ """
1318
+ Run two schedules in sequence.
1319
+ """
1320
+ return Schedule(Thunk.fn(Declarations.create, self, other), SequenceDecl((self.schedule, other.schedule)))
1321
+
1322
+
1323
+ @dataclass
1324
+ class Ruleset(Schedule):
1325
+ """
1326
+ A collection of rules, which can be run as a schedule.
1327
+ """
1328
+
1329
+ __egg_decls_thunk__: Callable[[], Declarations] = field(init=False)
1330
+ schedule: RunDecl = field(init=False)
1331
+ name: str | None
1332
+
1333
+ # Current declerations we have accumulated
1334
+ _current_egg_decls: Declarations = field(default_factory=Declarations)
1335
+ # Current rulesets we have accumulated
1336
+ __egg_ruleset__: RulesetDecl = field(init=False)
1337
+ # Rule generator functions that have been deferred, to allow for late type binding
1338
+ deferred_rule_gens: list[Callable[[], Iterable[RewriteOrRule]]] = field(default_factory=list)
1339
+
1340
+ def __post_init__(self) -> None:
1341
+ self.schedule = RunDecl(self.__egg_name__, ())
1342
+ self.__egg_ruleset__ = self._current_egg_decls._rulesets[self.__egg_name__] = RulesetDecl([])
1343
+ self.__egg_decls_thunk__ = self._update_egg_decls
1344
+
1345
+ def _update_egg_decls(self) -> Declarations:
1346
+ """
1347
+ To return the egg decls, we go through our deferred rules and add any we haven't yet
1348
+ """
1349
+ while self.deferred_rule_gens:
1350
+ with set_current_ruleset(self):
1351
+ rules = self.deferred_rule_gens.pop()()
1352
+ self._current_egg_decls.update(*rules)
1353
+ self.__egg_ruleset__.rules.extend(r.decl for r in rules)
1354
+ return self._current_egg_decls
1355
+
1356
+ def append(self, rule: RewriteOrRule) -> None:
1357
+ """
1358
+ Register a rule with the ruleset.
1359
+ """
1360
+ self._current_egg_decls |= rule
1361
+ self.__egg_ruleset__.rules.append(rule.decl)
1362
+
1363
+ def register(
1364
+ self,
1365
+ /,
1366
+ rule_or_generator: RewriteOrRule | RewriteOrRuleGenerator,
1367
+ *rules: RewriteOrRule,
1368
+ _increase_frame: bool = False,
1369
+ ) -> None:
1370
+ """
1371
+ Register rewrites or rules, either as a function or as values.
1372
+ """
1373
+ if isinstance(rule_or_generator, RewriteOrRule):
1374
+ self.append(rule_or_generator)
1375
+ for r in rules:
1376
+ self.append(r)
1377
+ else:
1378
+ assert not rules
1379
+ current_frame = inspect.currentframe()
1380
+ assert current_frame
1381
+ original_frame = current_frame.f_back
1382
+ assert original_frame
1383
+ if _increase_frame:
1384
+ original_frame = original_frame.f_back
1385
+ assert original_frame
1386
+ self.deferred_rule_gens.append(Thunk.fn(_rewrite_or_rule_generator, rule_or_generator, original_frame))
1387
+
1388
+ def __str__(self) -> str:
1389
+ return pretty_decl(self._current_egg_decls, self.__egg_ruleset__, ruleset_name=self.name)
1390
+
1391
+ def __repr__(self) -> str:
1392
+ return str(self)
1393
+
1394
+ def __or__(self, other: Ruleset | UnstableCombinedRuleset) -> UnstableCombinedRuleset:
1395
+ return unstable_combine_rulesets(self, other)
1396
+
1397
+ # Create a unique name if we didn't pass one from the user
1398
+ @property
1399
+ def __egg_name__(self) -> str:
1400
+ return self.name or f"ruleset_{id(self)}"
1401
+
1402
+
1403
+ @dataclass
1404
+ class UnstableCombinedRuleset(Schedule):
1405
+ __egg_decls_thunk__: Callable[[], Declarations] = field(init=False)
1406
+ schedule: RunDecl = field(init=False)
1407
+ name: str | None
1408
+ rulesets: InitVar[list[Ruleset | UnstableCombinedRuleset]]
1409
+
1410
+ def __post_init__(self, rulesets: list[Ruleset | UnstableCombinedRuleset]) -> None:
1411
+ self.schedule = RunDecl(self.__egg_name__, ())
1412
+ # Don't use thunk so that this is re-evaluated each time its requsted, so that additions inside will
1413
+ # be added after its been evaluated once.
1414
+ self.__egg_decls_thunk__ = partial(self._create_egg_decls, *rulesets)
1415
+
1416
+ @property
1417
+ def __egg_name__(self) -> str:
1418
+ return self.name or f"combined_ruleset_{id(self)}"
1419
+
1420
+ def _create_egg_decls(self, *rulesets: Ruleset | UnstableCombinedRuleset) -> Declarations:
1421
+ decls = Declarations.create(*rulesets)
1422
+ decls._rulesets[self.__egg_name__] = CombinedRulesetDecl(tuple(r.__egg_name__ for r in rulesets))
1423
+ return decls
1424
+
1425
+ def __or__(self, other: Ruleset | UnstableCombinedRuleset) -> UnstableCombinedRuleset:
1426
+ return unstable_combine_rulesets(self, other)
1427
+
1428
+
1429
+ def unstable_combine_rulesets(
1430
+ *rulesets: Ruleset | UnstableCombinedRuleset, name: str | None = None
1431
+ ) -> UnstableCombinedRuleset:
1432
+ """
1433
+ Combine multiple rulesets into a single ruleset.
1434
+ """
1435
+ return UnstableCombinedRuleset(name, list(rulesets))
1436
+
1437
+
1438
+ @dataclass
1439
+ class RewriteOrRule:
1440
+ __egg_decls__: Declarations
1441
+ decl: RewriteOrRuleDecl
1442
+ ruleset: Ruleset | None = None
1443
+
1444
+ def __str__(self) -> str:
1445
+ return pretty_decl(self.__egg_decls__, self.decl)
1446
+
1447
+ def __repr__(self) -> str:
1448
+ return str(self)
1449
+
1450
+
1451
+ @dataclass
1452
+ class Fact:
1453
+ """
1454
+ A query on an EGraph, either by an expression or an equivalence between multiple expressions.
1455
+ """
1456
+
1457
+ __egg_decls__: Declarations
1458
+ fact: FactDecl
1459
+
1460
+ def __str__(self) -> str:
1461
+ return pretty_decl(self.__egg_decls__, self.fact)
1462
+
1463
+ def __repr__(self) -> str:
1464
+ return str(self)
1465
+
1466
+ def __bool__(self) -> bool:
1467
+ """
1468
+ Returns True if the two sides of an equality are structurally equal.
1469
+ """
1470
+ match self.fact:
1471
+ case EqDecl(_, left, right):
1472
+ return left == right
1473
+ case ExprFactDecl(TypedExprDecl(_, CallDecl(FunctionRef("!="), (left_tp, right_tp)))):
1474
+ return left_tp != right_tp
1475
+ msg = f"Can only check equality for == or != not {self}"
1476
+ raise ValueError(msg)
1477
+
1478
+
1479
+ @dataclass
1480
+ class Action:
1481
+ """
1482
+ A change to an EGraph, either unioning multiple expressions, setting the value of a function call, deleting an expression, or panicing.
1483
+ """
1484
+
1485
+ __egg_decls__: Declarations
1486
+ action: ActionDecl
1487
+
1488
+ def __str__(self) -> str:
1489
+ return pretty_decl(self.__egg_decls__, self.action)
1490
+
1491
+ def __repr__(self) -> str:
1492
+ return str(self)
1493
+
1494
+
1495
+ # We use these builders so that when creating these structures we can type check
1496
+ # if the arguments are the same type of expression
1497
+
1498
+
1499
+ def rewrite(lhs: EXPR, ruleset: None = None, *, subsume: bool = False) -> _RewriteBuilder[EXPR]:
1500
+ """Rewrite the given expression to a new expression."""
1501
+ return _RewriteBuilder(lhs, ruleset, subsume)
1502
+
1503
+
1504
+ def birewrite(lhs: EXPR, ruleset: None = None) -> _BirewriteBuilder[EXPR]:
1505
+ """Rewrite the given expression to a new expression and vice versa."""
1506
+ return _BirewriteBuilder(lhs, ruleset)
1507
+
1508
+
1509
+ def eq(expr: BASE_EXPR) -> _EqBuilder[BASE_EXPR]:
1510
+ """Check if the given expression is equal to the given value."""
1511
+ return _EqBuilder(expr)
1512
+
1513
+
1514
+ def ne(expr: BASE_EXPR) -> _NeBuilder[BASE_EXPR]:
1515
+ """Check if the given expression is not equal to the given value."""
1516
+ return _NeBuilder(expr)
1517
+
1518
+
1519
+ def panic(message: str) -> Action:
1520
+ """Raise an error with the given message."""
1521
+ return Action(Declarations(), PanicDecl(message))
1522
+
1523
+
1524
+ def set_cost(expr: BaseExpr, cost: i64Like) -> Action:
1525
+ """Set the cost of the given expression."""
1526
+ from .builtins import i64 # noqa: PLC0415
1527
+
1528
+ expr_runtime = to_runtime_expr(expr)
1529
+ typed_expr_decl = expr_runtime.__egg_typed_expr__
1530
+ expr_decl = typed_expr_decl.expr
1531
+ assert isinstance(expr_decl, CallDecl), "Can only set cost of calls, not literals or vars"
1532
+ cost_decl = to_runtime_expr(convert(cost, i64)).__egg_typed_expr__.expr
1533
+ return Action(expr_runtime.__egg_decls__, SetCostDecl(typed_expr_decl.tp, expr_decl, cost_decl))
1534
+
1535
+
1536
+ def let(name: str, expr: BaseExpr) -> Action:
1537
+ """Create a let binding."""
1538
+ runtime_expr = to_runtime_expr(expr)
1539
+ return Action(runtime_expr.__egg_decls__, LetDecl(name, runtime_expr.__egg_typed_expr__))
1540
+
1541
+
1542
+ def expr_action(expr: BaseExpr) -> Action:
1543
+ runtime_expr = to_runtime_expr(expr)
1544
+ return Action(runtime_expr.__egg_decls__, ExprActionDecl(runtime_expr.__egg_typed_expr__))
1545
+
1546
+
1547
+ def delete(expr: BaseExpr) -> Action:
1548
+ """Create a delete expression."""
1549
+ runtime_expr = to_runtime_expr(expr)
1550
+ typed_expr = runtime_expr.__egg_typed_expr__
1551
+ call_decl = typed_expr.expr
1552
+ assert isinstance(call_decl, CallDecl), "Can only delete calls, not literals or vars"
1553
+ return Action(runtime_expr.__egg_decls__, ChangeDecl(typed_expr.tp, call_decl, "delete"))
1554
+
1555
+
1556
+ def subsume(expr: Expr) -> Action:
1557
+ """Subsume an expression so it cannot be matched against or extracted"""
1558
+ runtime_expr = to_runtime_expr(expr)
1559
+ typed_expr = runtime_expr.__egg_typed_expr__
1560
+ call_decl = typed_expr.expr
1561
+ assert isinstance(call_decl, CallDecl), "Can only subsume calls, not literals or vars"
1562
+ return Action(runtime_expr.__egg_decls__, ChangeDecl(typed_expr.tp, call_decl, "subsume"))
1563
+
1564
+
1565
+ def expr_fact(expr: BaseExpr) -> Fact:
1566
+ runtime_expr = to_runtime_expr(expr)
1567
+ return Fact(runtime_expr.__egg_decls__, ExprFactDecl(runtime_expr.__egg_typed_expr__))
1568
+
1569
+
1570
+ def union(lhs: EXPR) -> _UnionBuilder[EXPR]:
1571
+ """Create a union of the given expression."""
1572
+ return _UnionBuilder(lhs=lhs)
1573
+
1574
+
1575
+ def set_(lhs: BASE_EXPR) -> _SetBuilder[BASE_EXPR]:
1576
+ """Create a set of the given expression."""
1577
+ return _SetBuilder(lhs=lhs)
1578
+
1579
+
1580
+ def rule(*facts: FactLike, ruleset: None = None, name: str | None = None) -> _RuleBuilder:
1581
+ """Create a rule with the given facts."""
1582
+ return _RuleBuilder(facts=_fact_likes(facts), name=name, ruleset=ruleset)
1583
+
1584
+
1585
+ def var(name: str, bound: type[T], egg_name: str | None = None) -> T:
1586
+ """Create a new variable with the given name and type."""
1587
+ return cast("T", _var(name, bound, egg_name=egg_name))
1588
+
1589
+
1590
+ def _var(name: str, bound: object, egg_name: str | None) -> RuntimeExpr:
1591
+ """Create a new variable with the given name and type."""
1592
+ decls_like, type_ref = resolve_type_annotation(bound)
1593
+ return RuntimeExpr(
1594
+ Thunk.fn(Declarations.create, decls_like),
1595
+ Thunk.value(TypedExprDecl(type_ref.to_just(), UnboundVarDecl(name, egg_name))),
1596
+ )
1597
+
1598
+
1599
+ def vars_(names: str, bound: type[BASE_EXPR]) -> Iterable[BASE_EXPR]:
1600
+ """Create variables with the given names and type."""
1601
+ for name in names.split(" "):
1602
+ yield var(name, bound)
1603
+
1604
+
1605
+ @dataclass
1606
+ class _RewriteBuilder(Generic[EXPR]):
1607
+ lhs: EXPR
1608
+ ruleset: Ruleset | None
1609
+ subsume: bool
1610
+
1611
+ def to(self, rhs: EXPR, *conditions: FactLike) -> RewriteOrRule:
1612
+ lhs = to_runtime_expr(self.lhs)
1613
+ facts = _fact_likes(conditions)
1614
+ rhs = convert_to_same_type(rhs, lhs)
1615
+ rule = RewriteOrRule(
1616
+ Declarations.create(lhs, rhs, *facts, self.ruleset),
1617
+ RewriteDecl(
1618
+ lhs.__egg_typed_expr__.tp,
1619
+ lhs.__egg_typed_expr__.expr,
1620
+ rhs.__egg_typed_expr__.expr,
1621
+ tuple(f.fact for f in facts),
1622
+ self.subsume,
1623
+ ),
1624
+ )
1625
+ if self.ruleset:
1626
+ self.ruleset.append(rule)
1627
+ return rule
1628
+
1629
+ def __str__(self) -> str:
1630
+ lhs = to_runtime_expr(self.lhs)
1631
+ return lhs.__egg_pretty__("rewrite")
1632
+
1633
+
1634
+ @dataclass
1635
+ class _BirewriteBuilder(Generic[EXPR]):
1636
+ lhs: EXPR
1637
+ ruleset: Ruleset | None
1638
+
1639
+ def to(self, rhs: EXPR, *conditions: FactLike) -> RewriteOrRule:
1640
+ lhs = to_runtime_expr(self.lhs)
1641
+ facts = _fact_likes(conditions)
1642
+ rhs = convert_to_same_type(rhs, lhs)
1643
+ rule = RewriteOrRule(
1644
+ Declarations.create(lhs, rhs, *facts, self.ruleset),
1645
+ BiRewriteDecl(
1646
+ lhs.__egg_typed_expr__.tp,
1647
+ lhs.__egg_typed_expr__.expr,
1648
+ rhs.__egg_typed_expr__.expr,
1649
+ tuple(f.fact for f in facts),
1650
+ ),
1651
+ )
1652
+ if self.ruleset:
1653
+ self.ruleset.append(rule)
1654
+ return rule
1655
+
1656
+ def __str__(self) -> str:
1657
+ lhs = to_runtime_expr(self.lhs)
1658
+ return lhs.__egg_pretty__("birewrite")
1659
+
1660
+
1661
+ @dataclass
1662
+ class _EqBuilder(Generic[BASE_EXPR]):
1663
+ expr: BASE_EXPR
1664
+
1665
+ def to(self, other: BASE_EXPR) -> Fact:
1666
+ expr = to_runtime_expr(self.expr)
1667
+ other = convert_to_same_type(other, expr)
1668
+ return Fact(
1669
+ Declarations.create(expr, other),
1670
+ EqDecl(expr.__egg_typed_expr__.tp, expr.__egg_typed_expr__.expr, other.__egg_typed_expr__.expr),
1671
+ )
1672
+
1673
+ def __repr__(self) -> str:
1674
+ return str(self)
1675
+
1676
+ def __str__(self) -> str:
1677
+ expr = to_runtime_expr(self.expr)
1678
+ return expr.__egg_pretty__("eq")
1679
+
1680
+
1681
+ @dataclass
1682
+ class _NeBuilder(Generic[BASE_EXPR]):
1683
+ lhs: BASE_EXPR
1684
+
1685
+ def to(self, rhs: BASE_EXPR) -> Unit:
1686
+ from .builtins import Unit # noqa: PLC0415
1687
+
1688
+ lhs = to_runtime_expr(self.lhs)
1689
+ rhs = convert_to_same_type(rhs, lhs)
1690
+ res = RuntimeExpr.__from_values__(
1691
+ Declarations.create(cast("RuntimeClass", Unit), lhs, rhs),
1692
+ TypedExprDecl(
1693
+ JustTypeRef("Unit"), CallDecl(FunctionRef("!="), (lhs.__egg_typed_expr__, rhs.__egg_typed_expr__))
1694
+ ),
1695
+ )
1696
+ return cast("Unit", res)
1697
+
1698
+ def __repr__(self) -> str:
1699
+ return str(self)
1700
+
1701
+ def __str__(self) -> str:
1702
+ expr = to_runtime_expr(self.lhs)
1703
+ return expr.__egg_pretty__("ne")
1704
+
1705
+
1706
+ @dataclass
1707
+ class _SetBuilder(Generic[BASE_EXPR]):
1708
+ lhs: BASE_EXPR
1709
+
1710
+ def to(self, rhs: BASE_EXPR) -> Action:
1711
+ lhs = to_runtime_expr(self.lhs)
1712
+ rhs = convert_to_same_type(rhs, lhs)
1713
+ lhs_expr = lhs.__egg_typed_expr__.expr
1714
+ assert isinstance(lhs_expr, CallDecl), "Can only set function calls"
1715
+ return Action(
1716
+ Declarations.create(lhs, rhs),
1717
+ SetDecl(lhs.__egg_typed_expr__.tp, lhs_expr, rhs.__egg_typed_expr__.expr),
1718
+ )
1719
+
1720
+ def __repr__(self) -> str:
1721
+ return str(self)
1722
+
1723
+ def __str__(self) -> str:
1724
+ lhs = to_runtime_expr(self.lhs)
1725
+ return lhs.__egg_pretty__("set_")
1726
+
1727
+
1728
+ @dataclass
1729
+ class _UnionBuilder(Generic[EXPR]):
1730
+ lhs: EXPR
1731
+
1732
+ def with_(self, rhs: EXPR) -> Action:
1733
+ lhs = to_runtime_expr(self.lhs)
1734
+ rhs = convert_to_same_type(rhs, lhs)
1735
+ return Action(
1736
+ Declarations.create(lhs, rhs),
1737
+ UnionDecl(lhs.__egg_typed_expr__.tp, lhs.__egg_typed_expr__.expr, rhs.__egg_typed_expr__.expr),
1738
+ )
1739
+
1740
+ def __repr__(self) -> str:
1741
+ return str(self)
1742
+
1743
+ def __str__(self) -> str:
1744
+ lhs = to_runtime_expr(self.lhs)
1745
+ return lhs.__egg_pretty__("union")
1746
+
1747
+
1748
+ @dataclass
1749
+ class _RuleBuilder:
1750
+ facts: tuple[Fact, ...]
1751
+ name: str | None
1752
+ ruleset: Ruleset | None
1753
+
1754
+ def then(self, *actions: ActionLike) -> RewriteOrRule:
1755
+ actions = _action_likes(actions)
1756
+ rule = RewriteOrRule(
1757
+ Declarations.create(self.ruleset, *actions, *self.facts),
1758
+ RuleDecl(tuple(a.action for a in actions), tuple(f.fact for f in self.facts), self.name),
1759
+ )
1760
+ if self.ruleset:
1761
+ self.ruleset.append(rule)
1762
+ return rule
1763
+
1764
+ def __str__(self) -> str:
1765
+ # TODO: Figure out how to stringify rulebuilder that preserves statements
1766
+ args = list(map(str, self.facts))
1767
+ if self.name is not None:
1768
+ args.append(f"name={self.name}")
1769
+ if ruleset is not None:
1770
+ args.append(f"ruleset={self.ruleset}")
1771
+ return f"rule({', '.join(args)})"
1772
+
1773
+
1774
+ def expr_parts(expr: BaseExpr) -> TypedExprDecl:
1775
+ """
1776
+ Returns the underlying type and decleration of the expression. Useful for testing structural equality or debugging.
1777
+ """
1778
+ if not isinstance(expr, RuntimeExpr):
1779
+ raise TypeError(f"Expected a RuntimeExpr not {expr}")
1780
+ return expr.__egg_typed_expr__
1781
+
1782
+
1783
+ def to_runtime_expr(expr: BaseExpr) -> RuntimeExpr:
1784
+ if not isinstance(expr, RuntimeExpr):
1785
+ raise TypeError(f"Expected a RuntimeExpr not {expr}")
1786
+ return expr
1787
+
1788
+
1789
+ def run(ruleset: Ruleset | None = None, *until: FactLike) -> Schedule:
1790
+ """
1791
+ Create a run configuration.
1792
+ """
1793
+ facts = _fact_likes(until)
1794
+ return Schedule(
1795
+ Thunk.fn(Declarations.create, ruleset, *facts),
1796
+ RunDecl(ruleset.__egg_name__ if ruleset else "", tuple(f.fact for f in facts) or None),
1797
+ )
1798
+
1799
+
1800
+ def seq(*schedules: Schedule) -> Schedule:
1801
+ """
1802
+ Run a sequence of schedules.
1803
+ """
1804
+ return Schedule(Thunk.fn(Declarations.create, *schedules), SequenceDecl(tuple(s.schedule for s in schedules)))
1805
+
1806
+
1807
+ ActionLike: TypeAlias = Action | BaseExpr
1808
+
1809
+
1810
+ def _action_likes(action_likes: Iterable[ActionLike]) -> tuple[Action, ...]:
1811
+ return tuple(map(_action_like, action_likes))
1812
+
1813
+
1814
+ def _action_like(action_like: ActionLike) -> Action:
1815
+ if isinstance(action_like, Action):
1816
+ return action_like
1817
+ return expr_action(action_like)
1818
+
1819
+
1820
+ Command: TypeAlias = Action | RewriteOrRule
1821
+
1822
+ CommandLike: TypeAlias = ActionLike | RewriteOrRule
1823
+
1824
+
1825
+ def _command_like(command_like: CommandLike) -> Command:
1826
+ if isinstance(command_like, RewriteOrRule):
1827
+ return command_like
1828
+ return _action_like(command_like)
1829
+
1830
+
1831
+ RewriteOrRuleGenerator = Callable[..., Iterable[RewriteOrRule]]
1832
+
1833
+
1834
+ def _rewrite_or_rule_generator(gen: RewriteOrRuleGenerator, frame: FrameType) -> Iterable[RewriteOrRule]:
1835
+ """
1836
+ Returns a thunk which will call the function with variables of the type and name of the arguments.
1837
+ """
1838
+ # Need to manually pass in the frame locals from the generator, because otherwise classes defined within function
1839
+ # will not be available in the annotations
1840
+ # combine locals and globals so that they are the same dict. Otherwise get_type_hints will go through the wrong
1841
+ # path and give an error for the test
1842
+ # python/tests/test_no_import_star.py::test_no_import_star_rulesset
1843
+ combined = {**gen.__globals__, **frame.f_locals}
1844
+ hints = get_type_hints(gen, combined, combined)
1845
+ args = [_var(p.name, hints[p.name], egg_name=None) for p in signature(gen).parameters.values()]
1846
+ return list(gen(*args))
1847
+
1848
+
1849
+ FactLike = Fact | BaseExpr
1850
+
1851
+
1852
+ def _fact_likes(fact_likes: Iterable[FactLike]) -> tuple[Fact, ...]:
1853
+ return tuple(map(_fact_like, fact_likes))
1854
+
1855
+
1856
+ def _fact_like(fact_like: FactLike) -> Fact:
1857
+ if isinstance(fact_like, Fact):
1858
+ return fact_like
1859
+ return expr_fact(fact_like)
1860
+
1861
+
1862
+ _CURRENT_RULESET = ContextVar[Ruleset | None]("CURRENT_RULESET", default=None)
1863
+
1864
+
1865
+ def get_current_ruleset() -> Ruleset | None:
1866
+ return _CURRENT_RULESET.get()
1867
+
1868
+
1869
+ @contextlib.contextmanager
1870
+ def set_current_ruleset(r: Ruleset | None) -> Generator[None, None, None]:
1871
+ token: Token[Ruleset | None] = _CURRENT_RULESET.set(r)
1872
+ try:
1873
+ yield
1874
+ finally:
1875
+ _CURRENT_RULESET.reset(token)