-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathegraph.py
More file actions
1793 lines (1473 loc) · 58.6 KB
/
egraph.py
File metadata and controls
1793 lines (1473 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import contextlib
import inspect
import pathlib
import tempfile
from collections.abc import Callable, Generator, Iterable
from contextvars import ContextVar
from dataclasses import InitVar, dataclass, field
from functools import partial
from inspect import Parameter, currentframe, signature
from types import FrameType, FunctionType
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Generic,
Literal,
TypeAlias,
TypedDict,
TypeVar,
cast,
get_type_hints,
overload,
)
import graphviz
from typing_extensions import Never, ParamSpec, Self, Unpack, assert_never
from . import bindings
from .conversion import *
from .conversion import convert_to_same_type, resolve_literal
from .declarations import *
from .egraph_state import *
from .ipython_magic import IN_IPYTHON
from .pretty import pretty_decl
from .runtime import *
from .thunk import *
from .version_compat import *
if TYPE_CHECKING:
from .builtins import String, Unit
__all__ = [
"Action",
"BaseExpr",
"BuiltinExpr",
"Command",
"Command",
"EGraph",
"Expr",
"Fact",
"Fact",
"GraphvizKwargs",
"RewriteOrRule",
"Ruleset",
"Schedule",
"_BirewriteBuilder",
"_EqBuilder",
"_NeBuilder",
"_RewriteBuilder",
"_SetBuilder",
"_UnionBuilder",
"birewrite",
"check",
"check_eq",
"constant",
"delete",
"eq",
"expr_action",
"expr_fact",
"expr_parts",
"function",
"let",
"method",
"ne",
"panic",
"relation",
"rewrite",
"rule",
"ruleset",
"run",
"seq",
"set_",
"subsume",
"union",
"unstable_combine_rulesets",
"var",
"vars_",
]
T = TypeVar("T")
P = ParamSpec("P")
EXPR_TYPE = TypeVar("EXPR_TYPE", bound="type[Expr]")
BASE_EXPR_TYPE = TypeVar("BASE_EXPR_TYPE", bound="type[BaseExpr]")
EXPR = TypeVar("EXPR", bound="Expr")
BASE_EXPR = TypeVar("BASE_EXPR", bound="BaseExpr")
BE1 = TypeVar("BE1", bound="BaseExpr")
BE2 = TypeVar("BE2", bound="BaseExpr")
BE3 = TypeVar("BE3", bound="BaseExpr")
BE4 = TypeVar("BE4", bound="BaseExpr")
# Attributes which are sometimes added to classes by the interpreter or the dataclass decorator, or by ipython.
# We ignore these when inspecting the class.
IGNORED_ATTRIBUTES = {
"__module__",
"__doc__",
"__dict__",
"__weakref__",
"__orig_bases__",
"__annotations__",
"__hash__",
"__qualname__",
"__firstlineno__",
"__static_attributes__",
# Ignore all reflected binary method
*(f"__r{m[2:]}" for m in NUMERIC_BINARY_METHODS),
}
# special methods that return none and mutate self
ALWAYS_MUTATES_SELF = {"__setitem__", "__delitem__"}
# special methods which must return real python values instead of lazy expressions
ALWAYS_PRESERVED = {
"__repr__",
"__str__",
"__bytes__",
"__format__",
"__hash__",
"__bool__",
"__len__",
"__length_hint__",
"__iter__",
"__reversed__",
"__contains__",
"__index__",
"__bufer__",
}
def check_eq(x: BASE_EXPR, y: BASE_EXPR, schedule: Schedule | None = None, *, add_second=True, display=False) -> EGraph:
"""
Verifies that two expressions are equal after running the schedule.
If add_second is true, then the second expression is added to the egraph before running the schedule.
"""
egraph = EGraph()
x_var = egraph.let("__check_eq_x", x)
y_var: BASE_EXPR = egraph.let("__check_eq_y", y) if add_second else y
if schedule:
try:
egraph.run(schedule)
finally:
if display:
egraph.display()
fact = eq(x_var).to(y_var)
try:
egraph.check(fact)
except bindings.EggSmolError as err:
if display:
egraph.display()
raise add_note(
f"Failed:\n{eq(x).to(y)}\n\nExtracted:\n {eq(egraph.extract(x)).to(egraph.extract(y))})", err
) from None
return egraph
def check(x: FactLike, schedule: Schedule | None = None, *given: ActionLike) -> None:
"""
Verifies that the fact is true given some assumptions and after running the schedule.
"""
egraph = EGraph()
if given:
egraph.register(*given)
if schedule:
egraph.run(schedule)
egraph.check(x)
# We seperate the function and method overloads to make it simpler to know if we are modifying a function or method,
# So that we can add the functions eagerly to the registry and wait on the methods till we process the class.
CALLABLE = TypeVar("CALLABLE", bound=Callable)
CONSTRUCTOR_CALLABLE = TypeVar("CONSTRUCTOR_CALLABLE", bound=Callable[..., "Expr | None"])
EXPR_NONE = TypeVar("EXPR_NONE", bound="Expr | None")
BASE_EXPR_NONE = TypeVar("BASE_EXPR_NONE", bound="BaseExpr | None")
@overload
def method(
*,
preserve: Literal[True],
) -> Callable[[CALLABLE], CALLABLE]: ...
# function wihout merge
@overload
def method(
*,
egg_fn: str | None = ...,
reverse_args: bool = ...,
mutates_self: bool = ...,
) -> Callable[[CALLABLE], CALLABLE]: ...
# function
@overload
def method(
*,
egg_fn: str | None = ...,
merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = ...,
mutates_self: bool = ...,
) -> Callable[[Callable[P, BASE_EXPR]], Callable[P, BASE_EXPR]]: ...
# constructor
@overload
def method(
*,
egg_fn: str | None = ...,
cost: int | None = ...,
mutates_self: bool = ...,
unextractable: bool = ...,
subsume: bool = ...,
) -> Callable[[Callable[P, EXPR_NONE]], Callable[P, EXPR_NONE]]: ...
def method(
*,
egg_fn: str | None = None,
cost: int | None = None,
merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = None,
preserve: bool = False,
mutates_self: bool = False,
unextractable: bool = False,
subsume: bool = False,
reverse_args: bool = False,
) -> Callable[[Callable[P, BASE_EXPR_NONE]], Callable[P, BASE_EXPR_NONE]]:
"""
Any method can be decorated with this to customize it's behavior. This is only supported in classes which subclass :class:`Expr`.
"""
merge = cast("Callable[[object, object], object]", merge)
return lambda fn: _WrappedMethod(
egg_fn, cost, merge, fn, preserve, mutates_self, unextractable, subsume, reverse_args
)
@overload
def function(fn: CALLABLE, /) -> CALLABLE: ...
# function without merge
@overload
def function(
*,
egg_fn: str | None = ...,
builtin: bool = ...,
mutates_first_arg: bool = ...,
) -> Callable[[CALLABLE], CALLABLE]: ...
# function
@overload
def function(
*,
egg_fn: str | None = ...,
merge: Callable[[BASE_EXPR, BASE_EXPR], BASE_EXPR] | None = ...,
builtin: bool = ...,
mutates_first_arg: bool = ...,
) -> Callable[[Callable[P, BASE_EXPR]], Callable[P, BASE_EXPR]]: ...
# constructor
@overload
def function(
*,
egg_fn: str | None = ...,
cost: int | None = ...,
mutates_first_arg: bool = ...,
unextractable: bool = ...,
ruleset: Ruleset | None = ...,
subsume: bool = ...,
) -> Callable[[CONSTRUCTOR_CALLABLE], CONSTRUCTOR_CALLABLE]: ...
def function(*args, **kwargs) -> Any:
"""
Decorate a function typing stub to create an egglog function for it.
If a body is included, it will be added to the `ruleset` passed in as a default rewrite.
This will default to creating a "constructor" in egglog, unless a merge function is passed in or the return
type is a primtive, then it will be a "function".
"""
fn_locals = currentframe().f_back.f_locals # type: ignore[union-attr]
# If we have any positional args, then we are calling it directly on a function
if args:
assert len(args) == 1
return _FunctionConstructor(fn_locals)(args[0])
# otherwise, we are passing some keyword args, so save those, and then return a partial
return _FunctionConstructor(fn_locals, **kwargs)
class _ExprMetaclass(type):
"""
Metaclass of Expr.
Used to override isistance checks, so that runtime expressions are instances of Expr at runtime.
"""
def __new__( # type: ignore[misc]
cls: type[_ExprMetaclass],
name: str,
bases: tuple[type, ...],
namespace: dict[str, Any],
egg_sort: str | None = None,
ruleset: Ruleset | None = None,
) -> RuntimeClass | type:
# If this is the Expr subclass, just return the class
if not bases or bases == (BaseExpr,):
return super().__new__(cls, name, bases, namespace)
builtin = BuiltinExpr in bases
# TODO: Raise error on subclassing or multiple inheritence
frame = currentframe()
assert frame
prev_frame = frame.f_back
assert prev_frame
# Pass in an instance of the class so that when we are generating the decls
# we can update them eagerly so that we can access the methods in the class body
runtime_cls = RuntimeClass(None, TypeRefWithVars(name)) # type: ignore[arg-type]
# Store frame so that we can get live access to updated locals/globals
# Otherwise, f_locals returns a copy
# https://peps.python.org/pep-0667/
runtime_cls.__egg_decls_thunk__ = Thunk.fn(
_generate_class_decls,
namespace,
prev_frame,
builtin,
egg_sort,
name,
ruleset,
runtime_cls,
)
return runtime_cls
def __instancecheck__(cls, instance: object) -> bool:
return isinstance(instance, RuntimeExpr)
class BaseExpr(metaclass=_ExprMetaclass):
"""
Either a builtin or a user defined expression type.
"""
def __ne__(self, other: Self) -> Unit: ... # type: ignore[override, empty-body]
def __eq__(self, other: Self) -> Fact: ... # type: ignore[override, empty-body]
class BuiltinExpr(BaseExpr, metaclass=_ExprMetaclass):
"""
A builtin expr type, not an eqsort.
"""
class Expr(BaseExpr, metaclass=_ExprMetaclass):
"""
Subclass this to define a custom expression type.
"""
def _generate_class_decls( # noqa: C901,PLR0912
namespace: dict[str, Any],
frame: FrameType,
builtin: bool,
egg_sort: str | None,
cls_name: str,
ruleset: Ruleset | None,
runtime_cls: RuntimeClass,
) -> Declarations:
"""
Lazy constructor for class declerations to support classes with methods whose types are not yet defined.
"""
parameters: list[TypeVar] = (
# Get the generic params from the orig bases generic class
namespace["__orig_bases__"][1].__parameters__ if "__orig_bases__" in namespace else []
)
type_vars = tuple(ClassTypeVarRef.from_type_var(p) for p in parameters)
del parameters
cls_decl = ClassDecl(egg_sort, type_vars, builtin)
decls = Declarations(_classes={cls_name: cls_decl})
# Update class think eagerly when resolving so that lookups work in methods
runtime_cls.__egg_decls_thunk__ = Thunk.value(decls)
##
# Register class variables
##
# Create a dummy type to pass to get_type_hints to resolve the annotations we have
_Dummytype = type("_DummyType", (), {"__annotations__": namespace.get("__annotations__", {})})
for k, v in get_type_hints(_Dummytype, globalns=frame.f_globals, localns=frame.f_locals).items():
if getattr(v, "__origin__", None) == ClassVar:
(inner_tp,) = v.__args__
type_ref = resolve_type_annotation_mutate(decls, inner_tp)
cls_decl.class_variables[k] = ConstantDecl(type_ref.to_just())
_add_default_rewrite(
decls, ClassVariableRef(cls_name, k), type_ref, namespace.pop(k, None), ruleset, subsume=False
)
else:
msg = f"On class {cls_name}, for attribute '{k}', expected a ClassVar, but got {v}"
raise NotImplementedError(msg)
##
# Register methods, classmethods, preserved methods, and properties
##
# Get all the methods from the class
filtered_namespace: list[tuple[str, Any]] = [
(k, v) for k, v in namespace.items() if k not in IGNORED_ATTRIBUTES or isinstance(v, _WrappedMethod)
]
# all methods we should try adding default functions for
add_default_funcs: list[Callable[[], None]] = []
# Then register each of its methods
for method_name, method in filtered_namespace:
is_init = method_name == "__init__"
# Don't register the init methods for literals, since those don't use the type checking mechanisms
if is_init and cls_name in LIT_CLASS_NAMES:
continue
match method:
case _WrappedMethod(egg_fn, cost, merge, fn, preserve, mutates, unextractable, subsume, reverse_args):
pass
case _:
egg_fn, cost, merge = None, None, None
fn = method
unextractable, preserve, subsume = False, False, False
mutates = method_name in ALWAYS_MUTATES_SELF
reverse_args = False
if preserve:
cls_decl.preserved_methods[method_name] = fn
continue
locals = frame.f_locals
ref: ClassMethodRef | MethodRef | PropertyRef | InitRef
match fn:
case classmethod():
ref = ClassMethodRef(cls_name, method_name)
fn = fn.__func__
case property():
ref = PropertyRef(cls_name, method_name)
fn = fn.fget
case _:
ref = InitRef(cls_name) if is_init else MethodRef(cls_name, method_name)
if isinstance(fn, _WrappedMethod):
msg = f"{cls_name}.{method_name} Add the @method(...) decorator above @classmethod or @property"
raise ValueError(msg) # noqa: TRY004
special_function_name: SpecialFunctions | None = (
"fn-partial" if egg_fn == "unstable-fn" else "fn-app" if egg_fn == "unstable-app" else None
)
if special_function_name:
decl = FunctionDecl(special_function_name, builtin=True, egg_name=egg_fn)
decls.set_function_decl(ref, decl)
continue
try:
add_rewrite = _fn_decl(
decls,
egg_fn,
ref,
fn,
locals,
cost,
merge,
mutates,
builtin,
ruleset=ruleset,
unextractable=unextractable,
subsume=subsume,
reverse_args=reverse_args,
)
except Exception as e:
raise add_note(f"Error processing {cls_name}.{method_name}", e) from None
if not builtin and not isinstance(ref, InitRef) and not mutates:
add_default_funcs.append(add_rewrite)
# Add all rewrite methods at the end so that all methods are registered first and can be accessed
# in the bodies
for add_rewrite in add_default_funcs:
add_rewrite()
return decls
@dataclass
class _FunctionConstructor:
hint_locals: dict[str, Any]
builtin: bool = False
mutates_first_arg: bool = False
egg_fn: str | None = None
cost: int | None = None
merge: Callable[[object, object], object] | None = None
unextractable: bool = False
ruleset: Ruleset | None = None
subsume: bool = False
def __call__(self, fn: Callable) -> RuntimeFunction:
return RuntimeFunction(*split_thunk(Thunk.fn(self.create_decls, fn)))
def create_decls(self, fn: Callable) -> tuple[Declarations, CallableRef]:
decls = Declarations()
add_rewrite = _fn_decl(
decls,
self.egg_fn,
ref := FunctionRef(fn.__name__),
fn,
self.hint_locals,
self.cost,
self.merge,
self.mutates_first_arg,
self.builtin,
ruleset=self.ruleset,
subsume=self.subsume,
unextractable=self.unextractable,
)
add_rewrite()
return decls, ref
def _fn_decl(
decls: Declarations,
egg_name: str | None,
ref: FunctionRef | MethodRef | PropertyRef | ClassMethodRef | InitRef,
fn: object,
# Pass in the locals, retrieved from the frame when wrapping,
# so that we support classes and function defined inside of other functions (which won't show up in the globals)
hint_locals: dict[str, Any],
cost: int | None,
merge: Callable[[object, object], object] | None,
mutates_first_arg: bool,
is_builtin: bool,
subsume: bool,
ruleset: Ruleset | None = None,
unextractable: bool = False,
reverse_args: bool = False,
) -> Callable[[], None]:
"""
Sets the function decl for the function object and returns the ref as well as a thunk that sets the default callable.
"""
if isinstance(fn, RuntimeFunction):
msg = "Inside of classes, wrap methods with the `method` decorator, not `function`"
raise ValueError(msg) # noqa: TRY004
if not isinstance(fn, FunctionType):
raise NotImplementedError(f"Can only generate function decls for functions not {fn} {type(fn)}")
# Instead of passing both globals and locals, just pass the globals. Otherwise, for some reason forward references
# won't be resolved correctly
# We need this to be false so it returns "__forward_value__" https://github.com/python/cpython/blob/440ed18e08887b958ad50db1b823e692a747b671/Lib/typing.py#L919
# https://github.com/egraphs-good/egglog-python/issues/210
hint_globals = {**fn.__globals__, **hint_locals}
hints = get_type_hints(fn, hint_globals)
params = list(signature(fn).parameters.values())
# If this is an init function, or a classmethod, the first arg is not used
if isinstance(ref, ClassMethodRef | InitRef):
params = params[1:]
if _last_param_variable(params):
*params, var_arg_param = params
# For now, we don't use the variable arg name
var_arg_type = resolve_type_annotation_mutate(decls, hints[var_arg_param.name])
else:
var_arg_type = None
arg_types = tuple(
decls.get_paramaterized_class(ref.class_name)
if i == 0 and isinstance(ref, MethodRef | PropertyRef)
else resolve_type_annotation_mutate(decls, hints[t.name])
for i, t in enumerate(params)
)
# Resolve all default values as arg types
arg_defaults = [
resolve_literal(t, p.default, Thunk.value(decls)) if p.default is not Parameter.empty else None
for (t, p) in zip(arg_types, params, strict=True)
]
decls.update(*arg_defaults)
return_type = (
decls.get_paramaterized_class(ref.class_name)
if isinstance(ref, InitRef)
else arg_types[0]
if mutates_first_arg
else resolve_type_annotation_mutate(decls, hints["return"])
)
arg_names = tuple(t.name for t in params)
merged = (
None
if merge is None
else resolve_literal(
return_type,
merge(
RuntimeExpr.__from_values__(decls, TypedExprDecl(return_type.to_just(), UnboundVarDecl("old", "old"))),
RuntimeExpr.__from_values__(decls, TypedExprDecl(return_type.to_just(), UnboundVarDecl("new", "new"))),
),
lambda: decls,
)
)
decls |= merged
# defer this in generator so it doesn't resolve for builtins eagerly
args = (TypedExprDecl(tp.to_just(), UnboundVarDecl(name)) for name, tp in zip(arg_names, arg_types, strict=True))
return_type_is_eqsort = (
not decls._classes[return_type.name].builtin if isinstance(return_type, TypeRefWithVars) else False
)
is_constructor = not is_builtin and return_type_is_eqsort and merged is None
signature_ = FunctionSignature(
return_type=None if mutates_first_arg else return_type,
var_arg_type=var_arg_type,
arg_types=arg_types,
arg_names=arg_names,
arg_defaults=tuple(a.__egg_typed_expr__.expr if a is not None else None for a in arg_defaults),
reverse_args=reverse_args,
)
decl: ConstructorDecl | FunctionDecl
if is_constructor:
decl = ConstructorDecl(signature_, egg_name, cost, unextractable)
else:
if cost is not None:
msg = "Cost can only be set for constructors"
raise ValueError(msg)
if unextractable:
msg = "Unextractable can only be set for constructors"
raise ValueError(msg)
decl = FunctionDecl(
signature=signature_,
egg_name=egg_name,
merge=merged.__egg_typed_expr__.expr if merged is not None else None,
builtin=is_builtin,
)
decls.set_function_decl(ref, decl)
return Thunk.fn(
_add_default_rewrite_function, decls, ref, fn, args, ruleset, subsume, return_type, context=f"creating {ref}"
)
# Overload to support aritys 0-4 until variadic generic support map, so we can map from type to value
@overload
def relation(
name: str, tp1: type[BE1], tp2: type[BE2], tp3: type[BE3], tp4: type[BE4], /
) -> Callable[[BE1, BE2, BE3, BE4], Unit]: ...
@overload
def relation(name: str, tp1: type[BE1], tp2: type[BE2], tp3: type[BE3], /) -> Callable[[BE1, BE2, BE3], Unit]: ...
@overload
def relation(name: str, tp1: type[BE1], tp2: type[BE2], /) -> Callable[[BE1, BE2], Unit]: ...
@overload
def relation(name: str, tp1: type[BE1], /, *, egg_fn: str | None = None) -> Callable[[BE1], Unit]: ...
@overload
def relation(name: str, /, *, egg_fn: str | None = None) -> Callable[[], Unit]: ...
def relation(name: str, /, *tps: type, egg_fn: str | None = None) -> Callable[..., Unit]:
"""
Creates a function whose return type is `Unit` and has a default value.
"""
decls_thunk = Thunk.fn(_relation_decls, name, tps, egg_fn)
return cast("Callable[..., Unit]", RuntimeFunction(decls_thunk, Thunk.value(FunctionRef(name))))
def _relation_decls(name: str, tps: tuple[type, ...], egg_fn: str | None) -> Declarations:
from .builtins import Unit
decls = Declarations()
decls |= cast("RuntimeClass", Unit)
arg_types = tuple(resolve_type_annotation_mutate(decls, tp).to_just() for tp in tps)
decls._functions[name] = RelationDecl(arg_types, tuple(None for _ in tps), egg_fn)
return decls
def constant(
name: str,
tp: type[BASE_EXPR],
default_replacement: BASE_EXPR | None = None,
/,
*,
egg_name: str | None = None,
ruleset: Ruleset | None = None,
) -> BASE_EXPR:
"""
A "constant" is implemented as the instantiation of a value that takes no args.
This creates a function with `name` and return type `tp` and returns a value of it being called.
"""
return cast(
"BASE_EXPR",
RuntimeExpr(*split_thunk(Thunk.fn(_constant_thunk, name, tp, egg_name, default_replacement, ruleset))),
)
def _constant_thunk(
name: str, tp: type, egg_name: str | None, default_replacement: object, ruleset: Ruleset | None
) -> tuple[Declarations, TypedExprDecl]:
decls = Declarations()
type_ref = resolve_type_annotation_mutate(decls, tp)
callable_ref = ConstantRef(name)
decls._constants[name] = ConstantDecl(type_ref.to_just(), egg_name)
_add_default_rewrite(decls, callable_ref, type_ref, default_replacement, ruleset, subsume=False)
return decls, TypedExprDecl(type_ref.to_just(), CallDecl(callable_ref))
def _add_default_rewrite_function(
decls: Declarations,
ref: FunctionRef | MethodRef | PropertyRef | ClassMethodRef | InitRef,
fn: Callable,
args: Iterable[TypedExprDecl],
ruleset: Ruleset | None,
subsume: bool,
res_type: TypeOrVarRef,
) -> None:
args: list[object] = [RuntimeExpr.__from_values__(decls, a) for a in args]
# If this is a classmethod, add the class as the first arg
if isinstance(ref, ClassMethodRef):
tp = decls.get_paramaterized_class(ref.class_name)
args.insert(0, RuntimeClass(Thunk.value(decls), tp))
with set_current_ruleset(ruleset):
res = fn(*args)
_add_default_rewrite(decls, ref, res_type, res, ruleset, subsume)
def _add_default_rewrite(
decls: Declarations,
ref: CallableRef,
type_ref: TypeOrVarRef,
default_rewrite: object,
ruleset: Ruleset | None,
subsume: bool,
) -> None:
"""
Adds a default rewrite for the callable, if the default rewrite is not None
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.
"""
if default_rewrite is None:
return
resolved_value = resolve_literal(type_ref, default_rewrite, Thunk.value(decls))
rewrite_decl = DefaultRewriteDecl(ref, resolved_value.__egg_typed_expr__.expr, subsume)
ruleset_decls = _add_default_rewrite_inner(decls, rewrite_decl, ruleset)
ruleset_decls |= resolved_value
def _add_default_rewrite_inner(
decls: Declarations, rewrite_decl: DefaultRewriteDecl, ruleset: Ruleset | None
) -> Declarations:
if ruleset:
ruleset_decls = ruleset._current_egg_decls
ruleset_decl = ruleset.__egg_ruleset__
else:
ruleset_decls = decls
ruleset_decl = decls.default_ruleset
ruleset_decl.rules.append(rewrite_decl)
return ruleset_decls
def _last_param_variable(params: list[Parameter]) -> bool:
"""
Checks if the last paramater is a variable arg.
Raises an error if any of the other params are not positional or keyword.
"""
found_var_arg = False
for param in params:
if found_var_arg:
msg = "Can only have a single var arg at the end"
raise ValueError(msg)
kind = param.kind
if kind == Parameter.VAR_POSITIONAL:
found_var_arg = True
elif kind != Parameter.POSITIONAL_OR_KEYWORD:
raise ValueError(f"Can only register functions with positional or keyword args, not {param.kind}")
return found_var_arg
class GraphvizKwargs(TypedDict, total=False):
max_functions: int | None
max_calls_per_function: int | None
n_inline_leaves: int
split_primitive_outputs: bool
split_functions: list[object]
include_temporary_functions: bool
@dataclass
class EGraph:
"""
A collection of expressions where each expression is part of a distinct equivalence class.
Can run actions, check facts, run schedules, or extract minimal cost expressions.
"""
seminaive: InitVar[bool] = True
save_egglog_string: InitVar[bool] = False
_state: EGraphState = field(init=False, repr=False)
# For pushing/popping with egglog
_state_stack: list[EGraphState] = field(default_factory=list, repr=False)
# For storing the global "current" egraph
_token_stack: list[EGraph] = field(default_factory=list, repr=False)
def __post_init__(self, seminaive: bool, save_egglog_string: bool) -> None:
egraph = bindings.EGraph(GLOBAL_PY_OBJECT_SORT, seminaive=seminaive, record=save_egglog_string)
self._state = EGraphState(egraph)
def _add_decls(self, *decls: DeclerationsLike) -> None:
for d in decls:
self._state.__egg_decls__ |= d
@property
def as_egglog_string(self) -> str:
"""
Returns the egglog string for this module.
"""
cmds = self._egraph.commands()
if cmds is None:
msg = "Can't get egglog string unless EGraph created with save_egglog_string=True"
raise ValueError(msg)
return cmds
def _ipython_display_(self) -> None:
self.display()
def input(self, fn: Callable[..., String], path: str) -> None:
"""
Loads a CSV file and sets it as *input, output of the function.
"""
self._egraph.run_program(bindings.Input(span(1), self._callable_to_egg(fn), path))
def _callable_to_egg(self, fn: object) -> str:
ref, decls = resolve_callable(fn)
self._add_decls(decls)
return self._state.callable_ref_to_egg(ref)[0]
def let(self, name: str, expr: BASE_EXPR) -> BASE_EXPR:
"""
Define a new expression in the egraph and return a reference to it.
"""
action = let(name, expr)
self.register(action)
runtime_expr = to_runtime_expr(expr)
self._add_decls(runtime_expr)
return cast(
"BASE_EXPR",
RuntimeExpr.__from_values__(
self.__egg_decls__, TypedExprDecl(runtime_expr.__egg_typed_expr__.tp, LetRefDecl(name))
),
)
def include(self, path: str) -> None:
"""
Include a file of rules.
"""
msg = "Not implemented yet, because we don't have a way of registering the types with Python"
raise NotImplementedError(msg)
def output(self) -> None:
msg = "Not imeplemented yet, because there are no examples in the egglog repo"
raise NotImplementedError(msg)
@overload
def run(self, limit: int, /, *until: Fact, ruleset: Ruleset | None = None) -> bindings.RunReport: ...
@overload
def run(self, schedule: Schedule, /) -> bindings.RunReport: ...
def run(
self, limit_or_schedule: int | Schedule, /, *until: Fact, ruleset: Ruleset | None = None
) -> bindings.RunReport:
"""
Run the egraph until the given limit or until the given facts are true.
"""
if isinstance(limit_or_schedule, int):
limit_or_schedule = run(ruleset, *until) * limit_or_schedule
return self._run_schedule(limit_or_schedule)
def _run_schedule(self, schedule: Schedule) -> bindings.RunReport:
self._add_decls(schedule)
egg_schedule = self._state.schedule_to_egg(schedule.schedule)
self._egraph.run_program(bindings.RunSchedule(egg_schedule))
run_report = self._egraph.run_report()
if not run_report:
msg = "No run report saved"
raise ValueError(msg)
return run_report
def check_bool(self, *facts: FactLike) -> bool:
"""
Returns true if the facts are true in the egraph.
"""
try:
self.check(*facts)
# TODO: Make a separate exception class for this
except Exception as e:
if "Check failed" in str(e):
return False
raise
return True
def check(self, *facts: FactLike) -> None:
"""
Check if a fact is true in the egraph.
"""
self._egraph.run_program(self._facts_to_check(facts))
def check_fail(self, *facts: FactLike) -> None:
"""
Checks that one of the facts is not true
"""
self._egraph.run_program(bindings.Fail(span(1), self._facts_to_check(facts)))
def _facts_to_check(self, fact_likes: Iterable[FactLike]) -> bindings.Check:
facts = _fact_likes(fact_likes)
self._add_decls(*facts)
egg_facts = [self._state.fact_to_egg(f.fact) for f in _fact_likes(facts)]
return bindings.Check(span(2), egg_facts)
@overload
def extract(self, expr: BASE_EXPR, /, include_cost: Literal[False] = False) -> BASE_EXPR: ...
@overload
def extract(self, expr: BASE_EXPR, /, include_cost: Literal[True]) -> tuple[BASE_EXPR, int]: ...
def extract(self, expr: BASE_EXPR, include_cost: bool = False) -> BASE_EXPR | tuple[BASE_EXPR, int]:
"""
Extract the lowest cost expression from the egraph.
"""
runtime_expr = to_runtime_expr(expr)
extract_report = self._run_extract(runtime_expr, 0)
if not isinstance(extract_report, bindings.Best):
msg = "No extract report saved"
raise ValueError(msg) # noqa: TRY004
(new_typed_expr,) = self._state.exprs_from_egg(
extract_report.termdag, [extract_report.term], runtime_expr.__egg_typed_expr__.tp
)
res = cast("BASE_EXPR", RuntimeExpr.__from_values__(self.__egg_decls__, new_typed_expr))
if include_cost:
return res, extract_report.cost
return res
def extract_multiple(self, expr: BASE_EXPR, n: int) -> list[BASE_EXPR]:
"""
Extract multiple expressions from the egraph.
"""
runtime_expr = to_runtime_expr(expr)
extract_report = self._run_extract(runtime_expr, n)
if not isinstance(extract_report, bindings.Variants):
msg = "Wrong extract report type"
raise ValueError(msg) # noqa: TRY004
new_exprs = self._state.exprs_from_egg(
extract_report.termdag, extract_report.terms, runtime_expr.__egg_typed_expr__.tp
)
return [cast("BASE_EXPR", RuntimeExpr.__from_values__(self.__egg_decls__, expr)) for expr in new_exprs]
def _run_extract(self, expr: RuntimeExpr, n: int) -> bindings._ExtractReport:
self._add_decls(expr)
expr = self._state.typed_expr_to_egg(expr.__egg_typed_expr__)
try:
self._egraph.run_program(bindings.Extract(span(2), expr, bindings.Lit(span(2), bindings.Int(n))))
except BaseException as e:
raise add_note("Extracting: " + str(expr), e) # noqa: B904
extract_report = self._egraph.extract_report()
if not extract_report:
msg = "No extract report saved"
raise ValueError(msg)
return extract_report
def push(self) -> None:
"""
Push the current state of the egraph, so that it can be popped later and reverted back.
"""
self._egraph.run_program(bindings.Push(1))
self._state_stack.append(self._state)
self._state = self._state.copy()
def pop(self) -> None: