egglog 9.0.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

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