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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Equality saturation driver loop.
use crate::EGraphConfig;
use crate::apply::{PreparedRule, apply_rule_pooled};
use crate::canon::{MSetCanon, VarCanon};
use crate::containers::DenseId;
use crate::egraph::EGraph;
use crate::ematch::MatchPool;
use crate::index::IndexStore;
use crate::lit_model::LitModel;
use crate::literal::LitVal;
/// The goal of a `(run … :until …)`: two already-built class ids and the relation that has
/// to hold between them for the run to stop. The terms are ground, so they are built once
/// before the run and only their classes move.
#[derive(Clone, Copy, Debug)]
pub struct RunGoal<G> {
pub left: G,
pub right: G,
/// `true` for `:until (= a b)`, `false` for `:until (!= a b)`.
pub equal: bool,
}
impl<G: DenseId> RunGoal<G> {
/// Does the goal hold in a rebuilt graph?
///
/// Rebuild can merge congruent parent classes, so callers must not use this
/// observation while congruence work is pending.
fn holds<Cfg, L, const T: bool, const P: bool>(&self, eg: &EGraph<Cfg, L, T, P>) -> bool
where
Cfg: EGraphConfig<G = G>,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
(eg.find_const(self.left) == eg.find_const(self.right)) == self.equal
}
}
/// What a `(run …)` asks for beyond the iteration budget: which ruleset to run, and an
/// optional goal that stops it early.
#[derive(Clone, Copy, Debug)]
pub struct RunSpec<G> {
/// Iteration budget.
pub limit: usize,
/// Run only the rules in this ruleset. `None` is the default ruleset — the one untagged
/// rules join — so a program that declares no ruleset behaves exactly as before.
pub ruleset: Option<crate::apply::RulesetId>,
/// Checked before every iteration, including the first; the run stops as soon as it holds.
pub until: Option<RunGoal<G>>,
}
impl<G> RunSpec<G> {
/// A plain `(run N)`: default ruleset, no goal.
pub fn budget(limit: usize) -> Self {
Self {
limit,
ruleset: None,
until: None,
}
}
}
/// Result of a saturation run.
#[derive(Clone, Debug)]
pub struct SatResult {
/// Number of iterations executed.
pub iterations: usize,
/// Whether a fixpoint was reached (no new merges/insertions).
pub saturated: bool,
/// Whether the run stopped because its `:until` goal held. Distinct from `saturated`:
/// the goal can be met with rules still firing.
pub goal_met: bool,
/// Total executed lowered matching steps plus emitted matches across all
/// rounds and rules — see [`crate::ematch::match_steps`]. This
/// implementation-level work proxy is not a semantic match count or a
/// machine-independent runtime measure.
pub match_steps: u64,
}
/// Which saturation algorithm to run.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum SaturationStrategy {
/// Rediscover every match each round (`saturate`).
#[default]
Naive,
/// Use delta variants via the k-variant decomposition (`saturate_semi`).
/// The driver does not switch wholesale to naive; rules without safe delta
/// coverage use a full-index match.
SemiNaive,
}
/// Run equality saturation for up to `limit` iterations, over every rule given.
pub fn saturate<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
limit: usize,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
saturate_spec(rules, eg, model, &RunSpec::budget(limit), globals)
}
/// Run equality saturation under a full [`RunSpec`]: the iteration budget, the ruleset to
/// run, and an optional `:until` goal checked before each iteration.
pub fn saturate_spec<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
spec: &RunSpec<Cfg::G>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
saturate_spec_in(
rules,
eg,
model,
spec,
globals,
&mut crate::index::IndexScratch::new(),
)
}
/// [`saturate_spec`] over a caller-owned scratch, so the stream buffers and the
/// span arenas outlive the call.
///
/// A run of one round — which is what `(run 1)` is, and what the E6 incremental
/// cycle repeats — gets no reuse from a scratch that the saturation call
/// allocates and drops. Threading it in from the interpreter is what lets the
/// span arena carry its allocation and its generation stamp from one `(run)` to
/// the next. Reuse across calls needs no invalidation from the caller: a build
/// bumps the stamp, so whatever an earlier call left in the table reads as
/// empty.
pub fn saturate_spec_in<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
spec: &RunSpec<Cfg::G>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
scratch: &mut crate::index::IndexScratch<Cfg>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let steps_base = crate::ematch::match_steps();
// Outside the round loop: the pool's whole purpose is to survive rounds.
let mut pool = MatchPool::new();
for i in 0..spec.limit {
{
let _t = crate::phase_timing::Timer::start(crate::phase_timing::REBUILD);
eg.rebuild();
}
if goal_met(spec, eg) {
return sat_result(i, false, true, steps_base);
}
let index = {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::FULL);
IndexStore::build_with(eg, scratch)
};
let mut changes = 0;
{
let _t = crate::phase_timing::Timer::start(crate::phase_timing::MATCH);
let stats = {
let _s = crate::phase_timing::Timer::start(crate::phase_timing::STATS);
crate::schedule::IndexStats::from_index(&index)
};
for rule in rules.iter().filter(|r| r.ruleset == spec.ruleset) {
changes += apply_rule_pooled(rule, eg, &index, &stats, model, globals, &mut pool);
}
}
// Before any exit from the loop body: the arenas go back so the next
// round, and the next `(run)`, build into the same span tables.
index.recycle_into(scratch, true);
crate::phase_timing::count(crate::phase_timing::C_ROUNDS, 1);
crate::phase_timing::round_line("naive");
if changes == 0 {
return sat_result(i + 1, true, false, steps_base);
}
}
// The budget is spent, but a goal met by the last iteration's work should still be
// reported as met. Rebuild first: the final actions may have made parent nodes
// congruent without merging their classes directly.
if spec.until.is_some() {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::REBUILD);
eg.rebuild();
}
let met = goal_met(spec, eg);
sat_result(spec.limit, false, met, steps_base)
}
/// Does the run's `:until` goal hold? Always false when there is no goal.
fn goal_met<Cfg, L, const T: bool, const P: bool>(
spec: &RunSpec<Cfg::G>,
eg: &EGraph<Cfg, L, T, P>,
) -> bool
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
spec.until.is_some_and(|g| g.holds(eg))
}
fn sat_result(iterations: usize, saturated: bool, goal_met: bool, steps_base: u64) -> SatResult {
SatResult {
iterations,
saturated,
goal_met,
match_steps: crate::ematch::match_steps() - steps_base,
}
}
// ===========================================================================
// Semi-naive saturation
// ===========================================================================
use crate::index::VariantIndex;
use crate::resolve::{RAtom, ResolvedQuery};
use crate::schedule::IndexStats;
use std::hash::Hash;
/// The op a join atom scans, or `None` for atoms that don't scan an index
/// (`Eq`, `EqGlobal`). Atoms with an op are the ones that participate
/// in the semi-naive variant decomposition — see the design doc, "Which Atoms
/// Count as Positions": only relation-scanning atoms generate candidate nodes;
/// built-in constraints have no delta. `Lit` scans `@sort` like `LitBind` does
/// (it is that scan filtered to one payload), so it is a position too: a match
/// whose only new tuple is a freshly interned literal node needs a variant that
/// reads the literal atom's delta.
pub(crate) fn atom_op<O: Copy, S, V>(atom: &RAtom<O, S, V>) -> Option<O> {
match atom {
RAtom::Plain { op, .. }
| RAtom::AExact { op, .. }
| RAtom::APrefix { op, .. }
| RAtom::ASuffix { op, .. }
| RAtom::ABoth { op, .. }
| RAtom::ACExact { op, .. }
| RAtom::ACSub { op, .. }
| RAtom::ACIExact { op, .. }
| RAtom::ACISub { op, .. }
| RAtom::Lit { op, .. }
| RAtom::LitBind { op, .. } => Some(*op),
RAtom::Eq(..) | RAtom::EqGlobal(..) | RAtom::Pred { .. } => None,
}
}
/// Indices (stable `atom_id`s) of the join atoms in a rule — the atoms the
/// semi-naive variant loop ranges over. Excludes `Eq`/`EqGlobal`.
fn join_atom_indices<O: Copy, S, V>(rq: &ResolvedQuery<O, S, V>) -> Vec<usize> {
rq.atoms
.iter()
.enumerate()
.filter(|(_, a)| atom_op(a).is_some())
.map(|(i, _)| i)
.collect()
}
/// The node variable an atom binds, or `None` for the atoms that bind none (`Eq`,
/// `EqGlobal`, `Pred`).
pub(crate) fn atom_node<O, S, V>(atom: &RAtom<O, S, V>) -> Option<crate::ast::VarId> {
match atom {
RAtom::Plain { node, .. }
| RAtom::Lit { node, .. }
| RAtom::AExact { node, .. }
| RAtom::APrefix { node, .. }
| RAtom::ASuffix { node, .. }
| RAtom::ABoth { node, .. }
| RAtom::ACExact { node, .. }
| RAtom::ACSub { node, .. }
| RAtom::ACIExact { node, .. }
| RAtom::ACISub { node, .. }
| RAtom::LitBind { node, .. } => Some(*node),
RAtom::Eq(..) | RAtom::EqGlobal(..) | RAtom::Pred { .. } => None,
}
}
/// Whether a rule has to be matched against the whole graph every round instead of
/// being delta-restricted.
///
/// The variant decomposition assumes that every way a match can become available shows
/// up as a new or re-canonicalized tuple in some atom's relation. A constraint between
/// two atoms' *node* variables breaks that assumption: when those two classes merge,
/// neither node's tuple changes, so no variant's delta holds the event and the match is
/// never found. Measured on the `matrix` translation, whose conditional Kron/MMul rewrite
/// guards on `(= p (ncols a)) (= p (nrows c))`: under delta restriction the rule never
/// fires, at any budget.
///
/// The root-binding pattern form `(= v pat)` is what produces such constraints; a rule
/// that does not use it is unaffected, so this costs the existing corpus nothing.
fn needs_naive_match<O: Copy, S, V>(rq: &ResolvedQuery<O, S, V>) -> bool {
// A global reference in a child or element position is a fixed-class
// constraint with no scanning atom behind it: the match set grows when the
// global's class absorbs another class, and if the surviving
// representative is the id the parents already store, nothing
// recanonicalizes and no relation gains a tuple — the merge-membership
// delta (`merge_in_classes`) cannot help a class no atom scans. Such a
// rule matches the whole graph every round, like the Eq-constrained rules
// below. `semi_recanon_parent_delta.egg` is the regression test.
if rq.atoms.iter().any(pattern_refs_global) {
return true;
}
let has_eq = rq
.atoms
.iter()
.any(|a| matches!(a, RAtom::Eq(..) | RAtom::EqGlobal(..)));
if !has_eq {
return false;
}
let node_vars: Vec<crate::ast::VarId> = rq.atoms.iter().filter_map(atom_node).collect();
rq.atoms.iter().any(|a| match a {
RAtom::Eq(x, y) => node_vars.contains(x) || node_vars.contains(y),
RAtom::EqGlobal(x, _) => node_vars.contains(x),
_ => false,
})
}
/// The worst access-path skew any of the rule's scan atoms can meet this
/// round: the max over the atoms' operators of the measured
/// size-biased-over-plain bucket-size ratios (`FanOuts` skew maps). Only the
/// op-keyed paths participate — `by_repr` is graph-global and would flip every
/// rule together.
fn rule_skew<O: DenseId + std::hash::Hash, S, V>(
rule: &PreparedRule<O, S, V>,
stats: &IndexStats<O>,
) -> f64 {
let mut worst: f64 = 1.0;
for atom in &rule.query.atoms {
let Some(op) = atom_op(atom) else { continue };
for (&(o, _), &sk) in &stats.fanouts.by_child_pos_skew {
if o == op {
worst = worst.max(sk);
}
}
if let Some(&sk) = stats.fanouts.by_contains_skew.get(&op) {
worst = worst.max(sk);
}
}
worst
}
/// Whether an atom's pattern references a let-bound global in a child or
/// element position (see the fixed-class case in [`needs_naive_match`]).
fn pattern_refs_global<O, S, V>(a: &RAtom<O, S, V>) -> bool {
use crate::resolve::PatVar;
let g = |v: &PatVar| matches!(v, PatVar::Global(_));
match a {
RAtom::Plain { children, .. } | RAtom::AExact { children, .. } => children.iter().any(g),
RAtom::APrefix { fixed, .. }
| RAtom::ASuffix { fixed, .. }
| RAtom::ABoth { fixed, .. } => fixed.iter().any(g),
RAtom::ACExact { elems, .. } | RAtom::ACSub { elems, .. } => {
elems.iter().any(|(v, _)| g(v))
}
RAtom::ACIExact { elems, .. } | RAtom::ACISub { elems, .. } => elems.iter().any(g),
RAtom::Lit { .. }
| RAtom::LitBind { .. }
| RAtom::Eq(..)
| RAtom::EqGlobal(..)
| RAtom::Pred { .. } => false,
}
}
/// Stats for the semi-naive variant whose delta atom is `delta_atom`.
///
/// Each join atom's driver-scan cardinality is set by its **mode in this
/// flavor**, which is per-atom, not per-op (two atoms with the same op can have
/// different modes — see the design doc "How a Variant Executes"). So we fill
/// `atom_card` per atom rather than clobbering `op_card` by op:
///
/// | atom `j` | mode | base cardinality |
/// |----------|------|------------------|
/// | `j == delta_atom` | delta | `|delta.by_op[op_j]|` |
/// | `j < delta_atom` | full∖delta | `|full.by_op[op_j]| − |delta.by_op[op_j]|` |
/// | `j > delta_atom` | full | `|full.by_op[op_j]|` |
///
/// `full∖delta` is exact and O(1) because `delta ⊆ full` per key. The scheduler
/// then picks most-selective-first from these real per-flavor numbers; the
/// `VariantIndex` applies the matching modes at execution by `atom_id`.
fn variant_stats<O, S, V, Cfg>(
rq: &ResolvedQuery<O, S, V>,
delta_atom: usize,
full: &IndexStore<Cfg>,
delta: &IndexStore<Cfg>,
) -> IndexStats<O>
where
O: DenseId + Hash,
Cfg: EGraphConfig<O = O>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let mut stats = IndexStats::from_index(full);
for (j, atom) in rq.atoms.iter().enumerate() {
let Some(op) = atom_op(atom) else { continue };
let full_card = full.nodes_by_op(op).len();
let delta_card = delta.nodes_by_op(op).len();
let card = match j.cmp(&delta_atom) {
std::cmp::Ordering::Equal => delta_card, // delta
std::cmp::Ordering::Less => full_card - delta_card, // full ∖ delta
std::cmp::Ordering::Greater => full_card, // full
};
stats.atom_card.insert(j, card);
}
stats
}
/// Schedule one (rule, variant) against `vindex` and apply its actions to
/// every match. Returns the number of changes applied.
/// `pool` is carried across every (rule, variant) in a saturation run so the
/// match buffers are allocated once and then recycled; see [`MatchPool`].
fn run_rule_variant<Cfg, L, M, S, const T: bool, const P: bool>(
rule: &PreparedRule<Cfg::O, S, L>,
eg: &mut EGraph<Cfg, L, T, P>,
vindex: &VariantIndex<'_, Cfg>,
stats: &IndexStats<Cfg::O>,
model: &M,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
pool: &mut MatchPool<Cfg>,
) -> usize
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
// Per-rule scheduling-mode auto-selection: under `Auto`,
// a rule whose join touches a skewed access path (a hub bucket) runs with
// per-binding atom ordering, and a rule over flat paths keeps the static
// plan and skips the per-binding overhead. The threshold separates nearly
// flat paths from distributions dominated by hub buckets. The match set is
// the same either way (design chapter 20).
if crate::ematch::scheduling_mode() == crate::ematch::SchedulingMode::Auto {
const SKEW_THRESHOLD: f64 = 8.0;
crate::ematch::set_runtime_scheduling(rule_skew(rule, stats) > SKEW_THRESHOLD);
}
let sampler = crate::index::IndexSampler::new(eg, *vindex);
let plan = crate::schedule::schedule_with_stats_sampled(&rule.query, stats, &sampler);
crate::ematch::run_query_scheduled_into(&rule.query, &plan, eg, vindex, globals, pool);
let mut changes = 0;
for j in 0..pool.len() {
let row = pool.row(j);
changes += crate::apply::apply_rule_actions(rule, &row, eg, model, globals);
}
changes
}
/// Semi-naive saturation: equivalent to [`saturate`] but, each round after
/// the first, restricts matching to matches involving at least one node that
/// changed in the previous round (the delta), via the k-variant decomposition.
///
/// Round 0 runs naive (the whole graph is "new"). Rounds ≥ 1 run, per rule,
/// one variant per join atom: variant `i` reads delta for atom `i`, full∖delta
/// for atoms `< i`, and full for atoms `> i`. The touched log feeding the
/// delta is reset each round.
pub fn saturate_semi<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
limit: usize,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
saturate_semi_spec(rules, eg, model, &RunSpec::budget(limit), globals)
}
/// Semi-naive saturation under a full [`RunSpec`] — the delta-driven counterpart of
/// [`saturate_spec`].
pub fn saturate_semi_spec<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
spec: &RunSpec<Cfg::G>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
saturate_semi_spec_in(
rules,
eg,
model,
spec,
globals,
&mut crate::index::IndexScratch::new(),
)
}
/// [`saturate_semi_spec`] over a caller-owned scratch. See
/// [`saturate_spec_in`] for why the scratch is threaded in rather than
/// allocated per call.
///
/// The full and delta indices are alive at the same time, so they draw from two
/// separate sets of arenas; [`IndexStore::recycle_into`]'s `full` flag is which
/// set a store's arenas go back to.
pub fn saturate_semi_spec_in<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[PreparedRule<Cfg::O, S, L>],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
spec: &RunSpec<Cfg::G>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
scratch: &mut crate::index::IndexScratch<Cfg>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let limit = spec.limit;
let steps_base = crate::ematch::match_steps();
// Outside the round loop, and shared by every variant of every rule: a
// round runs one query per (rule, join atom), all of similar match count.
let mut pool = MatchPool::new();
for i in 0..limit {
{
let _t = crate::phase_timing::Timer::start(crate::phase_timing::REBUILD);
eg.rebuild();
}
if goal_met(spec, eg) {
return sat_result(i, false, true, steps_base);
}
let full = {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::FULL);
IndexStore::build_with(eg, scratch)
};
// delta = everything touched since the previous round's index build
// (fresh nodes from the last round's apply + this round's recanon).
let delta = if i == 0 {
None
} else {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::DELTA);
crate::phase_timing::count(crate::phase_timing::C_ROUNDS_DELTA, 1);
Some(IndexStore::build_delta_with(eg, eg.touched(), scratch))
};
if std::env::var_os("EGRAPH_TRACE_DELTA").is_some() {
eprintln!("[semi round {i}] touched={:?}", eg.touched());
}
eg.clear_touched();
let match_timer = crate::phase_timing::Timer::start(crate::phase_timing::MATCH);
let mut changes = 0;
match &delta {
// Round 0: naive — the whole graph is new.
None => {
let stats = {
let _s = crate::phase_timing::Timer::start(crate::phase_timing::STATS);
IndexStats::from_index(&full)
};
let vindex = VariantIndex::naive(&full);
for rule in rules.iter().filter(|r| r.ruleset == spec.ruleset) {
changes +=
run_rule_variant(rule, eg, &vindex, &stats, model, globals, &mut pool);
}
}
// Rounds ≥ 1: one variant per join atom.
Some(delta) => {
let full_stats = {
let _s = crate::phase_timing::Timer::start(crate::phase_timing::STATS);
IndexStats::from_index(&full)
};
for rule in rules.iter().filter(|r| r.ruleset == spec.ruleset) {
let jatoms = join_atom_indices(&rule.query);
if jatoms.is_empty() || needs_naive_match(&rule.query) {
// No scanning atoms (e.g. a bare-literal rule), or a
// constraint between two atoms' node variables, whose
// enabling merge no delta records: run it naive so its
// matches are never missed.
let vindex = VariantIndex::naive(&full);
changes += run_rule_variant(
rule,
eg,
&vindex,
&full_stats,
model,
globals,
&mut pool,
);
continue;
}
for &di in &jatoms {
let stats = {
let _s = crate::phase_timing::Timer::start(crate::phase_timing::STATS);
crate::phase_timing::count(crate::phase_timing::C_VARIANTS, 1);
variant_stats(&rule.query, di, &full, delta)
};
let vindex = VariantIndex::variant(&full, delta, di);
changes +=
run_rule_variant(rule, eg, &vindex, &stats, model, globals, &mut pool);
}
}
}
}
match_timer.stop();
let had_delta = delta.is_some();
// Both stores' arenas go back before any exit from the loop body, each
// to the set it was drawn from.
if let Some(delta) = delta {
delta.recycle_into(scratch, false);
}
full.recycle_into(scratch, true);
crate::phase_timing::count(crate::phase_timing::C_ROUNDS, 1);
crate::phase_timing::round_line(if had_delta { "semi" } else { "semi-r0" });
if changes == 0 {
return sat_result(i + 1, true, false, steps_base);
}
}
if spec.until.is_some() {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::REBUILD);
eg.rebuild();
}
let met = goal_met(spec, eg);
sat_result(limit, false, met, steps_base)
}
/// Like `saturate`, but prints each match and union when `labels` is provided.
pub fn saturate_trace<Cfg, L, M, S, const T: bool, const P: bool>(
rules: &[(&str, PreparedRule<Cfg::O, S, L>)],
eg: &mut EGraph<Cfg, L, T, P>,
model: &M,
limit: usize,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> SatResult
where
Cfg: EGraphConfig,
S: DenseId,
L: LitVal,
M: LitModel<Value = L>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
use crate::ematch::run_query;
let steps_base = crate::ematch::match_steps();
let mut total_iter = 0;
for i in 0..limit {
total_iter = i + 1;
eg.rebuild();
let index = IndexStore::build(eg);
let stats = crate::schedule::IndexStats::from_index(&index);
let vindex = crate::index::VariantIndex::naive(&index);
let mut changes = 0;
for (label, rule) in rules {
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let shape = &plan.shape;
let matches = run_query(&plan, eg, &vindex, globals);
for m in &matches {
// Print node bindings (skip internal ?-prefixed names)
let binds: Vec<String> = shape
.nodes
.iter()
.enumerate()
.filter(|(_, name)| !name.starts_with('?'))
.map(|(i, name)| {
let vid = crate::ast::VarId::new(i as u16);
format!("{name}=e{}", m.get(vid).to_usize())
})
.collect();
let lit_binds: Vec<String> = shape
.lit_vals
.iter()
.enumerate()
.map(|(i, name)| {
let vid = crate::ast::LitValVarId::new(i as u16);
let lid = m.get_lit_val(vid);
format!("{name}={}", eg.lits().get(lid))
})
.collect();
let all_binds = [binds, lit_binds].concat().join(", ");
eprint!(" [{label}] match: {all_binds}");
changes += crate::apply::apply_rule_actions(rule, m, eg, model, globals);
eprintln!();
}
}
if changes == 0 {
eprintln!("-- fixpoint after {total_iter} iterations --");
return sat_result(total_iter, true, false, steps_base);
}
eprintln!("-- iteration {total_iter}: {changes} changes --");
}
sat_result(total_iter, false, false, steps_base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::apply::compile_rewrite;
use crate::id::{OpId, SortId};
use crate::literal::{NiraLitVal, NiraModel};
use crate::nodes::DefaultConfig;
use crate::registry::{OpRegistry, SortRegistry};
use crate::test_helpers::{parse_pattern, parse_rhs};
type EG = EGraph<DefaultConfig, NiraLitVal, false, false>;
fn make_eg() -> EG {
let mut eg = EG::from_model(&NiraModel);
let e = eg.intern_sort("IExpr");
let ibig = eg.sorts().id_by_name("IBig").unwrap();
eg.register_op2("f", e, e, e);
eg.register_op1("g", e, e);
eg.register_op0("a", e);
eg.register_op0("b", e);
eg.register_op0("c", e);
eg.register_opn("ILit", &[ibig], e);
eg.register_op2("IAdd", e, e, e);
eg.register_op2("IMul", e, e, e);
eg.register_mset("add", e, e);
eg.register_set("union", e, e);
eg.register_a("concat", e, e, crate::registry::AssocDir::Right);
eg
}
fn mk_rule<const TRACK: bool>(
lhs: &str,
rhs: &str,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
rules: &mut crate::registry::RuleRegistry<TRACK>,
) -> PreparedRule<OpId, SortId, NiraLitVal> {
let model = NiraModel;
let l = parse_pattern(lhs);
let r = parse_rhs(rhs);
compile_rewrite(
"test",
lhs,
rhs,
&l,
&r,
&[],
false,
ops,
sorts,
rules,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap()
}
/// Like `mk_rule` but with `when` side-conditions: the LHS plus extra
/// top-level patterns that flatten into independent atoms sharing vars.
fn mk_rule_when<const TRACK: bool>(
lhs: &str,
when: &[&str],
rhs: &str,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
rules: &mut crate::registry::RuleRegistry<TRACK>,
) -> PreparedRule<OpId, SortId, NiraLitVal> {
let model = NiraModel;
let l = parse_pattern(lhs);
let whens: Vec<_> = when.iter().map(|s| parse_pattern(s)).collect();
let r = parse_rhs(rhs);
compile_rewrite(
"test",
lhs,
rhs,
&l,
&r,
&whens,
false,
ops,
sorts,
rules,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap()
}
/// Build the `ByContains` scenario at scale `n_distractors`: exactly one
/// `g`-node binding `x`, one `add` node that contains `x` (the only match),
/// and `n_distractors` further distinct `add` nodes that do NOT contain
/// `x`. Returns the egraph + the prepared `when`-clause rule
/// `(g x)` with side condition `(add x ..rest)`.
///
/// The side-condition variadic atom has its element `x` already bound (by
/// `(g x)`) but its node unbound — the exact case `IndexLookup::ByContains`
/// exists to optimize: drive the `add` atom from the few parents that
/// contain `x`, instead of scanning the whole `by_op[add]` bucket.
fn build_by_contains_scenario(
n_distractors: usize,
) -> (EG, PreparedRule<OpId, SortId, NiraLitVal>) {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oadd = eg.ops().id_by_name("add").unwrap();
let og = eg.ops().id_by_name("g").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
// Exactly ONE g-node, binding x once.
let x = eg.add(oa, &[]);
let _gx = eg.add(og, &[x]);
// The single matching add: contains x at multiplicity 1.
let bx = eg.add(ob, &[]);
let _add_with_x = eg.add(oadd, &[x, bx]);
// N distinct distractor adds from f-towers (never g, never contain x).
let mut prev = eg.add(ob, &[]);
for _ in 0..n_distractors {
let e1 = eg.add(of, &[prev, prev]);
let e2 = eg.add(of, &[e1, prev]);
eg.add(oadd, &[e1, e2]);
prev = e2;
}
eg.rebuild();
let rule = mk_rule_when(
"(g x)",
&["(add x ..rest)"],
"(g x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
(eg, rule)
}
/// Measure the e-matching match-steps for the `ByContains` scenario at a
/// given distractor count, under the naive index view (one round).
fn by_contains_match_steps(n_distractors: usize) -> (u64, usize) {
use crate::ematch::{match_steps, reset_match_steps, set_match_step_counting};
let (eg, rule) = build_by_contains_scenario(n_distractors);
let full = IndexStore::build(&eg);
let stats = IndexStats::from_index(&full);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::naive(&full);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
set_match_step_counting(true);
reset_match_steps();
let matches = crate::ematch::run_query(&plan, &eg, &vindex, &globals);
(match_steps(), matches.len())
}
// -- Instrumentation: semi-naive does less match work than naive --
//
// End-to-end check of the `SatResult.match_steps` counter: over a
// multi-round saturation, semi-naive must reach the same fixpoint as naive
// while exploring strictly fewer partial-match extensions, because it
// rediscovers far fewer already-applied matches each round. This is the
// headline reason semi-naive exists, made measurable.
#[test]
fn semi_naive_does_less_match_work() {
crate::ematch::set_match_step_counting(true);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
// A converging saturation with several rounds of growth: commute +
// project + const-fold-ish AC growth over a non-trivial seed.
let setup = || -> (EG, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// a small tower of f's so multiple rounds fire.
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let f1 = eg.add(of, &[a, b]);
let f2 = eg.add(of, &[f1, c]);
let _f3 = eg.add(of, &[f2, a]);
let r1 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule(
"(f (f x y) z)",
"(f x (f y z))",
eg.ops(),
eg.sorts(),
&mut rr,
);
let n = eg.node_count();
(eg, vec![r1, r2], n)
};
let (mut a, rules_a, n) = setup();
let ra = saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, 30, &globals,
);
let (mut b, rules_b, n2) = setup();
let rb = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, 30, &globals,
);
// Same fixpoint.
assert_eq!(n, n2);
assert_eq!(ra.saturated, rb.saturated, "saturation flag mismatch");
assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"naive vs semi-naive partition mismatch"
);
// …reached with strictly less match work.
assert!(
rb.match_steps < ra.match_steps,
"semi-naive should explore fewer match steps than naive \
(naive={}, semi={})",
ra.match_steps,
rb.match_steps
);
}
// -- ByContains optimization: variadic atom with a bound element --
//
// A variadic side-condition atom whose ELEMENT is bound but whose NODE is
// not (`(g x)` then `(add x ..rest)`) must not drive from the full
// `by_op[add]` bucket and filter in DecomposeAC: match-steps would scale
// with the TOTAL number of `add` nodes even though only one contains
// `x`. `emit_variadic_join` intersects `by_op[add]` with
// `by_contains[x]` (the variadic analogue of `Plain`'s `ByChildPos`), so
// the driver is the few parents containing `x` and the work is independent
// of the distractor count.
//
// This pins the optimization: match-steps must stay ~constant as the
// distractor add count grows 10 → 210, while still finding the one match.
#[test]
fn by_contains_narrows_variadic_driver() {
let (small, m_small) = by_contains_match_steps(10);
let (large, m_large) = by_contains_match_steps(210);
// Correctness is invariant: exactly one match at either scale.
assert_eq!(m_small, 1, "scenario should yield exactly one match");
assert_eq!(m_large, 1, "scenario should yield exactly one match");
// 210 vs 10 distractors adds 200 more non-matching `add` nodes. With
// ByContains the driver is `by_contains[x]` (one entry), so the extra
// 200 nodes cost nothing; match-steps stay within a small constant.
// Allow generous slack for incidental per-round bookkeeping while still
// rejecting work proportional to the 200 additional distractors.
assert!(
large <= small + 10,
"ByContains should make variadic match work independent of the \
distractor count, but it grew: small={small} large={large} steps"
);
}
// -- Differential check: saturate (naive) vs saturate_semi --
/// Normalized equivalence partition over the original node id range,
/// for comparing two saturated e-graphs.
fn partition_over<const T: bool, const P: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, T, P>,
n: usize,
) -> Vec<u32> {
use crate::containers::DenseId;
let mut label = std::collections::HashMap::new();
let mut next = 0u32;
(0..n)
.map(|i| {
let r = eg.class_repr(crate::id::ENodeId::from_usize(i)).to_usize();
*label.entry(r).or_insert_with(|| {
let l = next;
next += 1;
l
})
})
.collect()
}
/// Build the scenario twice, saturate one naive and one semi-naive, and
/// assert they reach the same fixpoint and the same equalities over the
/// original nodes.
fn diff_test(setup: impl Fn() -> (EG, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize)) {
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let (mut a, rules_a, n) = setup();
let ra = saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, 50, &globals,
);
let (mut b, rules_b, n2) = setup();
let rb = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, 50, &globals,
);
assert_eq!(n, n2, "setup must be deterministic");
assert_eq!(ra.saturated, rb.saturated, "saturation flag mismatch");
assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"naive vs semi-naive partition over original nodes differs"
);
}
#[test]
fn diff_commute() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r], n)
});
}
#[test]
fn diff_multi_rule() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r1 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
#[test]
fn diff_const_fold() {
use num_bigint::BigInt;
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
let ilit = eg.ops().id_by_name("ILit").unwrap();
let iadd = eg.ops().id_by_name("IAdd").unwrap();
let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(3)));
let n3 = eg.add_lit(at_ibig, v3);
let lit3 = eg.add(ilit, &[n3]);
let v5 = eg.intern_lit(NiraLitVal::Int(BigInt::from(5)));
let n5 = eg.add_lit(at_ibig, v5);
let lit5 = eg.add(ilit, &[n5]);
let _add = eg.add(iadd, &[lit3, lit5]);
let r = mk_rule(
"(IAdd (ILit x) (ILit y))",
"(ILit (+ x y))",
eg.ops(),
eg.sorts(),
&mut rr,
);
let n = eg.node_count();
(eg, vec![r], n)
});
}
#[test]
fn diff_two_level_fold() {
use num_bigint::BigInt;
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
let ilit = eg.ops().id_by_name("ILit").unwrap();
let iadd = eg.ops().id_by_name("IAdd").unwrap();
let imul = eg.ops().id_by_name("IMul").unwrap();
let mk = |eg: &mut EG, k: i64| {
let v = eg.intern_lit(NiraLitVal::Int(BigInt::from(k)));
let n = eg.add_lit(at_ibig, v);
eg.add(ilit, &[n])
};
let l3 = mk(&mut eg, 3);
let l4 = mk(&mut eg, 4);
let l5 = mk(&mut eg, 5);
let add = eg.add(iadd, &[l4, l5]);
let _mul = eg.add(imul, &[l3, add]);
let add_rule = mk_rule(
"(IAdd (ILit x) (ILit y))",
"(ILit (+ x y))",
eg.ops(),
eg.sorts(),
&mut rr,
);
let mul_rule = mk_rule(
"(IMul (ILit x) (ILit y))",
"(ILit (* x y))",
eg.ops(),
eg.sorts(),
&mut rr,
);
let n = eg.node_count();
(eg, vec![add_rule, mul_rule], n)
});
}
// -- #1: randomized differential proptest --
mod prop {
use super::*;
use proptest::prelude::*;
// Rule pool over the f/g/a/b/c signature (fixed-arity; AC/ACI covered
// separately). Each entry is (lhs, rhs).
const POOL: &[(&str, &str)] = &[
("(f x y)", "(f y x)"), // commute
("(f x y)", "(g x)"), // project
("(g x)", "(f x x)"), // expand
];
/// Build an e-graph from a random node-spec list and a random subset
/// of the rule pool. Deterministic in its inputs, so it can be run
/// twice to produce identical e-graphs.
fn build(
specs: &[u8],
rule_mask: u8,
) -> (EG, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
let og = eg.ops().id_by_name("g").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let mut nodes: Vec<crate::id::ENodeId> = Vec::new();
for &s in specs {
let id = match s % 5 {
0 => eg.add(oa, &[]),
1 => eg.add(ob, &[]),
2 => eg.add(oc, &[]),
3 => {
let c = *nodes.last().unwrap_or(&eg.add(oa, &[]));
eg.add(og, &[c])
}
_ => {
let c1 = nodes.first().copied().unwrap_or_else(|| eg.add(oa, &[]));
let c2 = nodes.last().copied().unwrap_or_else(|| eg.add(ob, &[]));
eg.add(of, &[c1, c2])
}
};
nodes.push(id);
}
let mut rules = Vec::new();
for (bit, (lhs, rhs)) in POOL.iter().enumerate() {
if rule_mask & (1 << bit) != 0 {
rules.push(mk_rule(lhs, rhs, eg.ops(), eg.sorts(), &mut rr));
}
}
let n = eg.node_count();
(eg, rules, n)
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
/// Random input term + random rule subset: naive and semi-naive
/// saturation must agree on the equivalence partition over the
/// original nodes (the observational-equivalence property) and on
/// the saturation flag.
///
/// Node *count* is deliberately not asserted: it is order-dependent
/// (the node store is append-only and which representative wins a
/// merge depends on discovery order), so two equivalent runs may
/// materialize a different number of congruent transient nodes.
#[test]
fn diff_random(specs in proptest::collection::vec(0u8..5, 1..7), mask in 0u8..8) {
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let (mut a, rules_a, n) = build(&specs, mask);
let ra = saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, 40, &globals,
);
let (mut b, rules_b, _n2) = build(&specs, mask);
let rb = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, 40, &globals,
);
prop_assert_eq!(ra.saturated, rb.saturated, "saturation flag");
prop_assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"partition over original nodes"
);
}
}
// Nested same-op rule pool. `diff_random`'s POOL is single-level f/g,
// so deep same-op nesting under multi-round delta propagation — the
// design's flagship case, where a variant stacks several
// FullMinusDelta cursors on the SAME op bucket — is never randomly
// fuzzed there. These rules nest f within f (and g within f) so the
// flattener emits multiple join atoms sharing an op.
const NESTED_POOL: &[(&str, &str)] = &[
("(f (f x y) z)", "(f x (f y z))"), // re-associate
("(f (f x y) z)", "(g x)"), // project from nested
("(f x (g y))", "(f (g y) x)"), // commute past a g
("(g x)", "(f x x)"), // grow
];
const NESTED_REASSOCIATE: u8 = 1 << 0;
const NESTED_PROJECT: u8 = 1 << 1;
const NESTED_GROW: u8 = 1 << 3;
const NESTED_EXPLOSIVE: u8 = NESTED_REASSOCIATE | NESTED_PROJECT | NESTED_GROW;
fn bounded_nested_mask() -> impl Strategy<Value = u8> {
(0u8..16).prop_filter(
"recursive reassociation/projection/growth has a bounded fixture",
|mask| mask & NESTED_EXPLOSIVE != NESTED_EXPLOSIVE,
)
}
fn build_nested(
specs: &[u8],
rule_mask: u8,
) -> (EG, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
let og = eg.ops().id_by_name("g").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let mut nodes: Vec<crate::id::ENodeId> = Vec::new();
for &s in specs {
let id = match s % 5 {
0 => eg.add(oa, &[]),
1 => eg.add(ob, &[]),
2 => eg.add(oc, &[]),
3 => {
let c = *nodes.last().unwrap_or(&eg.add(oa, &[]));
eg.add(og, &[c])
}
_ => {
let c1 = nodes.first().copied().unwrap_or_else(|| eg.add(oa, &[]));
let c2 = nodes.last().copied().unwrap_or_else(|| eg.add(ob, &[]));
eg.add(of, &[c1, c2])
}
};
nodes.push(id);
}
let mut rules = Vec::new();
for (bit, (lhs, rhs)) in NESTED_POOL.iter().enumerate() {
if rule_mask & (1 << bit) != 0 {
rules.push(mk_rule(lhs, rhs, eg.ops(), eg.sorts(), &mut rr));
}
}
let n = eg.node_count();
(eg, rules, n)
}
#[test]
fn diff_nested_growth_blowup_bounded() {
// This is fixed-arity equality saturation, not AC completion or AU.
// `:subsume` would change which source enodes remain matchable.
// This six-node input grows beyond 200 nodes by round five when
// reassociation, nested projection, and duplicating growth interact.
// Later rounds accelerate sharply, so compare the two drivers only
// at this bounded prefix.
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let specs = [4, 2, 3, 4];
let mask = 0b1111;
let round_cap = 5;
let (mut a, rules_a, n) = build_nested(&specs, mask);
let ra = saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, round_cap, &globals,
);
let (mut b, rules_b, _n2) = build_nested(&specs, mask);
let rb = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, round_cap, &globals,
);
assert_eq!(n, 6, "fixture shape");
assert!(
a.node_count() >= 30 * n,
"naive fixture must exhibit growth"
);
assert!(
b.node_count() >= 30 * n,
"semi-naive fixture must exhibit growth"
);
assert!(
!ra.saturated && !rb.saturated,
"the bounded prefix must not claim a fixpoint"
);
assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"bounded nested blowup: partition over original nodes"
);
}
proptest! {
// Reassociation + projection + duplicating growth can create
// exponentially large rounds. The focused test above covers that
// interaction at a fixed boundary; this property samples every other
// combination while fuzzing the stacked-FullMinusDelta machinery.
#![proptest_config(ProptestConfig::with_cases(96))]
/// Differential equivalence for NESTED same-op rules. Same oracle
/// as `diff_random` (equivalence partition over the original
/// nodes) but driving the multi-atom, same-op, stacked-
/// FullMinusDelta machinery that the flat POOL never reaches.
#[test]
fn diff_random_nested(
specs in proptest::collection::vec(0u8..5, 1..5),
mask in bounded_nested_mask(),
) {
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let (mut a, rules_a, n) = build_nested(&specs, mask);
let ra = saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, 12, &globals,
);
let (mut b, rules_b, _n2) = build_nested(&specs, mask);
let rb = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, 12, &globals,
);
prop_assert_eq!(ra.saturated, rb.saturated, "saturation flag");
prop_assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"nested same-op: partition over original nodes"
);
}
}
}
// -- #2: variant disjointness (each new match emitted exactly once) --
//
// Final-state equivalence cannot see double-counting (rewrite application
// is idempotent), so this is tested directly: collect each variant's match
// set in one round and assert they are pairwise disjoint, and that their
// union is exactly the naive matches involving >= 1 new (delta) node.
#[test]
fn variants_disjoint_and_complete() {
for runtime in [false, true] {
variants_disjoint_and_complete_under(runtime);
}
}
/// The variant decomposition holds under both scheduling modes.
///
/// The delta restriction is per atom and independent of where the atom sits
/// in the order (`VariantIndex::mode` reads the compile-time numbering), so
/// re-choosing the order per binding must not move a match from one variant
/// to another, nor lose one: this asserts both halves against the flag.
fn variants_disjoint_and_complete_under(runtime: bool) {
use std::collections::HashSet;
crate::ematch::set_runtime_scheduling(runtime);
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
// 2 join atoms: the outer f and the inner g.
let rule = mk_rule("(f (g x) y)", "(g y)", eg.ops(), eg.sorts(), &mut rr);
let of = eg.ops().id_by_name("f").unwrap();
let og = eg.ops().id_by_name("g").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline (all old): g(a), f(g(a), b).
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let ga = eg.add(og, &[a]);
let _fgab = eg.add(of, &[ga, b]);
eg.rebuild();
eg.clear_touched();
// One round of fresh nodes:
let c = eg.add(oc, &[]);
let gc = eg.add(og, &[c]); // new g
let _fgcc = eg.add(of, &[gc, c]); // new f over NEW g → match with BOTH atoms new
let _fac = eg.add(of, &[ga, c]); // new f over OLD g → match with only f new
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let tset: HashSet<usize> = touched.iter().map(|g| g.to_usize()).collect();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
// Canonical key for a match: class-reps of every node variable.
let key = |m: &crate::ematch::Match<DefaultConfig>| -> Vec<usize> {
(0..rule.query.shape.nodes.len())
.map(|i| {
let vid = crate::ast::VarId::new(i as u16);
eg.class_repr(m.get(vid)).to_usize()
})
.collect::<Vec<_>>()
};
// Run each variant's query (no application) and collect its match keys.
let jatoms = join_atom_indices(&rule.query);
assert!(jatoms.len() >= 2, "scenario needs a multi-atom rule");
let mut per_variant: Vec<HashSet<Vec<usize>>> = Vec::new();
for &di in &jatoms {
let stats = variant_stats(&rule.query, di, &full, &delta);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::variant(&full, &delta, di);
let matches =
crate::ematch::run_query_scheduled(&rule.query, &plan, &eg, &vindex, &globals);
per_variant.push(matches.iter().map(&key).collect());
}
// Pairwise disjoint — no match emitted by two variants.
for i in 0..per_variant.len() {
for j in (i + 1)..per_variant.len() {
let shared: Vec<_> = per_variant[i].intersection(&per_variant[j]).collect();
assert!(
shared.is_empty(),
"variants {i} and {j} both emit matches {shared:?}"
);
}
}
// Completeness: union of variants == naive matches with >= 1 new atom.
let union: HashSet<Vec<usize>> = per_variant.iter().flatten().cloned().collect();
let naive_plan =
crate::schedule::schedule_with_stats(&rule.query, &IndexStats::from_index(&full));
let naive_vindex = VariantIndex::naive(&full);
let naive_matches = crate::ematch::run_query_scheduled(
&rule.query,
&naive_plan,
&eg,
&naive_vindex,
&globals,
);
let naive_new: HashSet<Vec<usize>> = naive_matches
.iter()
.filter(|m| {
// a match is "new" if some join-atom node is in the delta
rule.query.atoms.iter().any(|atom| match atom_node(atom) {
Some(vid) => tset.contains(&m.get(vid).to_usize()),
None => false,
})
})
.map(&key)
.collect();
assert_eq!(
union, naive_new,
"union of variant matches != naive matches involving a new node"
);
// sanity: the scenario actually produced new matches
assert!(!union.is_empty(), "expected at least one new match");
crate::ematch::set_runtime_scheduling(false);
}
// -- per-atom cardinality: same op, different mode → different card --
//
// The crux of flavor-aware scheduling: in one semi-naive flavor, two atoms
// sharing an op can have DIFFERENT driver-scan cardinalities because their
// modes differ (delta vs full∖delta vs full). The old `op_card`-keyed stats
// could not express this — one number per op. `variant_stats` now fills a
// per-atom `atom_card`. This pins the three modes to their exact slice
// sizes for `(f (f x y) z)` (atoms 0 and 1 both op `f`).
#[test]
fn variant_stats_per_atom_cardinality() {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let rule = mk_rule("(f (f x y) z)", "(g z)", eg.ops(), eg.sorts(), &mut rr);
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline: 3 old f-nodes.
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let fab = eg.add(of, &[a, b]);
let _f1 = eg.add(of, &[fab, c]);
let _f2 = eg.add(of, &[fab, a]);
eg.rebuild();
eg.clear_touched();
// One round: add 2 fresh f-nodes (delta), leaving the 3 old ones.
let fac = eg.add(of, &[a, c]);
let _f3 = eg.add(of, &[fac, b]);
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let full_f = full.nodes_by_op(of).len();
let delta_f = delta.nodes_by_op(of).len();
assert!(delta_f >= 1 && delta_f < full_f, "need a partial delta");
let jatoms = join_atom_indices(&rule.query);
assert_eq!(jatoms.len(), 2, "two same-op join atoms expected");
let (a0, a1) = (jatoms[0], jatoms[1]);
// Flavor with delta atom = a1: atom a0 is full∖delta, atom a1 is delta.
// They share op `f` yet must get DIFFERENT per-atom cardinalities.
let stats = variant_stats(&rule.query, a1, &full, &delta);
assert_eq!(
stats.atom_card.get(&a1).copied(),
Some(delta_f),
"delta atom should be sized at the delta bucket"
);
assert_eq!(
stats.atom_card.get(&a0).copied(),
Some(full_f - delta_f),
"the lower (full∖delta) atom should be sized full − delta"
);
assert_ne!(
stats.atom_card.get(&a0),
stats.atom_card.get(&a1),
"same-op atoms in one flavor must get distinct cardinalities"
);
// The opposite flavor (delta atom = a0): a0 is delta, a1 is full.
let stats0 = variant_stats(&rule.query, a0, &full, &delta);
assert_eq!(stats0.atom_card.get(&a0).copied(), Some(delta_f));
assert_eq!(stats0.atom_card.get(&a1).copied(), Some(full_f));
}
// -- #2b: same-op-at-multiple-positions disjointness --
//
// The flagship design example is `mul(add, mul)`: two atoms share the op
// `mul`. The #2 test above uses distinct ops (f over g), so the shared-op
// interaction is never exercised: in one variant, two atoms read the SAME
// `by_op` bucket — one as Delta, one as Difference(full, delta). The
// scheduler now sizes each by its per-atom mode (see `variant_stats` /
// `atom_card`), but correctness rests on the atom NUMBERING regardless
// (mode is `compare(atom_id, i)`), independent of drive order. This pins
// that down: whatever order the scheduler picks, the variants must stay
// disjoint and complete.
//
// Rule `(f (f x y) z)`: atom 0 = outer f, atom 1 = inner f — both op `f`.
#[test]
fn variants_disjoint_same_op() {
use std::collections::HashSet;
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let rule = mk_rule("(f (f x y) z)", "(g z)", eg.ops(), eg.sorts(), &mut rr);
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline (all old): fab = f(a,b); f(fab, c) — one outer match.
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let fab = eg.add(of, &[a, b]);
let _outer_old = eg.add(of, &[fab, c]); // old inner, old outer
eg.rebuild();
eg.clear_touched();
// One round of fresh nodes producing a mix of newness profiles:
let fac = eg.add(of, &[a, c]); // NEW inner f
let _both_new = eg.add(of, &[fac, b]); // new outer over NEW inner → both atoms new
let _outer_new = eg.add(of, &[fab, a]); // new outer over OLD inner → only outer new
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let tset: HashSet<usize> = touched.iter().map(|g| g.to_usize()).collect();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let key = |m: &crate::ematch::Match<DefaultConfig>| -> Vec<usize> {
(0..rule.query.shape.nodes.len())
.map(|i| {
let vid = crate::ast::VarId::new(i as u16);
eg.class_repr(m.get(vid)).to_usize()
})
.collect::<Vec<_>>()
};
let jatoms = join_atom_indices(&rule.query);
assert!(jatoms.len() >= 2, "scenario needs a multi-atom rule");
// Both join atoms must scan the SAME op for this test to be meaningful.
let ops: HashSet<_> = jatoms
.iter()
.map(|&i| atom_op(&rule.query.atoms[i]).unwrap().to_usize())
.collect();
assert_eq!(ops.len(), 1, "expected both join atoms to share one op");
let mut per_variant: Vec<HashSet<Vec<usize>>> = Vec::new();
for &di in &jatoms {
let stats = variant_stats(&rule.query, di, &full, &delta);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::variant(&full, &delta, di);
let matches =
crate::ematch::run_query_scheduled(&rule.query, &plan, &eg, &vindex, &globals);
per_variant.push(matches.iter().map(&key).collect());
}
// Pairwise disjoint.
for i in 0..per_variant.len() {
for j in (i + 1)..per_variant.len() {
let shared: Vec<_> = per_variant[i].intersection(&per_variant[j]).collect();
assert!(
shared.is_empty(),
"same-op variants {i} and {j} both emit {shared:?}"
);
}
}
// Completeness: union == naive matches involving ≥1 new node.
let union: HashSet<Vec<usize>> = per_variant.iter().flatten().cloned().collect();
let naive_plan =
crate::schedule::schedule_with_stats(&rule.query, &IndexStats::from_index(&full));
let naive_vindex = VariantIndex::naive(&full);
let naive_matches = crate::ematch::run_query_scheduled(
&rule.query,
&naive_plan,
&eg,
&naive_vindex,
&globals,
);
let naive_new: HashSet<Vec<usize>> = naive_matches
.iter()
.filter(|m| {
rule.query.atoms.iter().any(|atom| match atom_node(atom) {
Some(vid) => tset.contains(&m.get(vid).to_usize()),
None => false,
})
})
.map(&key)
.collect();
assert_eq!(
union, naive_new,
"same-op: union of variant matches != naive matches involving a new node"
);
// The scenario must actually exercise a match where BOTH atoms are new
// (the case only variant 0 may claim) and one where only the outer is.
assert!(
union.len() >= 2,
"expected ≥2 distinct new matches, got {union:?}"
);
}
// -- #2c: 3-atom same-op — stacked FullMinusDelta cursors --
//
// Rule `(f (f (f x y) z) w)`: three nested f's, atoms 0/1/2 all op `f`.
// Variant 2 puts atoms 0 AND 1 in FullMinusDelta and atom 2 in Delta —
// two `Difference(full, delta)` cursors active in distinct joins of one
// plan. Because all three atoms share the op, `variant_stats` collapses
// `op_card[f]` to the delta size for EVERY atom (the scheduler can't tell
// them apart by cost), so disjointness can only come from `atom_id` mode.
#[test]
fn variants_disjoint_three_atom_same_op() {
use std::collections::HashSet;
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let rule = mk_rule(
"(f (f (f x y) z) w)",
"(g w)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline: f(f(f(a,b),c),a) entirely old.
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let inner_old = eg.add(of, &[a, b]);
let mid_old = eg.add(of, &[inner_old, c]);
let _top_old = eg.add(of, &[mid_old, a]);
eg.rebuild();
eg.clear_touched();
// One round: a new innermost f drives a fully-new tower, plus a new
// top over the OLD middle (only-outer-new), exercising several
// newness profiles across the three positions.
let inner_new = eg.add(of, &[b, c]); // NEW deepest
let mid_new = eg.add(of, &[inner_new, a]); // NEW middle over new inner
let _top_new = eg.add(of, &[mid_new, b]); // all three new
let _top_over_old = eg.add(of, &[mid_old, c]); // only outermost new
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let tset: HashSet<usize> = touched.iter().map(|g| g.to_usize()).collect();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let key = |m: &crate::ematch::Match<DefaultConfig>| -> Vec<usize> {
(0..rule.query.shape.nodes.len())
.map(|i| {
eg.class_repr(m.get(crate::ast::VarId::new(i as u16)))
.to_usize()
})
.collect::<Vec<_>>()
};
let jatoms = join_atom_indices(&rule.query);
assert_eq!(jatoms.len(), 3, "rule must have three join atoms");
let mut per_variant: Vec<HashSet<Vec<usize>>> = Vec::new();
for &di in &jatoms {
let stats = variant_stats(&rule.query, di, &full, &delta);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::variant(&full, &delta, di);
let matches =
crate::ematch::run_query_scheduled(&rule.query, &plan, &eg, &vindex, &globals);
per_variant.push(matches.iter().map(&key).collect());
}
for i in 0..per_variant.len() {
for j in (i + 1)..per_variant.len() {
let shared: Vec<_> = per_variant[i].intersection(&per_variant[j]).collect();
assert!(shared.is_empty(), "variants {i},{j} both emit {shared:?}");
}
}
let union: HashSet<Vec<usize>> = per_variant.iter().flatten().cloned().collect();
let naive_plan =
crate::schedule::schedule_with_stats(&rule.query, &IndexStats::from_index(&full));
let naive_matches =
crate::ematch::run_query(&naive_plan, &eg, &VariantIndex::naive(&full), &globals);
let naive_new: HashSet<Vec<usize>> = naive_matches
.iter()
.filter(|m| {
rule.query.atoms.iter().any(|atom| match atom_node(atom) {
Some(vid) => tset.contains(&m.get(vid).to_usize()),
None => false,
})
})
.map(&key)
.collect();
assert_eq!(
union, naive_new,
"3-atom same-op: variant union != naive matches with a new node"
);
assert!(!union.is_empty(), "scenario produced no new matches");
}
// -- #2d: multi-round differential, deep same-op nesting --
//
// The randomized proptest's rule POOL is single-level f/g only, so deep
// same-op nesting under multi-round delta propagation (where round K's
// recanonicalizations feed round K+1's delta through stacked
// FullMinusDelta atoms) is never differentially checked. This drives a
// tower of nested f's with a commute + an associativity-style rewrite so
// that merges — not just fresh nodes — populate the touched log.
#[test]
fn diff_deep_same_op_multiround() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Left-nested tower f(f(f(a,b),c),a).
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let i0 = eg.add(of, &[a, b]);
let i1 = eg.add(of, &[i0, c]);
let _i2 = eg.add(of, &[i1, a]);
// commute drives recanonicalization; the re-association rule
// rewrites the same op at two depths, repeatedly feeding delta.
let r_comm = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let r_assoc = mk_rule(
"(f (f x y) z)",
"(f x (f y z))",
eg.ops(),
eg.sorts(),
&mut rr,
);
let n = eg.node_count();
(eg, vec![r_comm, r_assoc], n)
});
}
// -- #3: AC / ACI differential (variadic decompose paths) --
// `(f x y) -> (add x y)` creates a fresh AC node in round 0; round 1's
// delta then drives the AC subset rule, exercising DecomposeAC / by_contains
// under semi-naive.
#[test]
fn diff_ac() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r1 = mk_rule("(f x y)", "(add x y)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(add x y ..rest)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
#[test]
fn diff_aci() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r1 = mk_rule("(f x y)", "(union x y)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(union x y ..rest)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
// -- #2e: variadic atoms keep their delta mode when driven from a parent --
//
// Regression test for a disjointness defect found by bi-abduction: every
// variant's per-atom mode is realized ONLY through `Step::Join.atom_id`
// (see ematch::run_join — mode is read off the join step). The implicit
// precondition is therefore: *every join atom emits a `Step::Join` in
// every variant's plan.* For variadic atoms (A/AC/ACI) the trap is
// emitting NO `Step::Join` when the atom's node var is already bound:
// a variant driving from an enclosing atom (binding the variadic child
// via `ExtractChild`) would leave the atom's `FullMinusDelta` exclusion
// silently unexecuted. The bound-node path therefore mirrors the
// fixed-arity `Plain` one: emit a `ByRepr ∩ ByOp` re-join carrying
// `atom_id` so the mode is applied.
//
// Without the re-join the failure is redundant re-emission only (the
// union still equals the naive new-match set, and application is
// idempotent, so the final state is correct; diff_ac / diff_aci and the
// whole .egg corpus cannot see it). The re-join recovers disjointness, i.e. the
// lost semi-naive work savings on parent-driven variadic atoms.
//
// Asserts BOTH: pairwise-disjoint variant sets AND completeness against
// naive, for `(f (add x ..r1) (add y ..r2))` (two `add` atoms sharing op).
#[test]
fn variadic_atoms_keep_delta_mode_when_parent_driven() {
use std::collections::HashSet;
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let rule = mk_rule(
"(f (add x ..r1) (add y ..r2))",
"(g x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let of = eg.ops().id_by_name("f").unwrap();
let oadd = eg.ops().id_by_name("add").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline (all old): f(add(a,b), add(b,c)).
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let add_ab = eg.add(oadd, &[a, b]);
let add_bc = eg.add(oadd, &[b, c]);
let _f_old = eg.add(of, &[add_ab, add_bc]);
eg.rebuild();
eg.clear_touched();
// One round of fresh nodes: a new add and new f's over old/new adds.
let add_mset = eg.add(oadd, &[a, c]); // NEW add
let _f_both_new = eg.add(of, &[add_mset, add_mset]); // both add atoms bind the new add
let _f_mixed = eg.add(of, &[add_ab, add_mset]); // old add, new add
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let tset: HashSet<usize> = touched.iter().map(|g| g.to_usize()).collect();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let jatoms = join_atom_indices(&rule.query);
let add_atoms: Vec<_> = jatoms
.iter()
.copied()
.filter(|&i| atom_op(&rule.query.atoms[i]) == Some(oadd))
.collect();
assert_eq!(add_atoms.len(), 2, "expected two add atoms sharing the op");
// Key by the tuple of NODE IDS each join atom binds — exactly the
// node-tuple the design's leftmost-new-atom partition is defined over.
let key = |m: &crate::ematch::Match<DefaultConfig>| -> Vec<usize> {
jatoms
.iter()
.map(|&ai| {
let vid = atom_node(&rule.query.atoms[ai]).unwrap();
m.get(vid).to_usize()
})
.collect::<Vec<_>>()
};
let mut per_variant: Vec<HashSet<Vec<usize>>> = Vec::new();
for &di in &jatoms {
let stats = variant_stats(&rule.query, di, &full, &delta);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::variant(&full, &delta, di);
let matches =
crate::ematch::run_query_scheduled(&rule.query, &plan, &eg, &vindex, &globals);
per_variant.push(matches.iter().map(&key).collect());
}
// Disjointness: with the parent-driven variadic re-join in place, the
// FullMinusDelta mode is applied, so no node-tuple is emitted twice.
for i in 0..per_variant.len() {
for j in (i + 1)..per_variant.len() {
let shared: Vec<_> = per_variant[i].intersection(&per_variant[j]).collect();
assert!(
shared.is_empty(),
"variadic same-op variants {i},{j} both emit {shared:?} — \
the parent-driven re-join in emit_variadic_join regressed"
);
}
}
// Completeness: the union still covers exactly the naive new-match set,
// so the disjointness fix dropped nothing.
let union: HashSet<Vec<usize>> = per_variant.iter().flatten().cloned().collect();
let naive_plan =
crate::schedule::schedule_with_stats(&rule.query, &IndexStats::from_index(&full));
let naive_matches =
crate::ematch::run_query(&naive_plan, &eg, &VariantIndex::naive(&full), &globals);
let naive_new: HashSet<Vec<usize>> = naive_matches
.iter()
.filter(|m| {
rule.query.atoms.iter().any(|atom| match atom_node(atom) {
Some(vid) => tset.contains(&m.get(vid).to_usize()),
None => false,
})
})
.map(&key)
.collect();
assert_eq!(
union, naive_new,
"variadic same-op: variant union != naive matches with a new node"
);
assert!(!union.is_empty(), "AC scenario produced no new matches");
}
// -- #2e2: parent-driven variadic re-join when the class is NOT a singleton --
//
// The fix re-joins a bound variadic node via `ByRepr ∩ ByOp`. That is a
// singleton in the common case, but if the node's class holds TWO distinct
// same-op variadic nodes (e.g. two `add`s merged into one class), the
// re-join's leapfrog iterates BOTH — each then feeds DecomposeAC
// separately. Bi-abduction target: the re-join must re-bind to *each*
// congruent node, not silently collapse to the representative, or matches
// that decompose differently per node would be lost. End-to-end
// differential under saturation is the oracle.
#[test]
fn diff_variadic_parent_driven_nonsingleton_class() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oadd = eg.ops().id_by_name("add").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
// Two DISTINCT add nodes, then merge them into one class so the
// class carries two same-op variadic members.
let add_ab = eg.add(oadd, &[a, b]);
let add_bc = eg.add(oadd, &[b, c]);
eg.merge(add_ab, add_bc);
// An f over that class drives the parent-driven variadic re-join.
let _f = eg.add(of, &[add_ab, c]);
// Rule with a parent-driven AC atom (subset → project a member).
let r1 = mk_rule("(f (add x ..r) z)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(g x)", "(f (add x x) x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
// -- #2f: congruent duplicates via merge — key-faithfulness --
//
// Bi-abduction: the disjointness oracle keys matches by CLASS-REPS. That
// is a faithful proxy for the design's node-tuple partition only if the
// surviving nodes in each `by_op` bucket have distinct class-rep keys.
// Congruent duplicates (two nodes, same op + same child-reprs, in the
// same class) arise from MERGES, not `add` (which hash-conses). None of
// the other disjointness tests merge to create that situation. Here a
// merge makes f(a,c) and f(b,c) congruent; the round's delta must still
// partition the survivors' matches disjointly and completely.
#[test]
fn variants_disjoint_with_congruent_dups() {
use std::collections::HashSet;
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
// single-atom rule keeps the focus on bucket contents, not nesting
let rule = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let of = eg.ops().id_by_name("f").unwrap();
let og = eg.ops().id_by_name("g").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
// Baseline: a, b, c, f(a,c), f(b,c), g(a). All old.
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let _fac = eg.add(of, &[a, c]);
let _fbc = eg.add(of, &[b, c]);
let _ga = eg.add(og, &[a]);
eg.rebuild();
eg.clear_touched();
// Round: merge a~b. Now f(a,c) and f(b,c) become congruent — both
// survive in by_op[f] until congruence closure merges them, and the
// recanonicalized one lands in `touched`. Add a genuinely fresh node.
eg.merge(a, b);
let _fcc = eg.add(of, &[c, c]); // fresh
eg.rebuild();
let touched: Vec<crate::id::ENodeId> = eg.touched().to_vec();
let tset: HashSet<usize> = touched.iter().map(|g| g.to_usize()).collect();
let full = IndexStore::build(&eg);
let delta = IndexStore::build_delta(&eg, &touched);
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
// Key by the actual surviving NODE id (not class-rep) so congruent
// duplicates, if any survive distinctly, are counted separately and a
// double-emission would be caught.
let key = |m: &crate::ematch::Match<DefaultConfig>| -> Vec<usize> {
(0..rule.query.shape.nodes.len())
.map(|i| m.get(crate::ast::VarId::new(i as u16)).to_usize())
.collect::<Vec<_>>()
};
let jatoms = join_atom_indices(&rule.query);
let mut per_variant: Vec<HashSet<Vec<usize>>> = Vec::new();
for &di in &jatoms {
let stats = variant_stats(&rule.query, di, &full, &delta);
let plan = crate::schedule::schedule_with_stats(&rule.query, &stats);
let vindex = VariantIndex::variant(&full, &delta, di);
let matches =
crate::ematch::run_query_scheduled(&rule.query, &plan, &eg, &vindex, &globals);
per_variant.push(matches.iter().map(&key).collect());
}
for i in 0..per_variant.len() {
for j in (i + 1)..per_variant.len() {
let shared: Vec<_> = per_variant[i].intersection(&per_variant[j]).collect();
assert!(
shared.is_empty(),
"variants {i},{j} both emit node-tuple {shared:?}"
);
}
}
// Completeness against naive, keyed identically by node id.
let union: HashSet<Vec<usize>> = per_variant.iter().flatten().cloned().collect();
let naive_plan =
crate::schedule::schedule_with_stats(&rule.query, &IndexStats::from_index(&full));
let naive_matches =
crate::ematch::run_query(&naive_plan, &eg, &VariantIndex::naive(&full), &globals);
let naive_new: HashSet<Vec<usize>> = naive_matches
.iter()
.filter(|m| {
rule.query.atoms.iter().any(|atom| match atom_node(atom) {
Some(vid) => tset.contains(&m.get(vid).to_usize()),
None => false,
})
})
.map(&key)
.collect();
assert_eq!(
union, naive_new,
"congruent-dups: variant union (by node id) != naive new matches"
);
}
// -- #2g: subsumption during a round stays sound (differential) --
//
// Bi-abduction: `build_delta` skips FLAG_SUBSUMED nodes (index.rs), but
// `recanonize_node` pushes to `touched` BEFORE collision/subsumption is
// resolved (caches.rs). So a node can be in `touched` yet absent from the
// delta because it was subsumed. The claim that survives only if the
// subsumed node's canonical form is also carried by a NON-subsumed node
// that the delta still indexes (or the match is genuinely old). A merge
// that makes two f-nodes congruent exercises exactly this — subsume the
// loser and confirm semi-naive still matches naive.
#[test]
fn semi_subsume_during_round_sound() {
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let setup = || -> (EG, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let fac = eg.add(of, &[a, c]);
let fbc = eg.add(of, &[b, c]);
// Merge a~b so f(a,c) and f(b,c) are congruent, then subsume one.
eg.merge(a, b);
eg.rebuild();
eg.subsume(fac);
// After subsumption fbc should still carry the f(_,c) form.
let _ = fbc;
let r1 = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(g x)", "(f x x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
};
let (mut a, rules_a, n) = setup();
saturate::<DefaultConfig, _, _, _, false, false>(
&rules_a, &mut a, &NiraModel, 50, &globals,
);
let (mut b, rules_b, n2) = setup();
saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules_b, &mut b, &NiraModel, 50, &globals,
);
assert_eq!(n, n2);
assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"subsumption-in-round: semi-naive diverged from naive"
);
}
// -- #2i: A-sequence (concat) patterns under semi-naive --
//
// GAP: every variadic test so far uses AC/ACI (`add`/`union`). The A
// (associative, ordered) path goes through `ExpandA`, a DIFFERENT decompose
// routine than DecomposeAC/ACI — and the parent-driven-variadic re-join fix
// in `emit_variadic_join` applies to A atoms too but was only ever
// exercised on AC. Differential equivalence over a rule whose LHS nests a
// `concat` inside an `f` drives `ExpandA` under the variant decomposition.
#[test]
fn diff_a_sequence_nested() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oconcat = eg.ops().id_by_name("concat").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let oc = eg.ops().id_by_name("c").unwrap();
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let c = eg.add(oc, &[]);
let cat = eg.add(oconcat, &[a, b, c]);
let _f = eg.add(of, &[cat, a]);
// f over a sliding-window concat → project the middle element;
// then a rule that rebuilds a concat to keep deltas flowing.
let r1 = mk_rule(
"(f (concat ..pre x ..suf) z)",
"(g x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let r2 = mk_rule("(g x)", "(concat x x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
// -- #2j: A-sequence top-level (ExpandA as the delta-driven atom) --
// A bare `(concat ..pre x ..suf)` rule whose only join atom IS the A atom,
// so in rounds ≥1 ExpandA runs delta-restricted (mode Delta on the A join).
#[test]
fn diff_a_sequence_toplevel() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let oconcat = eg.ops().id_by_name("concat").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let _cat = eg.add(oconcat, &[a, b]);
let r1 = mk_rule(
"(concat x y)",
"(concat y x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let r2 = mk_rule(
"(concat ..pre x ..suf)",
"(g x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
// -- #2k: sibling atoms sharing a variable (Eq-joined, not parent-child) --
//
// GAP: every disjointness/differential test chains atoms parent-to-child
// (resolved by ExtractChild). `(f (g x) (g x))` instead gives two SIBLING
// `g` atoms — both children of f — sharing `x`, joined by the nonlinear
// `CheckEq`/`CopyBinding` path rather than ExtractChild. Under semi-naive
// each `g` atom gets its own variant, and the cross-atom Eq join must
// compose with the delta decomposition.
#[test]
fn diff_sibling_shared_var() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let og = eg.ops().id_by_name("g").unwrap();
let of = eg.ops().id_by_name("f").unwrap();
let oa = eg.ops().id_by_name("a").unwrap();
let ob = eg.ops().id_by_name("b").unwrap();
let a = eg.add(oa, &[]);
let b = eg.add(ob, &[]);
let ga = eg.add(og, &[a]);
let gb = eg.add(og, &[b]);
let _f_same = eg.add(of, &[ga, ga]); // matches (f (g x) (g x))
let _f_diff = eg.add(of, &[ga, gb]); // does not (x≠y)
// RHS grows new g's so later rounds re-drive the shared-var g atoms.
let r1 = mk_rule("(f (g x) (g x))", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
});
}
// -- #2l: PROOFS=true under semi-naive --
//
// GAP: the design's "Not To Be Confused With has_history" section warns the
// touched-log push co-locates with the proof-history save in
// `recanonize_node` but must fire on DIFFERENT conditions (every round vs.
// once ever). `semi_restore_safety` uses TRACK=true but PROOFS=false, so
// that co-location is never exercised. Here PROOFS=true: semi-naive must
// still reach the same partition as naive while the history save runs.
#[test]
fn semi_with_proofs_matches_naive() {
type ProofEg = EGraph<DefaultConfig, NiraLitVal, false, true>;
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let build = || -> (ProofEg, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = ProofEg::from_model(&NiraModel);
let e = eg.intern_sort("IExpr");
eg.register_op2("f", e, e, e);
eg.register_op1("g", e, e);
eg.register_op0("a", e);
eg.register_op0("b", e);
eg.register_op0("c", e);
eg.register_mset("add", e, e);
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
// commute + project + AC growth — multiple rounds of recanon so the
// history-save path (once per node) and touched-push (per round)
// both fire and must stay independent.
let r1 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(f x y)", "(add x y)", eg.ops(), eg.sorts(), &mut rr);
let r3 = mk_rule("(add x y ..rest)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2, r3], n)
};
let (mut a, rules_a, n) = build();
let ra = saturate::<DefaultConfig, _, _, _, false, true>(
&rules_a, &mut a, &NiraModel, 50, &globals,
);
let (mut b, rules_b, n2) = build();
let rb = saturate_semi::<DefaultConfig, _, _, _, false, true>(
&rules_b, &mut b, &NiraModel, 50, &globals,
);
assert_eq!(n, n2);
assert_eq!(
ra.saturated, rb.saturated,
"PROOFS: saturation flag mismatch"
);
assert_eq!(
partition_over(&a, n),
partition_over(&b, n),
"PROOFS=true: semi-naive diverged from naive"
);
}
// -- #2h: nested-variadic differential under saturation --
//
// Guards the soundness claim for the variadic-mode defect above: even
// though variant sets overlap on the variadic path, the FINAL state must
// still match naive across multiple rounds (idempotent application makes
// the extra emissions harmless). Rule nests an AC atom inside an f, so the
// defect path (drive-from-parent, variadic child via ExtractChild) fires
// every round, and the const-fold-style AC rule keeps producing deltas.
#[test]
fn diff_nested_variadic_saturation() {
diff_test(|| {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let add_ab = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[add_ab, c]);
// f over an add subset → project; add subset grows g's; g feeds f.
let r1 = mk_rule("(f (add x ..r) z)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule(
"(add x y ..rest)",
"(f (add x y) x)",
eg.ops(),
eg.sorts(),
&mut rr,
);
let r3 = mk_rule("(g x)", "(add x x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2, r3], n)
});
}
// -- #4: restore-safety (touched cleared on restore; correct afterward) --
#[test]
fn semi_restore_safety() {
type TrackedEg = EGraph<DefaultConfig, NiraLitVal, true, false>;
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let build = || -> (TrackedEg, Vec<PreparedRule<OpId, SortId, NiraLitVal>>, usize) {
let mut eg = TrackedEg::from_model(&NiraModel);
let e = eg.intern_sort("IExpr");
eg.register_op2("f", e, e, e);
eg.register_op1("g", e, e);
eg.register_op0("a", e);
eg.register_op0("b", e);
let mut rr = crate::registry::RuleRegistry::<true>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r1 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
let r2 = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let n = eg.node_count();
(eg, vec![r1, r2], n)
};
let (mut eg, rules, n) = build();
let tok = eg.mark(crate::containers::ShrinkPolicy::Never);
let _ = saturate_semi::<DefaultConfig, _, _, _, true, false>(
&rules, &mut eg, &NiraModel, 50, &globals,
);
eg.restore(tok);
assert!(
eg.touched().is_empty(),
"restore must clear the touched log (no stale delta)"
);
// Semi-naive after a restore reaches the same fixpoint as a fresh
// naive run from the same input.
let rs = saturate_semi::<DefaultConfig, _, _, _, true, false>(
&rules, &mut eg, &NiraModel, 50, &globals,
);
assert!(rs.saturated);
let (mut egn, rules_n, n2) = build();
let _ = saturate::<DefaultConfig, _, _, _, true, false>(
&rules_n, &mut egn, &NiraModel, 50, &globals,
);
assert_eq!(n, n2);
assert_eq!(
partition_over(&eg, n),
partition_over(&egn, n),
"post-restore semi-naive diverged from naive"
);
}
// -- #5: empty delta / fixpoint is a stable no-op --
#[test]
fn semi_fixpoint_stable() {
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let setup = || {
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rr);
(eg, vec![r])
};
let (mut eg, rules) = setup();
let r1 = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules, &mut eg, &NiraModel, 50, &globals,
);
assert!(
r1.saturated,
"should reach a fixpoint (final round empty-delta)"
);
// Re-running on the saturated graph must be a 1-round no-op: round 0
// re-finds the matches, every application is idempotent → 0 changes.
let r2 = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&rules, &mut eg, &NiraModel, 50, &globals,
);
assert!(r2.saturated);
assert_eq!(
r2.iterations, 1,
"re-saturating a fixpoint must terminate in one no-op round"
);
}
#[test]
fn semi_no_match_fixpoint_in_one() {
// A rule that cannot match → semi-naive saturates immediately.
let globals = crate::resolve::GlobalCtx::<SortId, crate::id::ENodeId>::new();
let mut eg = make_eg();
let mut rr = crate::registry::RuleRegistry::<false>::new();
eg.add(eg.ops().id_by_name("a").unwrap(), &[]); // only an `a`, no `f`
let r = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rr);
let res = saturate_semi::<DefaultConfig, _, _, _, false, false>(
&[r],
&mut eg,
&NiraModel,
10,
&globals,
);
assert!(res.saturated);
assert_eq!(res.iterations, 1);
}
#[test]
fn saturate_commute() {
let mut eg = make_eg();
let mut rules = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let rule = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rules);
let res = saturate::<DefaultConfig, _, _, _, false, false>(
&[rule],
&mut eg,
&NiraModel,
10,
&crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
);
assert!(res.saturated);
let fba = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
assert_eq!(eg.find(fab), eg.find(fba));
}
#[test]
fn saturate_fixpoint_in_one() {
// No matching terms → saturates immediately
let mut eg = make_eg();
let mut rules = crate::registry::RuleRegistry::<false>::new();
eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let rule = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rules);
let res = saturate::<DefaultConfig, _, _, _, false, false>(
&[rule],
&mut eg,
&NiraModel,
10,
&crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
);
assert!(res.saturated);
assert_eq!(res.iterations, 1);
}
#[test]
fn saturate_constant_fold() {
use num_bigint::BigInt;
let mut eg = make_eg();
let mut rules = crate::registry::RuleRegistry::<false>::new();
let model = NiraModel;
let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
let ilit = eg.ops().id_by_name("ILit").unwrap();
let iadd = eg.ops().id_by_name("IAdd").unwrap();
// Build (IAdd (ILit 3) (ILit 5))
let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(3)));
let n3 = eg.add_lit(at_ibig, v3);
let lit3 = eg.add(ilit, &[n3]);
let v5 = eg.intern_lit(NiraLitVal::Int(BigInt::from(5)));
let n5 = eg.add_lit(at_ibig, v5);
let lit5 = eg.add(ilit, &[n5]);
let add_node = eg.add(iadd, &[lit3, lit5]);
let rule = mk_rule(
"(IAdd (ILit x) (ILit y))",
"(ILit (+ x y))",
eg.ops(),
eg.sorts(),
&mut rules,
);
let res = saturate::<DefaultConfig, _, _, _, false, false>(
&[rule],
&mut eg,
&model,
10,
&crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
);
assert!(res.saturated);
// (ILit 8) should be merged with (IAdd (ILit 3) (ILit 5))
let v8 = eg.intern_lit(NiraLitVal::Int(BigInt::from(8)));
let n8 = eg.add_lit(at_ibig, v8);
let lit8 = eg.add(ilit, &[n8]);
assert_eq!(eg.find(add_node), eg.find(lit8));
}
#[test]
fn saturate_multi_rule_chain() {
// f(a, b) with commute + distribute: f(x,y)→f(y,x), f(x,y)→g(x)
let mut eg = make_eg();
let mut rules = crate::registry::RuleRegistry::<false>::new();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let r1 = mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rules);
let r2 = mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rules);
let res = saturate::<DefaultConfig, _, _, _, false, false>(
&[r1, r2],
&mut eg,
&NiraModel,
10,
&crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
);
assert!(res.saturated);
// g(a) and g(b) should both be merged with f(a,b)
let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
let gb = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
assert_eq!(eg.find(fab), eg.find(ga));
assert_eq!(eg.find(fab), eg.find(gb));
}
#[test]
fn two_level_constant_fold() {
// (IMul (ILit 3) (IAdd (ILit 4) (ILit 5)))
// Step 1: IAdd folds → (ILit 9)
// Step 2: after rebuild, IMul should see (ILit 3) and (ILit 9) → (ILit 27)
use num_bigint::BigInt;
let mut eg = make_eg();
let mut rules = crate::registry::RuleRegistry::<false>::new();
let model = NiraModel;
let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
let ilit = eg.ops().id_by_name("ILit").unwrap();
let iadd = eg.ops().id_by_name("IAdd").unwrap();
let imul = eg.ops().id_by_name("IMul").unwrap();
let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(3)));
let n3 = eg.add_lit(at_ibig, v3);
let lit3 = eg.add(ilit, &[n3]);
let v4 = eg.intern_lit(NiraLitVal::Int(BigInt::from(4)));
let n4 = eg.add_lit(at_ibig, v4);
let lit4 = eg.add(ilit, &[n4]);
let v5 = eg.intern_lit(NiraLitVal::Int(BigInt::from(5)));
let n5 = eg.add_lit(at_ibig, v5);
let lit5 = eg.add(ilit, &[n5]);
let add_node = eg.add(iadd, &[lit4, lit5]);
let mul_node = eg.add(imul, &[lit3, add_node]);
let add_rule = mk_rule(
"(IAdd (ILit x) (ILit y))",
"(ILit (+ x y))",
eg.ops(),
eg.sorts(),
&mut rules,
);
let mul_rule = mk_rule(
"(IMul (ILit x) (ILit y))",
"(ILit (* x y))",
eg.ops(),
eg.sorts(),
&mut rules,
);
let globals = crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new();
let res = saturate::<DefaultConfig, _, _, _, false, false>(
&[add_rule, mul_rule],
&mut eg,
&model,
10,
&globals,
);
assert!(res.saturated);
let v9 = eg.intern_lit(NiraLitVal::Int(BigInt::from(9)));
let n9 = eg.add_lit(at_ibig, v9);
let lit9 = eg.add(ilit, &[n9]);
assert_eq!(
eg.find(add_node),
eg.find(lit9),
"Add should fold to (ILit 9)"
);
let v27 = eg.intern_lit(NiraLitVal::Int(BigInt::from(27)));
let n27 = eg.add_lit(at_ibig, v27);
let lit27 = eg.add(ilit, &[n27]);
assert_eq!(
eg.find(mul_node),
eg.find(lit27),
"Mul should fold to (ILit 27)"
);
}
/// Not a real test — run with `cargo test saturate_demo -- --nocapture --ignored` to visualize.
#[test]
#[ignore]
fn saturate_demo() {
use num_bigint::BigInt;
let mut eg = make_eg();
let mut rule_reg = crate::registry::RuleRegistry::<false>::new();
let model = NiraModel;
let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
let ilit = eg.ops().id_by_name("ILit").unwrap();
let iadd = eg.ops().id_by_name("IAdd").unwrap();
let f = eg.ops().id_by_name("f").unwrap();
let g = eg.ops().id_by_name("g").unwrap();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
// f(a, b), f(b, c), g(f(a, b))
let fab = eg.add(f, &[a, b]);
let _fbc = eg.add(f, &[b, c]);
let _gfab = eg.add(g, &[fab]);
// IAdd(ILit(2), ILit(3))
let v2 = eg.intern_lit(NiraLitVal::Int(BigInt::from(2)));
let n2 = eg.add_lit(at_ibig, v2);
let lit2 = eg.add(ilit, &[n2]);
let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(3)));
let n3 = eg.add_lit(at_ibig, v3);
let lit3 = eg.add(ilit, &[n3]);
let add23 = eg.add(iadd, &[lit2, lit3]);
eg.show("before_saturation");
let rules: Vec<(&str, PreparedRule<OpId, SortId, NiraLitVal>)> = vec![
(
"commute",
mk_rule("(f x y)", "(f y x)", eg.ops(), eg.sorts(), &mut rule_reg),
),
(
"extract",
mk_rule("(f x y)", "(g x)", eg.ops(), eg.sorts(), &mut rule_reg),
),
(
"const-fold",
mk_rule(
"(IAdd (ILit x) (ILit y))",
"(ILit (+ x y))",
eg.ops(),
eg.sorts(),
&mut rule_reg,
),
),
];
let res = saturate_trace::<DefaultConfig, _, _, _, false, false>(
&rules,
&mut eg,
&model,
20,
&crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
);
eg.rebuild();
eg.show("after_saturation");
eprintln!(
"Saturated: {}, iterations: {}",
res.saturated, res.iterations
);
eprintln!("E-nodes: {}", eg.node_count());
// Verify some expected equalities
assert!(res.saturated);
let fba = eg.add(f, &[b, a]);
assert_eq!(eg.find(fab), eg.find(fba), "f(a,b) = f(b,a)");
let ga = eg.add(g, &[a]);
assert_eq!(eg.find(fab), eg.find(ga), "f(a,b) = g(a)");
let v5 = eg.intern_lit(NiraLitVal::Int(BigInt::from(5)));
let n5 = eg.add_lit(at_ibig, v5);
let lit5 = eg.add(ilit, &[n5]);
assert_eq!(
eg.find(add23),
eg.find(lit5),
"IAdd(ILit(2), ILit(3)) = ILit(5)"
);
}
}