forked from egraphs-good/egglog-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_high_level.py
More file actions
1573 lines (1123 loc) · 40.6 KB
/
Copy pathtest_high_level.py
File metadata and controls
1573 lines (1123 loc) · 40.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
# mypy: disable-error-code="empty-body"
from __future__ import annotations
import importlib
import pathlib
from collections.abc import Iterator
from copy import copy
from fractions import Fraction
from functools import partial
from typing import ClassVar, TypeAlias, TypeVar, cast
from unittest.mock import MagicMock
import pytest
from egglog import *
from egglog.declarations import CallDecl, FunctionRef, Ident, JustTypeRef, MethodRef, TypedExprDecl
from egglog.runtime import RuntimeExpr, RuntimeFunction
class TestExprStr:
def test_unwrap_lit(self):
assert str(i64(1) + 1) == "i64(1) + 1"
assert str(i64(1).max(2)) == "i64(1).max(2)"
def test_ne(self):
assert str(ne(i64(1)).to(i64(2))) == "ne(i64(1)).to(i64(2))"
def test_eqsat_basic():
egraph = EGraph()
class Math(Expr):
def __init__(self, value: i64Like) -> None: ...
@classmethod
def var(cls, v: StringLike) -> Math: ...
def __add__(self, other: Math) -> Math: ...
def __mul__(self, other: Math) -> Math: ...
# expr1 = 2 * (x + 3)
expr1 = egraph.let("expr1", Math(2) * (Math.var("x") + Math(3)))
# expr2 = 6 + 2 * x
expr2 = egraph.let("expr2", Math(6) + Math(2) * Math.var("x"))
a, b, c = vars_("a b c", Math)
x, y = vars_("x y", i64)
egraph.register(
rewrite(a + b).to(b + a),
rewrite(a * (b + c)).to((a * b) + (a * c)),
rewrite(Math(x) + Math(y)).to(Math(x + y)),
rewrite(Math(x) * Math(y)).to(Math(x * y)),
)
egraph.run(10)
egraph.check(eq(expr1).to(expr2))
def test_fib():
egraph = EGraph()
@function
def fib(x: i64Like) -> i64: ...
f0, f1, x = vars_("f0 f1 x", i64)
egraph.register(
set_(fib(0)).to(i64(1)),
set_(fib(1)).to(i64(1)),
rule(
eq(f0).to(fib(x)),
eq(f1).to(fib(x + 1)),
).then(set_(fib(x + 2)).to(f0 + f1)),
)
egraph.run(7)
egraph.check(eq(fib(i64(7))).to(i64(21)))
def test_fib_demand():
egraph = EGraph()
class Num(Expr):
def __init__(self, i: i64Like) -> None: ...
def __add__(self, other: Num) -> Num: ...
@function(cost=20)
def fib(x: i64Like) -> Num: ...
@egraph.register
def _fib(a: i64, b: i64):
yield rewrite(Num(a) + Num(b)).to(Num(a + b))
yield rewrite(fib(a)).to(fib(a - 1) + fib(a - 2), a > 1)
yield rewrite(fib(a)).to(Num(a), a <= 1)
f7 = egraph.let("f7", fib(7))
egraph.run(14)
egraph.check(eq(f7).to(Num(13)))
res = egraph.extract(f7)
assert expr_parts(res) == expr_parts(Num(13))
def test_push_pop():
egraph = EGraph()
@function(merge=lambda old, new: old.max(new))
def foo() -> i64: ...
egraph.register(set_(foo()).to(i64(1)))
egraph.check(eq(foo()).to(i64(1)))
with egraph:
egraph.register(set_(foo()).to(i64(2)))
egraph.check(eq(foo()).to(i64(2)))
egraph.check(eq(foo()).to(i64(1)))
def test_constants():
egraph = EGraph()
class A(Expr):
pass
one = constant("one", A)
two = constant("two", A)
egraph.register(union(one).with_(two))
egraph.check(eq(one).to(two))
def test_class_vars():
egraph = EGraph()
class B(Expr):
ONE: ClassVar[B]
two = constant("two", B)
egraph.register(union(B.ONE).with_(two))
egraph.check(eq(B.ONE).to(two))
def test_extract_constant_twice():
# Sometimes extracting a constant twice will give an error
egraph = EGraph()
class Numeric(Expr):
ONE: ClassVar[Numeric]
egraph.extract(Numeric.ONE)
egraph.extract(Numeric.ONE)
def test_extract_include_cost():
_, cost = EGraph().extract(i64(0), include_cost=True)
assert cost == 1
def test_relation():
egraph = EGraph()
test_relation = relation("test_relation", i64, i64)
egraph.register(test_relation(i64(1), i64(1)))
def test_variable_args():
egraph = EGraph()
egraph.check(Set(i64(1), i64(2)).contains(i64(1)))
def test_generic_sort():
egraph = EGraph()
egraph.check(Set(i64(1), i64(2)).contains(i64(1)))
def test_keyword_args():
EGraph()
@function
def foo(x: i64Like, y: i64Like) -> i64: ...
pos = expr_parts(foo(i64(1), i64(2)))
assert expr_parts(foo(i64(1), y=i64(2))) == pos
assert expr_parts(foo(y=i64(2), x=i64(1))) == pos
def test_keyword_args_init():
EGraph()
class Foo(Expr):
def __init__(self, x: i64Like) -> None: ...
assert expr_parts(Foo(1)) == expr_parts(Foo(x=1))
def test_property():
egraph = EGraph()
class Foo(Expr):
def __init__(self) -> None: ...
@property
def bar(self) -> i64: ...
egraph.register(set_(Foo().bar).to(i64(1)))
egraph.check(eq(Foo().bar).to(i64(1)))
def test_default_args():
EGraph()
@function
def foo(x: i64Like, y: i64Like = i64(1)) -> i64: ...
assert expr_parts(foo(i64(1))) == expr_parts(foo(i64(1), i64(1)))
assert str(foo(i64(1), i64(2))) == "foo(1, 2)"
assert str(foo(i64(1), i64(1))) == "foo(1)"
class TestPyObject:
def test_from_string(self):
assert EGraph().extract(PyObject.from_string("foo")).value == "foo"
def test_to_string(self):
EGraph().check(PyObject("foo").to_string() == String("foo"))
def test_to_int(self):
EGraph().check(PyObject(42).to_int() == i64(42))
def test_dict_update(self):
original_d = {"foo": "bar"}
res = EGraph().extract(PyObject(original_d).dict_update("foo", "baz")).value
assert res == {"foo": "baz"}
assert original_d == {"foo": "bar"}
def test_eval(self):
assert EGraph().extract(py_eval("x + y", {"x": 10, "y": 20}, {})).value == 30
@pytest.mark.xfail(reason="cant pickle locals")
def test_eval_local(self):
x = "hi"
res = py_eval("my_add(x, y)", PyObject(locals()).dict_update("y", "there"), globals())
assert EGraph().extract(res).value == "hithere"
def test_exec(self):
assert EGraph().extract(py_exec("x = 10")).value == {"x": 10}
def test_exec_globals(self):
assert EGraph().extract(py_exec("x = y + 1", {"y": 10})).value == {"x": 11}
def my_add(a, b):
return a + b
def test_convert_int_float():
egraph = EGraph()
egraph.check(eq(i64(1)).to(f64(1.0).to_i64()))
egraph.check(eq(f64(1.0)).to(f64.from_i64(i64(1))))
def test_f64_negation() -> None:
egraph = EGraph()
# expr1 = -2.0
expr1 = egraph.let("expr1", -f64(2.0))
# expr2 = 2.0
expr2 = egraph.let("expr2", f64(2.0))
# expr3 = -(-2.0)
expr3 = egraph.let("expr3", -(-f64(2.0))) # noqa: B002
egraph.check(eq(expr1).to(-expr2))
egraph.check(eq(expr3).to(expr2))
def test_not_equals():
egraph = EGraph()
egraph.check(ne(i64(10)).to(i64(2)))
def test_custom_equality():
egraph = EGraph()
class Boolean(Expr):
def __init__(self, value: BoolLike) -> None: ...
def __eq__(self, other: Boolean) -> Boolean: # type: ignore[override]
...
def __ne__(self, other: Boolean) -> Boolean: # type: ignore[override]
...
egraph.register(rewrite(Boolean(True) == Boolean(True)).to(Boolean(False)))
egraph.register(rewrite(Boolean(True) != Boolean(True)).to(Boolean(True)))
should_be_true = Boolean(True) == Boolean(True)
should_be_false = Boolean(True) != Boolean(True)
egraph.register(should_be_true, should_be_false)
egraph.run(10)
egraph.check(eq(should_be_true).to(Boolean(False)))
egraph.check(eq(should_be_false).to(Boolean(True)))
class TestMutate:
def test_setitem_defaults(self):
EGraph()
class Foo(Expr):
def __init__(self) -> None: ...
def __setitem__(self, key: i64Like, value: i64Like) -> None: ...
foo = Foo()
foo[10] = 20
assert str(foo) == "_Foo_1 = Foo()\n_Foo_1[10] = 20\n_Foo_1"
assert expr_parts(foo) == TypedExprDecl(
JustTypeRef(Ident("Foo", __name__)),
CallDecl(
MethodRef(Ident("Foo", __name__), "__setitem__"),
(expr_parts(Foo()), expr_parts(i64(10)), expr_parts(i64(20))),
),
)
def test_function(self):
egraph = EGraph()
class Math(Expr):
def __init__(self, i: i64Like) -> None: ...
def __add__(self, other: Math) -> Math: ...
@function(mutates_first_arg=True)
def incr(x: Math) -> None: ...
x = Math(i64(10))
x_copied = copy(x)
incr(x)
assert expr_parts(x_copied) == expr_parts(Math(i64(10)))
assert expr_parts(x) == TypedExprDecl(
JustTypeRef(Ident("Math", __name__)),
CallDecl(FunctionRef(Ident("incr", __name__)), (expr_parts(x_copied),)),
)
assert str(x) == "_Math_1 = Math(10)\nincr(_Math_1)\n_Math_1"
assert str(x + Math(10)) == "_Math_1 = Math(10)\nincr(_Math_1)\n_Math_1 + Math(10)"
i, _j = vars_("i j", Math)
incr_i = copy(i)
incr(incr_i)
egraph.register(rewrite(incr_i).to(i + Math(1)), x)
egraph.run(10)
egraph.check(eq(x).to(Math(10) + Math(1)))
x_incr_copy = copy(x)
incr(x)
assert (
str(x_incr_copy + x)
== "_Math_1 = Math(10)\nincr(_Math_1)\n_Math_2 = copy(_Math_1)\nincr(_Math_2)\n_Math_1 + _Math_2"
), "only copy when re-used later"
def test_builtin_reflected():
assert expr_parts(5 + i64(10)) == expr_parts(i64(5) + i64(10))
def test_reflected_binary_method():
# If we have a reflected binary method, it should be converted into the non-reflected version
EGraph()
class Math(Expr):
def __init__(self, value: i64Like) -> None: ...
def __add__(self, other: Math) -> Math: ...
def __radd__(self, other: Math) -> Math: ...
converter(i64, Math, Math)
expr = 10 + Math(5) # type: ignore[operator]
assert str(expr) == "Math(10) + Math(5)"
assert expr_parts(expr) == TypedExprDecl(
JustTypeRef(Ident("Math", __name__)),
CallDecl(MethodRef(Ident("Math", __name__), "__add__"), (expr_parts(Math(i64(10))), expr_parts(Math(i64(5))))),
)
def test_rewrite_upcasts():
class X(Expr):
def __init__(self, value: i64Like) -> None: ...
converter(i64, X, X)
rewrite(X(1)).to(0) # type: ignore[arg-type]
def test_function_default_upcasts():
@function
def f(x: i64Like) -> i64: ...
assert expr_parts(f(1)) == expr_parts(f(i64(1)))
def test_upcast_self_lower_cost():
# Verifies that self will be upcasted, if that upcast has a lower cast than converting the other arg
# i.e. Int(x) + NDArray(y) -> NDArray(Int(x)) + NDArray(y) instead of Int(x) + NDArray(y).to_int()
class Int(Expr):
def __init__(self, name: StringLike) -> None: ...
def __add__(self, other: Int) -> Int: ...
class NDArray(Expr):
def __init__(self, name: StringLike) -> None: ...
def __add__(self, other: NDArrayLike) -> NDArray: ...
def __radd__(self, other: NDArrayLike) -> NDArray: ...
def to_int(self) -> Int: ...
@classmethod
def from_int(cls, other: Int) -> NDArray: ...
NDArrayLike: TypeAlias = NDArray | Int
converter(Int, NDArray, NDArray.from_int)
converter(NDArray, Int, lambda a: a.to_int(), 100)
r = Int("x") + NDArray("y")
assert expr_parts(r) == expr_parts(NDArray.from_int(Int("x")) + NDArray("y"))
class TestEval:
def test_string(self):
assert String("hi").value == "hi"
def test_bool(self):
assert Bool(True).value is True
assert bool(Bool(True)) is True
def test_i64(self):
assert i64(10).value == 10
assert int(i64(10)) == 10
assert [10][i64(0)] == 10
def test_f64(self):
assert f64(10.0).value == 10.0
assert int(f64(10.0)) == 10
assert float(f64(10.0)) == 10.0
def test_map(self):
assert Map[String, i64].empty().value == {}
m = Map[String, i64].empty().insert(String("a"), i64(1)).insert(String("b"), i64(2))
assert m.value == {String("a"): i64(1), String("b"): i64(2)}
assert set(m) == {String("a"), String("b")}
assert len(m) == 2
assert String("a") in m
assert String("c") not in m
def test_set(self):
assert EGraph().extract(Set[i64].empty()).value == set()
s = Set(i64(1), i64(2))
assert s.value == {i64(1), i64(2)}
assert set(s) == {i64(1), i64(2)}
assert len(s) == 2
assert i64(1) in s
assert i64(3) not in s
def test_rational(self):
assert Rational(1, 2).value == Fraction(1, 2)
assert float(Rational(1, 2)) == 0.5
assert int(Rational(1, 1)) == 1
def test_vec(self):
assert Vec[i64].empty().value == ()
s = Vec(i64(1), i64(2))
assert s.value == (i64(1), i64(2))
assert list(s) == [i64(1), i64(2)]
assert len(s) == 2
assert i64(1) in s
assert i64(3) not in s
def test_py_object(self):
assert PyObject(10).value == 10
o = (1, 2, 3)
assert PyObject(o).value == o
def test_big_int(self):
assert int(EGraph().extract(BigInt(10))) == 10
def test_big_rat(self):
br = EGraph().extract(BigRat(1, 2))
assert float(br) == 1 / 2
assert br.value == Fraction(1, 2)
def test_multiset(self):
assert list(MultiSet(i64(1), i64(1))) == [i64(1), i64(1)]
def test_unstable_fn(self):
class Math(Expr):
def __init__(self) -> None: ...
@function
def f(x: Math) -> Math: ...
u_f = UnstableFn(f)
assert u_f.value == f
p_u_f = UnstableFn(f, Math())
value = p_u_f.value
assert isinstance(value, partial)
assert value.func == f
assert value.args == (Math(),)
# def test_egglog_string():
# egraph = EGraph(save_egglog_string=True)
# egraph.register((i64(1)))
# assert egraph.as_egglog_string
# def test_no_egglog_string():
# egraph = EGraph()
# egraph.register((i64(1)))
# with pytest.raises(ValueError):
# egraph.as_egglog_string
def test_eval_fn():
assert EGraph().extract(PyObject(lambda x: (x,))(PyObject.from_int(1))).value == (1,)
def _global_make_tuple(x):
return (x,)
def test_eval_fn_globals():
assert EGraph().extract(PyObject(lambda x: _global_make_tuple(x))(PyObject.from_int(1))).value == (1,)
def test_eval_fn_locals():
def _locals_make_tuple(x):
return (x,)
assert EGraph().extract(PyObject(lambda x: _locals_make_tuple(x))(PyObject.from_int(1))).value == (1,)
def test_lazy_types():
class A(Expr):
def __init__(self) -> None: ...
def b(self) -> B: ...
class B(Expr): ...
EGraph().register(A().b())
# https://github.com/egraphs-good/egglog-python/issues/100
def test_functions_seperate_pop():
egraph = EGraph()
class T(Expr):
def __init__(self, x: i64Like) -> None: ...
with egraph:
@function
def f(x: T) -> T: ...
egraph.register(f(T(1)))
with egraph:
@function
def f(x: T, y: T) -> T: ... # type: ignore[misc]
egraph.register(f(T(1), T(2))) # type: ignore[call-arg]
# https://github.com/egraphs-good/egglog/issues/113
def test_multiple_generics():
@function
def f() -> Vec[i64]: ...
@function
def g() -> Vec[String]: ...
egraph = EGraph()
egraph.register(
set_(f()).to(Vec[i64]()),
set_(g()).to(Vec[String]()),
)
assert str(egraph.extract(f())) == "Vec[i64].empty()"
assert str(egraph.extract(g())) == "Vec[String].empty()"
def test_deferred_ruleset():
@ruleset
def rules(x: AA):
yield rewrite(first(x)).to(second(x))
class AA(Expr):
def __init__(self) -> None: ...
@function
def first(x: AA) -> AA: ...
@function
def second(x: AA) -> AA: ...
check(
eq(first(AA())).to(second(AA())),
rules,
first(AA()),
)
def test_access_method_on_class():
class A(Expr):
def __init__(self) -> None: ...
def b(self, x: i64Like) -> A: ...
assert expr_parts(A.b(A(), 1)) == expr_parts(A().b(1))
def test_access_property_on_class():
class A(Expr):
def __init__(self) -> None: ...
@property
def b(self) -> i64: ...
assert expr_parts(A.b(A())) == expr_parts(A().b)
class A(Expr):
def __init__(self) -> None: ...
class TestDefaultReplacements:
def test_function(self):
@function
def f() -> A:
return A()
check_eq(f(), A(), run())
def test_function_ruleset(self):
r = ruleset()
@function(ruleset=r)
def f() -> A:
return A()
check_eq(f(), A(), r)
def test_constant(self):
a = constant("a", A, A())
check_eq(a, A(), run())
def test_constant_ruleset(self):
r = ruleset()
a = constant("a", A, A(), ruleset=r)
check_eq(a, A(), r)
def test_method(self):
class B(Expr):
def __init__(self) -> None: ...
def f(self) -> A:
return A()
check_eq(B().f(), A(), run())
def test_method_ruleset(self):
r = ruleset()
class B(Expr, ruleset=r):
def __init__(self) -> None: ...
def f(self) -> A:
return A()
check_eq(B().f(), A(), r)
def test_classmethod(self):
class B(Expr):
@classmethod
def f(cls) -> A:
return A()
check_eq(B.f(), A(), run())
def test_classmethod_ruleset(self):
r = ruleset()
class B(Expr, ruleset=r):
@classmethod
def f(cls) -> A:
return A()
check_eq(B.f(), A(), r)
def test_classvar(self):
class B(Expr):
a: ClassVar[A] = A()
check_eq(B.a, A(), run())
def test_classvar_ruleset(self):
r = ruleset()
class B(Expr, ruleset=r):
a: ClassVar[A] = A()
check_eq(B.a, A(), r)
def test_method_refer_to_later(self):
"""
Verify that an earlier method body can refer to values defined in later ones
"""
class B(Expr):
def __init__(self) -> None: ...
def f(self) -> A:
return self.g()
def g(self) -> A: ...
B()
left = B().f()
right = B().g()
check_eq(left, right, run())
def test_classmethod_own_class(self):
class B(Expr):
def __init__(self) -> None: ...
@classmethod
def f(cls) -> B:
return B()
check_eq(B.f(), B(), run())
class TestIssue166:
"""
Raised by @cgyurgyik in https://github.com/egraphs-good/egglog-python/issues/166
"""
def test_inserting_map(self):
egraph = EGraph()
m = egraph.let("map", Map[String, i64].empty().insert(String("a"), i64(42)))
egraph.run(5)
egraph.extract(m)
def test_creating_map(self):
m = Map[String, i64].empty()
egraph = EGraph()
egraph.register(m)
egraph.extract(m)
def test_helpful_error_function_class():
class E(Expr):
@function(cost=10)
def __init__(self) -> None: ...
match = "Inside of classes, wrap methods with the `method` decorator, not `function`"
with pytest.raises(ValueError, match=match):
E()
def test_vec_like_conversion():
"""
Test that we can use a generic type alias for conversion
"""
@function
def my_fn(xs: VecLike[i64, i64Like]) -> Unit: ...
assert expr_parts(my_fn((1, 2))) == expr_parts(my_fn(Vec[i64](i64(1), i64(2))))
assert expr_parts(my_fn([])) == expr_parts(my_fn(Vec[i64]()))
def test_set_like_conversion():
@function
def my_fn(xs: SetLike[i64, i64Like]) -> Unit: ...
assert expr_parts(my_fn({1, 2})) == expr_parts(my_fn(Set[i64](i64(1), i64(2))))
assert expr_parts(my_fn(set())) == expr_parts(my_fn(Set[i64]()))
def test_map_like_conversion():
@function
def my_fn(xs: MapLike[i64, String, i64Like, StringLike]) -> Unit: ...
assert expr_parts(my_fn({1: "hi"})) == expr_parts(my_fn(Map[i64, String].empty().insert(i64(1), String("hi"))))
assert expr_parts(my_fn({})) == expr_parts(my_fn(Map[i64, String].empty()))
class TestEqNE:
def test_eq(self):
assert i64(3) == i64(3)
def test_ne(self):
EGraph().check(i64(3) != i64(4))
def test_eq_false(self):
assert not (i64(3) == 4) # noqa: SIM201
def test_no_upcast_eq():
"""
Verifies that if two items can be upcast to something, calling == on them won't use
equality
"""
class A(Expr):
def __init__(self) -> None: ...
class B(Expr):
def __init__(self) -> None: ...
def __eq__(self, other: B) -> B: ... # type: ignore[override]
converter(A, B, lambda a: B())
assert isinstance(A() == A(), Fact)
assert not isinstance(B() == B(), Fact)
def test_isinstance_expr():
"""
Verifies that isinstance() works on Exprs, and returns a Fact
"""
class A(Expr):
def __init__(self) -> None: ...
class B(Expr):
def __init__(self) -> None: ...
assert isinstance(A(), A)
assert not isinstance(A(), B)
class TestMatch:
def test_class(self):
"""
Verify that we can pattern match on expressions
"""
class A(Expr):
def __init__(self) -> None: ...
class B(Expr):
def __init__(self) -> None: ...
a = A()
match a:
case B():
msg = "Should not have matched B"
raise ValueError(msg)
case A():
pass
case _:
msg = "Should have matched A"
raise ValueError(msg)
def test_literal(self):
match i64(10):
case i64(i):
assert i == 10
case _:
msg = "Should have matched i64(10)"
raise ValueError(msg)
def test_literal_fail(self):
"""
Verify that matching on a literal that does not match raises an error
"""
match i64(10) + i64(10):
case i64(_i):
msg = "Should not have matched i64(20)"
raise ValueError(msg)
def test_custom_args(self):
class A(Expr):
def __init__(self) -> None: ...
__match_args__ = ("a", "b")
@method(preserve=True) # type: ignore[prop-decorator]
@property
def a(self) -> int:
return 1
@method(preserve=True) # type: ignore[prop-decorator]
@property
def b(self) -> str:
return "hi"
match A():
case A(a, b):
assert a == 1
assert b == "hi"
case _:
msg = "Should have matched A"
raise ValueError(msg)
def test_custom_args_fail(self):
"""
Verify that matching on a custom match that does not match raises an error
"""
class A(Expr):
def __init__(self) -> None: ...
__match_args__ = ("a",)
@method(preserve=True) # type: ignore[prop-decorator]
@property
def a(self) -> int:
raise AttributeError
match A():
case A(_a):
msg = "Should not have matched A"
raise ValueError(msg)
T = TypeVar("T")
def test_type_param_sub():
"""
Verify that type substituion works properly, by comparing string version.
Comparing actual versions is always false if they are no the same object for unions
"""
V = Vec[T] | int
assert str(V[Unit]) == str(Vec[Unit] | int) # type: ignore[misc]
def test_override_hash():
class A(Expr):
def __init__(self) -> None: ...
@method(preserve=True)
def __hash__(self) -> int:
return 42
assert hash(A()) == 42
def test_serialize_warning_max_functions():
class A(Expr):
def __init__(self) -> None: ...
egraph = EGraph()
egraph.register(A())
with pytest.warns(UserWarning, match="A"):
egraph._serialize(max_functions=0)
def test_serialize_warning_max_calls():
class A(Expr): ...
@function
def f(x: StringLike) -> A: ...
egraph = EGraph()
egraph.register(f("a"), f("b"))
with pytest.warns(UserWarning, match="f"):
egraph._serialize(max_calls_per_function=1)
EXAMPLE_FILES = list((pathlib.Path(__file__).parent / "../egglog/examples").glob("*.py"))
# Test all files in the `examples` directory by importing them in this parametrized test
@pytest.mark.parametrize("name", [f.stem for f in EXAMPLE_FILES if f.stem != "__init__"])
def test_example(name):
importlib.import_module(f"egglog.examples.{name}")
@function
def f() -> i64: ...
class E(Expr):
X: ClassVar[i64]
def __init__(self) -> None: ...
def m(self) -> i64: ...