package libzipperposition

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file superposition.ml

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
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
(* This file is free software, part of Zipperposition. See file "license" for more details. *)

open Logtk
open Libzipperposition

module BV = CCBV
module T = Term
module O = Ordering
module S = Subst
module Lit = Literal
module Lits = Literals
module Comp = Comparison
module US = Unif_subst
module P = Position
module HO = Higher_order

let section = Util.Section.make ~parent:Const.section "sup"

(* flag meaning the clause has been simplified already *)
let flag_simplified = SClause.new_flag()

module type S = Superposition_intf.S

(* statistics *)
let stat_basic_simplify_calls = Util.mk_stat "sup.basic_simplify calls"
let stat_basic_simplify = Util.mk_stat "sup.basic_simplify"
let stat_superposition_call = Util.mk_stat "sup.superposition calls"
let stat_equality_resolution_call = Util.mk_stat "sup.equality_resolution calls"
let stat_equality_factoring_call = Util.mk_stat "sup.equality_factoring calls"
let stat_subsumption_call = Util.mk_stat "sup.subsumption_calls"
let stat_eq_subsumption_call = Util.mk_stat "sup.equality_subsumption calls"
let stat_eq_subsumption_success = Util.mk_stat "sup.equality_subsumption success"
let stat_subsumed_in_active_set_call = Util.mk_stat "sup.subsumed_in_active_set calls"
let stat_subsumed_by_active_set_call = Util.mk_stat "sup.subsumed_by_active_set calls"
let stat_clauses_subsumed = Util.mk_stat "sup.num_clauses_subsumed"
let stat_demodulate_call = Util.mk_stat "sup.demodulate calls"
let stat_demodulate_step = Util.mk_stat "sup.demodulate steps"
let stat_semantic_tautology = Util.mk_stat "sup.semantic_tautologies"
let stat_condensation = Util.mk_stat "sup.condensation"
let stat_ext_dec = Util.mk_stat "sup.ext_dec calls"
let stat_ext_inst = Util.mk_stat "sup.ext_inst calls"
let stat_clc = Util.mk_stat "sup.clc"
let stat_complete_eq = Util.mk_stat "ho.complete_eq.steps"
let stat_orphan_checks = Util.mk_stat "orphan checks"


let prof_demodulate = ZProf.make "sup.demodulate"
let prof_back_demodulate = ZProf.make "sup.backward_demodulate"
let prof_pos_simplify_reflect = ZProf.make "sup.simplify_reflect+"
let prof_neg_simplify_reflect = ZProf.make "sup.simplify_reflect-"
let prof_clc = ZProf.make "sup.contextual_literal_cutting"
let prof_semantic_tautology = ZProf.make "sup.semantic_tautology"
let prof_condensation = ZProf.make "sup.condensation"
let prof_basic_simplify = ZProf.make "sup.basic_simplify"
let prof_subsumption = ZProf.make "sup.subsumption"
let prof_eq_subsumption = ZProf.make "sup.equality_subsumption"
let prof_subsumption_set = ZProf.make "sup.forward_subsumption"
let prof_subsumption_in_set = ZProf.make "sup.backward_subsumption"
let prof_infer_active = ZProf.make "sup.infer_active"
let prof_infer_passive = ZProf.make "sup.infer_passive"
let prof_ext_dec = ZProf.make "sup.ext_dec"
let prof_infer_fluidsup_active = ZProf.make "sup.infer_fluidsup_active"
let prof_infer_fluidsup_passive = ZProf.make "sup.infer_fluidsup_passive"
let prof_infer_equality_resolution = ZProf.make "sup.infer_equality_resolution"
let prof_infer_equality_factoring = ZProf.make "sup.infer_equality_factoring"
let prof_queues = ZProf.make "sup.queues"

let k_trigger_bool_inst = Flex_state.create_key ()
let k_trigger_bool_ind = Flex_state.create_key ()
let k_sup_at_vars = Flex_state.create_key ()
let k_sup_in_var_args = Flex_state.create_key ()
let k_sup_under_lambdas = Flex_state.create_key ()
let k_sup_at_var_headed = Flex_state.create_key ()
let k_sup_from_var_headed = Flex_state.create_key ()
let k_fluidsup = Flex_state.create_key ()
let k_subvarsup = Flex_state.create_key ()
let k_dupsup = Flex_state.create_key ()
let k_lambdasup = Flex_state.create_key ()
let k_demod_in_var_args = Flex_state.create_key ()
let k_lambda_demod = Flex_state.create_key ()
let k_ext_dec_lits = Flex_state.create_key ()
let k_ext_rules_max_depth = Flex_state.create_key ()
let k_ext_rules_kind = Flex_state.create_key ()
let k_use_simultaneous_sup = Flex_state.create_key ()
let k_unif_alg = Flex_state.create_key ()
let k_fluidsup_penalty = Flex_state.create_key ()
let k_dupsup_penalty = Flex_state.create_key ()
let k_ground_subs_check = Flex_state.create_key ()
let k_solid_subsumption = Flex_state.create_key ()
let k_dot_sup_into = Flex_state.create_key ()
let k_dot_sup_from = Flex_state.create_key ()
let k_dot_simpl = Flex_state.create_key ()
let k_dot_demod_into = Flex_state.create_key ()
let k_recognize_injectivity = Flex_state.create_key ()
let k_complete_ho_unification = Flex_state.create_key ()
let k_max_infs = Flex_state.create_key ()
let k_switch_stream_extraction = Flex_state.create_key ()
let k_dont_simplify = Flex_state.create_key ()
let k_use_semantic_tauto = Flex_state.create_key ()
let k_restrict_fluidsup = Flex_state.create_key ()
let k_check_sup_at_var_cond = Flex_state.create_key ()
let k_restrict_hidden_sup_at_vars = Flex_state.create_key ()
let k_ho_disagremeents = Flex_state.create_key ()
let k_bool_demod = Flex_state.create_key ()
let k_immediate_simplification = Flex_state.create_key ()
let k_arg_cong = Flex_state.create_key ()
let k_bool_eq_fact = Flex_state.create_key ()
let k_cc_simplify = Flex_state.create_key ()
let k_local_rw = Flex_state.create_key ()



let _NO_LAMSUP = -1


module Make(Env : Env.S) : S with module Env = Env = struct
  module Env = Env
  module Ctx = Env.Ctx
  module C = Env.C
  module PS = Env.ProofState
  module I = PS.TermIndex
  module TermIndex = PS.TermIndex
  module SubsumIdx = PS.SubsumptionIndex
  module UnitIdx = PS.UnitIndex
  module Stm = Stream.Make(struct
      module Ctx = Ctx
      module C = C
    end)
  module StmQ = StreamQueue.Make(struct
      module Stm = Stm
      module Env = Env end)
  module Bools = Booleans.Make(Env)

  (** {5 Stream queue} *)
  let k_stmq = Flex_state.create_key ()
  let _cc_simpl = ref (Congruence.FO.create ~size:256 ())


  let _stmq () = Env.flex_get k_stmq

  (** {5 Index Management} *)

  let _idx_sup_into = ref (TermIndex.empty ())
  let _idx_lambdasup_into = ref (TermIndex.empty ())
  let _idx_fluidsup_into = ref (TermIndex.empty ())
  let _idx_subvarsup_into = ref (TermIndex.empty ())
  let _idx_dupsup_into = ref (TermIndex.empty ())
  let _idx_sup_from = ref (TermIndex.empty ())
  let _idx_back_demod = ref (TermIndex.empty ())
  let _idx_fv = ref (SubsumIdx.empty ())
  (* let _idx_fv = ref (SubsumIdx.of_signature (Ctx.signature()) ()) *)

  let _idx_simpl = ref (UnitIdx.empty ())
  let _cls_w_pred_vars = ref (Type.Map.empty) (* type --> (clause,var) *)
  let _trigger_bools   = ref (Type.Map.empty) (* type --> boolean trigger *)
  let _ext_dec_from_idx = ref (ID.Map.empty)
  let _ext_dec_into_idx = ref (ID.Map.empty)

  let idx_sup_into () = !_idx_sup_into
  let idx_sup_from () = !_idx_sup_from
  let idx_fv () = !_idx_fv

  (* Beta-Eta-Normalizes terms before comparing them. Note that the Clause
     module calls Ctx.ord () independently, but clauses should be normalized
     independently by simplification rules. *) 
  let ord =
    Ctx.ord ()

  (* Given a list of streams, tries getting a single clause 
     from each of the streams; returns obtained clauses and
     partially evaluated streams *)
  let force_getting_cl streams = 
    let rec aux ((clauses, streams) as acc) = function 
      | [] -> acc
      | (penalty, parents, stm) :: xs ->
        begin
          match stm () with
          | OSeq.Nil -> aux acc xs 
          | OSeq.Cons((Some cl), stm') ->
            aux (cl::clauses, (Stm.make ~penalty ~parents stm')::streams) xs
          | OSeq.Cons(None, stm') ->
            aux (clauses, (Stm.make ~penalty ~parents stm')::streams) xs
        end 
    in
    aux ([], []) streams


  let get_triggers c =
    let trivial_trigger t =
      let body = snd @@ T.open_fun t in
      T.is_var body || T.is_true_or_false body in

    Literals.fold_terms ~ord ~subterms:true ~eligible:C.Eligible.always 
      ~which:`All (C.lits c) ~fun_bodies:false 
    |> Iter.filter_map (fun (t,p) -> 
        let ty = Term.ty t and hd = Term.head_term t in
        let cached_t = Subst.FO.canonize_all_vars t in
        if not (Term.Set.mem cached_t !Higher_order.prim_enum_terms) &&
           Type.is_fun ty && Type.returns_prop ty && not (Term.is_var hd) &&
           not (trivial_trigger t) then (
          Some t
        ) else None
      )

  let has_bad_occurrence_elsewhere c var pos =
    assert(T.is_var var);
    Lits.fold_terms ~ord ~subterms:true ~eligible:C.Eligible.always ~which:`All
      (C.lits c)
    |> Iter.exists (fun (t, pos') -> 
      not (Position.equal pos pos') &&
      (* variable appears at a prefix position
        somewhere else (pos ≠ pos') *)
      match T.view t with
      | T.App(hd, _) -> T.equal hd var
      | _ -> false
    )
  
  let instantiate_w_bool ~clause ~var ~trigger =
    assert(Type.equal (T.ty var) (T.ty trigger));

    let cl_sc, trig_sc = 0, 1 in
    let subst = Subst.FO.bind' Subst.empty (T.as_var_exn var, cl_sc) (trigger, trig_sc) in
    let renaming = Subst.Renaming.create () in
    let lits = Literals.apply_subst renaming subst (C.lits clause, cl_sc) in
    let lits = Literals.map (fun t -> Lambda.eta_reduce @@ Lambda.snf t) lits in
      let proof =
        Proof.Step.inference 
          ~rule:(Proof.Rule.mk "triggered_bool_instantiation") 
          ~tags:[Proof.Tag.T_ho; Proof.Tag.T_cannot_orphan]
          [C.proof_parent_subst renaming (clause, cl_sc) subst] in
    let res = C.create_a lits proof ~penalty:(C.penalty clause) ~trail:(C.trail clause) in
    (* CCFormat.printf "instatiate:@.c:@[%a@]@.subst:@[%a@]@.res:@[%a@]@." C.pp clause Subst.pp subst C.pp res; *)
    res

  let inst_clauses_w_trigger t =
    let triggers = Type.Map.get_or ~default:[] (T.ty t) !_trigger_bools in
    if not (CCList.mem ~eq:T.equal t triggers) then (
      _trigger_bools := Type.Map.update (T.ty t) (function 
        | None -> Some [t]
        | Some res -> Some (t :: res)
      ) !_trigger_bools;

      Type.Map.get_or ~default:[] (T.ty t) !_cls_w_pred_vars
      |> CCList.map (fun (clause,var) -> instantiate_w_bool ~clause ~var ~trigger:t)
    ) else []

  let insert_new_trigger t =
    inst_clauses_w_trigger t
    |> CCList.to_iter
    |> Env.add_passive


  let handle_new_pred_var_clause (clause,var) =
    assert(T.is_var var);
    let ty = T.ty var in
    
    Type.Map.get_or ~default:[] ty !_trigger_bools
    |> CCList.map (fun trigger -> instantiate_w_bool ~clause ~var ~trigger)
    |> CCList.to_iter
    |> Env.add_passive;

    _cls_w_pred_vars := Type.Map.update ty (function 
      | None -> Some [(clause, var)]
      | Some res -> Some ((clause, var) :: res)
    ) !_cls_w_pred_vars;

    Signal.ContinueListening

  let handle_new_skolem_sym (c,trigger) =
    let trig_hd = T.head_term trigger in
    assert(T.is_const trig_hd);
    assert(ID.is_postcnf_skolem (T.as_const_exn trig_hd));

    if C.proof_depth c <  Env.flex_get k_trigger_bool_inst 
    then  insert_new_trigger trigger;
    
    Signal.ContinueListening


  let update_triggers cl =
    (* if triggered boolean instantiation is off
       k_trigger_bool_inst is -1 *)
    if C.proof_depth cl < Env.flex_get k_trigger_bool_inst then (
      let new_triggers = (get_triggers cl) in
      if not (Iter.is_empty new_triggers) then (
        Iter.iter insert_new_trigger new_triggers
    ));
    Signal.ContinueListening

  let trigger_induction cl =
    (* abstracts away closed subterm from the term t
       by replacing it with (accordingly shifted) DB variable 0 *)
    let abstract ~subterm t =
      assert(T.DB.is_closed subterm);

      let rec aux ~depth t =
        if T.equal subterm t then (
          T.bvar ~ty:(T.ty subterm) depth
        ) else (
          match T.view t with
          | T.App(hd, args) ->
            let hd' = aux ~depth hd in
            let args' = List.map (aux ~depth) args in
            if T.equal hd hd' && T.same_l args args' then t
            else T.app hd' args'
          | T.AppBuiltin(hd, args) ->
            let args' = List.map (aux ~depth) args in
            if T.same_l args args' then t
            else T.app_builtin ~ty:(T.ty t) hd args'
          | T.Fun _ ->
            let pref, body = T.open_fun t in
            let body' = aux ~depth:(depth+(List.length pref)) body in
            if T.equal body body' then t else T.fun_l pref body'
          | _ -> t
        ) in
      
      let res = aux ~depth:0 t in
      assert (Type.equal (T.ty res) (T.ty t));
      if T.equal res t then None else (Some res) in
    
    let make_triggers lhs rhs sign =
      let lhs_body, rhs_body = snd (Term.open_fun lhs), snd (Term.open_fun rhs) in
      let immediate_args =
        if (T.is_const (T.head_term lhs_body)) && 
           (T.is_const (T.head_term rhs_body)) then (
          List.sort_uniq T.compare (T.args lhs_body @ T.args rhs_body)
        ) else [] in
      CCList.filter_map (fun arg -> 
        if T.DB.is_closed arg && not (Type.is_tType (T.ty arg)) then (
          match abstract ~subterm:arg lhs, abstract ~subterm:arg rhs with
          | Some(lhs'), Some(rhs') ->
            assert (Type.equal (T.ty lhs') (T.ty rhs'));
            (* Flipping the sign that is present in conjecture,
               to prove the negated conjecture using induction *)
            let build_body sign = if sign then T.Form.neq else T.Form.eq in
            let res = T.fun_ (T.ty arg) (build_body sign lhs' rhs') in
            assert (T.DB.is_closed res);
            Some res
          | _ -> None
        ) else None
      ) immediate_args in

    if C.proof_depth cl < Env.flex_get k_trigger_bool_ind &&
       CCOpt.is_some (C.distance_to_goal cl) then (
      match C.lits cl with
      | [| Literal.Equation(lhs, rhs, sign) |] ->
        CCList.flat_map inst_clauses_w_trigger (make_triggers lhs rhs sign)
      | _ -> []
    ) else []

  let fluidsup_applicable cl =
    not (Env.flex_get k_restrict_fluidsup) ||
    Array.length (C.lits cl) <= 2 ||  (C.proof_depth cl) == 0

  (* Syntactic overapproximation of fluid or deep terms *)
  let is_fluid_or_deep c t = 
    (* Fluid (1): Applied variables *)
    T.is_var (T.head_term t) && not (CCList.is_empty @@ T.args t) 
    (* Fluid (2): A lambda-expression that might eta-reduce to a non-lambda-expression after substitution (overapproximated) *)
    || T.is_fun t && not (T.is_ground t)                          
    (* Deep: A variable also occurring in a lambda-expression or in an argument of a variable in the same clause*)
    || match T.as_var t with
    | Some v -> 
      Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false 
        ~ty_args:false ~which:`All ~ord ~subterms:true
        ~eligible:(fun _ _ -> true) (C.lits c)
      |> Iter.exists 
        (fun (t, _) -> 
           match T.view t with
           | App (head, args) when T.is_var head -> 
             Iter.exists (HVar.equal Type.equal v) (args |> Iter.of_list |> Iter.flat_map T.Seq.vars)
           | Fun (_, body) -> 
             Iter.exists (HVar.equal Type.equal v) (T.Seq.vars body)
           | _ -> false)
    | None -> false

  let ext_rule_eligible cl =
    Env.flex_get k_ext_rules_max_depth < 0 ||
    C.proof_depth cl <= Env.flex_get k_ext_rules_max_depth

  (* apply operation [f] to some parts of the clause [c] just added/removed
     from the active set *)
  let _update_active f c =
    (* index subterms that can be rewritten by superposition *)
    let sup_at_vars = Env.flex_get k_sup_at_vars in
    let sup_in_var_args = Env.flex_get k_sup_in_var_args in
    let sup_under_lambdas = Env.flex_get k_sup_under_lambdas in
    let sup_at_var_headed = Env.flex_get k_sup_at_var_headed in
    let sup_from_var_headed = Env.flex_get k_sup_from_var_headed in
    let fluidsup = Env.flex_get k_fluidsup in
    let subvarsup = Env.flex_get k_subvarsup in
    let dupsup = Env.flex_get k_dupsup in
    let lambdasup = Env.flex_get k_lambdasup in
    let demod_in_var_args = Env.flex_get k_demod_in_var_args in
    let lambda_demod = Env.flex_get k_lambda_demod in


    _idx_sup_into :=
      Lits.fold_terms ~vars:sup_at_vars ~var_args:sup_in_var_args ~fun_bodies:sup_under_lambdas 
        ~ty_args:false ~ord ~which:`Max ~subterms:true  ~eligible:(C.Eligible.res c) (C.lits c)
      |> Iter.filter (fun (t, _) ->
          (* Util.debugf ~section 3 "@[ Filtering vars %a,1  @]" (fun k-> k T.pp t); *)
          (not (T.is_var t) || T.is_ho_var t))
      (* TODO: could exclude more variables from the index:
         they are not needed if they occur with the same args everywhere in the clause *)
      |> Iter.filter (fun (t, _) ->
          (* Util.debugf ~section 3 "@[ Filtering vars %a,2  @]" (fun k-> k T.pp t); *)
          sup_at_var_headed || not (T.is_var (T.head_term t)))
      |> Iter.fold
        (fun tree (t, pos) ->
           (* Util.debugf ~section 3 "@[ Adding %a to into index %B @]" (fun k-> k T.pp t !_sup_under_lambdas); *)
           let with_pos = C.WithPos.({term=t; pos; clause=c;}) in
           f tree t with_pos)
        !_idx_sup_into;

    (* index subterms that can be rewritten by FluidSup *)
    if fluidsup then
      _idx_fluidsup_into :=
        Lits.fold_terms ~vars:true ~var_args:false ~fun_bodies:false
          ~ty_args:false ~ord ~which:`Max ~subterms:true
          ~eligible:(C.Eligible.res c) (C.lits c)
        |> Iter.filter (fun (t, _) -> is_fluid_or_deep c t) 
        |> Iter.fold
          (fun tree (t, pos) ->
             let with_pos = C.WithPos.({term=t; pos; clause=c;}) in
             f tree t with_pos)
          !_idx_fluidsup_into;

     (* index subterms that can be rewritten by FluidSup *)
    if subvarsup then
      _idx_subvarsup_into :=
        Lits.fold_terms ~vars:true ~var_args:false ~fun_bodies:false
          ~ty_args:false ~ord ~which:`Max ~subterms:true
          ~eligible:(C.Eligible.res c) (C.lits c)
        |> Iter.filter (fun (t, pos) ->
          match T.view t with
          | T.Var _ -> has_bad_occurrence_elsewhere c t pos
          | T.App(hd, [_]) when T.is_var hd -> has_bad_occurrence_elsewhere c hd pos
          | _ -> false
        ) 
        |> Iter.fold
          (fun tree (t, pos) ->
             let with_pos = C.WithPos.({term=t; pos; clause=c;}) in
             f tree t with_pos)
          !_idx_subvarsup_into;

    if dupsup then 
      _idx_dupsup_into :=
        Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false
          ~ty_args:false ~ord ~which:`Max ~subterms:true
          ~eligible:(C.Eligible.res c) (C.lits c)
        |> Iter.filter (fun (t, _) -> 
            T.is_var (T.head_term t) && not (CCList.is_empty @@ T.args t)
            && Type.is_ground (T.ty t)) (* Only applied variables *)
        |> Iter.fold
          (fun tree (t, pos) ->
             let with_pos = C.WithPos.({term=t; pos; clause=c;}) in
             f tree t with_pos)
          !_idx_dupsup_into;

    (* index subterms that can be rewritten by LambdaSup --
       the ones that can rewrite those are actually the ones
       already indexed by _idx_sup_from*)
    if lambdasup != _NO_LAMSUP then
      _idx_lambdasup_into :=
        Lits.fold_terms ~vars:sup_at_vars ~var_args:sup_in_var_args
          ~fun_bodies:true ~ty_args:false ~ord
          ~which:`Max ~subterms:true
          ~eligible:(C.Eligible.res c) (C.lits c)
        (* We are going only under lambdas *)
        |> Iter.filter_map (fun (t, p) ->
            if not (T.is_fun t) then None
            else (let tyargs, body = T.open_fun t in
                  let new_pos = List.fold_left (fun p _ -> P.(append p (body stop))) p tyargs in
                  let hd = T.head_term body in
                  if (not (T.is_var body) || T.is_ho_var body) &&
                     (not (T.is_const hd) || not (ID.is_skolem (T.as_const_exn hd))) &&
                     (sup_at_var_headed || not (T.is_var (T.head_term body))) then
                    ( (*CCFormat.printf "Adding %a to LS index.\n" T.pp body; *)
                      Some (body, new_pos)) else None))
        |> Iter.fold
          (fun tree (t, pos) ->
             let with_pos = C.WithPos.({term=t; pos; clause=c;}) in
             f tree t with_pos)
          !_idx_lambdasup_into;

    (* index terms that can rewrite into other clauses *)
    _idx_sup_from :=
      Lits.fold_eqn ~ord ~both:true ~sign:true
        ~eligible:(C.Eligible.param c) (C.lits c)
      |> Iter.filter((fun (l, _, _, _) -> not (T.equal l T.false_)))
      |> Iter.filter(fun (l, _, _, _) -> 
          sup_from_var_headed || not (T.is_app_var l))
      |> Iter.fold
        (fun tree (l, _, sign, pos) ->
           assert sign;
           let with_pos = C.WithPos.({term=l; pos; clause=c;}) in
           f tree l with_pos)
        !_idx_sup_from ;
    (* terms that can be demodulated: all subterms (but vars) *)
    _idx_back_demod :=
      (* TODO: allow demod under lambdas under certain conditions (DemodExt) *)
      Lits.fold_terms ~vars:false ~var_args:(demod_in_var_args) ~fun_bodies:lambda_demod  
        ~ty_args:false ~ord ~subterms:true ~which:`All
        ~eligible:C.Eligible.always (C.lits c)
      |> Iter.fold
        (fun tree (t, pos) ->
           let with_pos = C.WithPos.( {term=t; pos; clause=c} ) in
           f tree t with_pos)
        !_idx_back_demod;
    Signal.ContinueListening

  (* update simpl. index using the clause [c] just added or removed to
     the simplification set *)
  let _update_simpl f c = 
    assert (CCArray.for_all Lit.no_prop_invariant (C.lits c));
    let idx = !_idx_simpl in
    let idx' = match C.lits c with
      | [| Lit.Equation (l,r,sign) |] when sign || T.equal r T.true_ ->
        if Env.flex_get k_bool_demod || sign then (
          let l, r = if sign then l, r else l, T.false_ in
          (* do not use formulas for rewriting... can have adverse
             effects on lazy cnf *)
          if !Lazy_cnf.enabled &&
             (T.is_appbuiltin l || (T.is_appbuiltin r && not @@ T.is_true_or_false r) ) then idx
          else (
            begin match Ordering.compare ord l r with
              | Comparison.Gt ->
                f idx (l,r,true,c)
              | Comparison.Lt ->
                f idx (r,l,true,c)
              | Comparison.Incomparable ->
                let idx = f idx (l,r,true,c) in
                f idx (r,l,true,c)
              | Comparison.Eq -> idx  (* no modif *)
            end)) 
        else idx
      | [| Lit.Equation (l,r,false) |] ->
        f idx (l,r,false,c)
      | _ -> idx
    in
    _idx_simpl := idx';
    Signal.ContinueListening

  let insert_into_ext_dec_index index (c,pos,t) =
    let key = T.head_exn t in
    let clause_map = ID.Map.find_opt key !index in
    let clause_map = match clause_map with 
      | None -> C.Tbl.create 8
      | Some res -> res in
    let all_pos =
      (try 
         (t,pos) :: (C.Tbl.find clause_map c)
       with _ -> 
         [(t,pos)]) in
    C.Tbl.replace clause_map c all_pos;
    index := ID.Map.add key clause_map !index

  let remove_from_ext_dec_index index (c,_,t) =
    let key = T.head_exn t in
    let clause_map = ID.Map.find_opt key !index in
    match clause_map with
    | None -> Util.debugf ~section 1 "all clauses allready deleted." CCFun.id
    | Some res -> (
        C.Tbl.remove res c;
        index := ID.Map.add key res !index
      )

  let update_ext_dec_indices f c =
    let which, eligible = if Env.flex_get k_ext_dec_lits = `OnlyMax 
      then `Max, C.Eligible.res c else `All, C.Eligible.always in
    if Env.flex_get k_ext_rules_kind != `Off &&
       ext_rule_eligible c then (
      Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false ~ty_args:false 
        ~ord ~which ~subterms:true ~eligible (C.lits c)
      |> Iter.filter (fun (t, _) ->
          not (T.is_var t) || T.is_ho_var t)
      |> Iter.filter (fun (t, _) ->
          not (T.is_var (T.head_term t)) &&
          T.is_const (T.head_term t) && Term.has_ho_subterm t)
      |> Iter.iter
        (fun (t, pos) ->
           f _ext_dec_into_idx (c,pos,t));

      let eligible = if Env.flex_get k_ext_dec_lits = `OnlyMax then C.Eligible.param c 
        else C.Eligible.always in
      Lits.fold_eqn ~ord ~both:true ~sign:true ~eligible (C.lits c)
      |> Iter.iter
        (fun (l, _, sign, pos) ->
           assert sign;
           let hd,_ = T.as_app l in
           if T.is_const hd && Term.has_ho_subterm l then (
             f _ext_dec_from_idx (c,pos,l)
           )));
    Signal.ContinueListening


  let () =
    Signal.on PS.ActiveSet.on_add_clause
      (fun c ->
         _idx_fv := SubsumIdx.add !_idx_fv c;
         ignore(_update_active TermIndex.add c);
         ignore(update_triggers c);
         update_ext_dec_indices insert_into_ext_dec_index c);
    Signal.on PS.ActiveSet.on_remove_clause
      (fun c ->
         _idx_fv := SubsumIdx.remove !_idx_fv c;
         ignore(update_ext_dec_indices remove_from_ext_dec_index c);
         _update_active TermIndex.remove c);
    Signal.on PS.SimplSet.on_add_clause
      (_update_simpl UnitIdx.add);
    Signal.on PS.SimplSet.on_remove_clause
      (_update_simpl UnitIdx.remove);
    ()

  (** {5 Inference Rules} *)

  (* ----------------------------------------------------------------------
   * Superposition rule
   * ---------------------------------------------------------------------- *)

  type supkind =
    | Classic
    | FluidSup
    | LambdaSup
    | DupSup
    | SubVarSup

  let kind_to_str = function
    | Classic -> "sup"
    | FluidSup -> "fluidSup"
    | LambdaSup -> "lambdaSup"
    | DupSup -> "dupSup"
    | SubVarSup -> "subVarSup"

  (* all the information needed for a superposition inference *)
  module SupInfo = struct
    type t = {
      active : C.t;
      active_pos : Position.t; (* position of [s] *)
      scope_active : int;
      s : T.t; (* lhs of rule *)
      t : T.t; (* rhs of rule *)
      passive : C.t;
      passive_pos : Position.t; (* position of [u_p] *)
      passive_lit : Lit.t;
      scope_passive : int;
      u_p : T.t; (* rewritten subterm *)
      subst : US.t;
      sup_kind: supkind;
    }
  end

  exception ExitSuperposition of string

  (* Checks whether we must allow superposition at variables to be complete. *)
  let sup_at_var_condition info var replacement =
    if Env.flex_get k_check_sup_at_var_cond then (
      let open SupInfo in
      let us = info.subst in
      let subst = US.subst us in
      let renaming = S.Renaming.create () in
      let replacement' = S.FO.apply renaming subst (replacement, info.scope_active) in
      let var' = S.FO.apply renaming subst (var, info.scope_passive) in
      if (not (Type.is_fun (Term.ty var')) || not (O.might_flip ord var' replacement'))
      then (
        Util.debugf ~section 3
          "Cannot flip: %a = %a"
          (fun k->k T.pp var' T.pp replacement');
        false (* If the lhs vs rhs cannot flip, we don't need a sup at var *)
      )
      else (
        (* Check whether var occurs only with the same arguments everywhere. *)
        let unique_args_of_var c =
          C.lits c
          |> Lits.fold_terms ~vars:true ~ty_args:false ~which:`All ~ord ~subterms:true ~eligible:(fun _ _ -> true)
          |> Iter.fold_while
            (fun unique_args (t,_) ->
               if Term.equal (fst (T.as_app t)) var
               then (
                 if CCOpt.equal (CCList.equal T.equal) unique_args (Some (snd (T.as_app t)))
                 then (unique_args, `Continue) (* found the same arguments of var again *)
                 else (None, `Stop) (* different arguments of var found *)
               ) else (unique_args, `Continue) (* this term doesn't have var as head *)
            )
            None
        in
        let unique_vars =
          if Env.flex_get Higher_order.k_prune_arg_fun != `NoPrune
          then None
          else unique_args_of_var info.passive in
        match unique_vars with
        | Some _ ->
          Util.debugf ~section 5
            "Variable %a has same args everywhere in %a"
            (fun k->k T.pp var C.pp info.passive);
          false (* If var occurs with the same arguments everywhere, we don't need sup at vars *)
        | None ->
          (* Check whether Cσ is >= C[var -> replacement]σ *)
          (* This is notoriously hard to implement due to the scope mechanism.
          Especially note that var may be of polymorphic type and subst might
          map to var, which can easily cause cyclic substitutions. *)
          let passive'_lits = Lits.apply_subst renaming subst (C.lits info.passive, info.scope_passive) in
          let fresh_var = HVar.fresh ~ty:(T.ty var) () in
          let subst_fresh_var = US.FO.bind US.empty (T.as_var_exn var, info.scope_passive) (T.var fresh_var, info.scope_passive) in
          let passive_fresh_var = Lits.apply_subst Subst.Renaming.none (US.subst subst_fresh_var) (C.lits info.passive, info.scope_passive) in
          let subst_replacement = Unif.FO.bind subst (fresh_var, info.scope_passive) (replacement, info.scope_active) in
          let passive_t'_lits = Lits.apply_subst renaming subst_replacement (passive_fresh_var, info.scope_passive) in
          if Lits.compare_multiset ~ord passive'_lits passive_t'_lits = Comp.Gt
          then (
            Util.debugf ~section 3
              "Sup at var condition is not fulfilled because: %a >= %a"
              (fun k->k Lits.pp passive'_lits Lits.pp passive_t'_lits);
            false
          )
          else true (* If Cσ is either <= or incomparable to C[var -> replacement]σ, we need sup at var.*)
      )
    ) 
    else false (* if k_check_sup_at_var_cond is false, never allow superposition at variable headed terms *)


  (* check for hidden superposition at variables,	
     e.g. superposing g x = f x into h (x b) = a to give h (f b) = a.	
     Returns a term only containing the concerned variable	
     and a term consisting of the part of info.t that unifies with the variable,	
     e.g. (x, f) in the example above. *)	
  let is_hidden_sup_at_var info =	
    let open SupInfo in	
    let active_idx = Lits.Pos.idx info.active_pos in	
    begin match T.view info.u_p with	
      | T.App (head, args) ->	
        begin match T.as_var head with	
          | Some _ ->	
            (* rewritten term is variable-headed *)	
            begin match T.view info.s, T.view info.t  with	
              | T.App (f, ss), T.App (g, tt) 
                when List.length ss >= List.length args 
                      && List.length tt >= List.length args ->	
                let s_args = Array.of_list ss in	
                let t_args = Array.of_list tt in
                let sub_s_args = 
                  Array.sub s_args (Array.length s_args - List.length args) (List.length args)
                  |> CCArray.to_list in
                let sub_t_args =
                  Array.sub t_args (Array.length t_args - List.length args) (List.length args)
                  |> CCArray.to_list in
                if	
                  Array.length s_args >= List.length args	
                  && Array.length t_args >= List.length args	
                  (* Check whether the last argument(s) of s and t are equal *)	
                  && List.for_all (fun (s,t) -> T.equal s t) (List.combine sub_s_args sub_t_args) 
                  (* Check whether they are all variables that occur nowhere else *)	
                  && CCList.(Array.length s_args - List.length args --^ Array.length s_args)	
                     |> List.for_all (fun idx ->	
                       match T.as_var (Array.get s_args idx) with	
                         | Some v ->	
                           (* Check whether variable occurs in previous arguments: *)	
                           not (CCArray.exists (T.var_occurs ~var:v) (Array.sub s_args 0 idx))	
                           && not (CCArray.exists (T.var_occurs ~var:v) (Array.sub t_args 0 (Array.length t_args - List.length args))	
                                   (* Check whether variable occurs in heads: *)	
                                   && not (T.var_occurs ~var:v f)	
                                   && not (T.var_occurs ~var:v g)	
                                   (* Check whether variable occurs in other literals: *)	
                                   && not (List.exists (Literal.var_occurs v) (CCArray.except_idx (C.lits info.active) active_idx)))	
                         | None -> false	
                     )	
                then	
                  (* Calculate the part of t that unifies with the variable *)	
                  let t_prefix = T.app g (Array.to_list (Array.sub t_args 0 (Array.length t_args - List.length args))) in	
                  Some (head, t_prefix)	
                else	
                  None 
              | _ -> None
            end
            
          | None -> None	
        end	
      | _ -> None	
    end


  let dup_sup_apply_subst t sc_a sc_p subst renaming =
    let z, args = T.as_app t in
    assert(T.is_var z);
    assert(CCList.length args >= 2);
    let u_n, t' = CCList.take_drop (List.length args - 1) args in
    let in_passive = S.FO.apply renaming subst (T.app z u_n, sc_p) in
    let t' = S.FO.apply renaming subst (List.hd t', sc_a) in
    T.app in_passive [t']

  (* Helper that does one or zero superposition inference, with all
     the given parameters. Clauses have a scope. *)
  let do_classic_superposition info =
    let open SupInfo in
    let module P = Position in
    Util.incr_stat stat_superposition_call;
    let sc_a = info.scope_active in
    let sc_p = info.scope_passive in
    assert (InnerTerm.DB.closed (info.s:>InnerTerm.t));
    assert (info.sup_kind == LambdaSup || InnerTerm.DB.closed (info.u_p:T.t:>InnerTerm.t));
    assert (not(T.is_var info.u_p) || T.is_ho_var info.u_p || info.sup_kind = FluidSup);
    assert (Env.flex_get k_sup_at_var_headed || info.sup_kind = FluidSup || 
            info.sup_kind = DupSup || info.sup_kind = SubVarSup || not (T.is_var (T.head_term info.u_p)));
    let active_idx = Lits.Pos.idx info.active_pos in
    let shift_vars = if info.sup_kind = LambdaSup then 0 else -1 in
    let passive_idx, passive_lit_pos = Lits.Pos.cut info.passive_pos in
    assert(Array.for_all Literal.no_prop_invariant (C.lits info.passive));
    assert(Array.for_all Literal.no_prop_invariant (C.lits info.passive));
    try
      if (info.sup_kind = LambdaSup && US.has_constr info.subst) then (
        raise (ExitSuperposition "Might sneak in bound vars through constraints.")
      );

      let renaming = S.Renaming.create () in
      let us = info.subst in
      let subst = US.subst us in
      let lambdasup_vars =
        if (info.sup_kind = LambdaSup) then (
          Term.Seq.subterms ~include_builtin:true info.u_p |> Iter.filter Term.is_var |> Term.Set.of_iter)
        else Term.Set.empty in
      let t' = if info.sup_kind != DupSup then 
          S.FO.apply ~shift_vars renaming subst (info.t, sc_a)
        else dup_sup_apply_subst info.t sc_a sc_p subst renaming in
      Util.debugf ~section 2
        "@[<2>sup, kind %s(%d)@ (@[<2>%a[%d]@ @[s=%a@]@ @[t=%a, t'=%a@]@])@ \
         (@[<2>%a[%d]@ @[passive_lit=%a@]@ @[p=%a@]@])@ with subst=@[%a@]@]"
        (fun k->k (kind_to_str info.sup_kind) (Term.Set.cardinal lambdasup_vars) C.pp info.active sc_a T.pp info.s T.pp info.t
            T.pp t' C.pp info.passive sc_p Lit.pp info.passive_lit
            Position.pp info.passive_pos US.pp info.subst);

      if(info.sup_kind = LambdaSup &&
         T.Set.exists (fun v ->
             not @@ T.DB.is_closed @@  Subst.FO.apply ~shift_vars renaming subst (v,sc_p))
           lambdasup_vars) then (
        let msg = "LambdaSup: an into free variable sneaks in bound variable" in
        Util.debugf ~section 3 "%s" (fun k->k msg);
        raise @@ ExitSuperposition(msg);
      );

      if info.sup_kind = FluidSup && 
         Term.equal (Lambda.eta_reduce @@ Lambda.snf @@ t') 
           (Lambda.eta_reduce @@ Lambda.snf @@ S.FO.apply ~shift_vars renaming subst (info.s, sc_a)) then (
        let msg = "Passive literal is trivial after substitution" in
        Util.debugf ~section 3 "%s" (fun k->k msg);
        raise @@ ExitSuperposition(msg);
      );

      begin match info.passive_lit, info.passive_pos with
        | Lit.Equation (_, v, true), P.Arg(_, P.Left P.Stop)
        | Lit.Equation (v, _, true), P.Arg(_, P.Right P.Stop) ->
          (* are we in the specific, but no that rare, case where we
             rewrite s=t using s=t (into a tautology t=t)? *)
          (* TODO: use Unif.FO.eq? *)
          let v' = S.FO.apply ~shift_vars:0 renaming subst (v, sc_p) in
          if T.equal t' v'
          then (
            Util.debugf ~section 2 "will yield a tautology" (fun k->k);
            raise (ExitSuperposition "will yield a tautology");)
        | _ -> ()
      end;

      if (info.sup_kind = LambdaSup) then (
        let vars_act = CCArray.except_idx (C.lits info.active) active_idx
                     |> CCArray.of_list |> Literals.vars |> T.VarSet.of_list in
        let vars_pas = C.lits info.passive |> Literals.vars |> T.VarSet.of_list in
        let dbs = ref [] in
        let vars_bound_to_closed_terms var_set scope =
          T.VarSet.iter (fun v -> 
              match Subst.FO.get_var subst ((v :> InnerTerm.t HVar.t),scope) with
              | Some (t,_) -> dbs := T.DB.unbound t @ !dbs (* hack *)
              | None -> ()) var_set in

        vars_bound_to_closed_terms vars_act sc_a;
        vars_bound_to_closed_terms vars_pas sc_p;

        if Util.Int_set.cardinal (Util.Int_set.of_list !dbs)  > Env.flex_get k_lambdasup   then (
          let msg = "Too many skolems will be introduced for LambdaSup." in
          Util.debugf ~section 3 "%s"  (fun k->k msg);
          raise (ExitSuperposition msg);
        )
      );     

      let subst', new_sk =
        if info.sup_kind = LambdaSup then
          S.FO.unleak_variables subst else subst, [] in
      let passive_lit' = Lit.apply_subst_no_simp renaming subst' (info.passive_lit, sc_p) in
      let new_trail = C.trail_l [info.active; info.passive] in
      if Env.is_trivial_trail new_trail then raise (ExitSuperposition "trivial trail");
      let s' = S.FO.apply ~shift_vars renaming subst (info.s, sc_a) in
      if (
        O.compare ord s' t' = Comp.Lt ||
        not (Lit.Pos.is_max_term ~ord passive_lit' passive_lit_pos) ||
        not (BV.get (C.eligible_res (info.passive, sc_p) subst) passive_idx) ||
        not (C.is_eligible_param (info.active, sc_a) subst ~idx:active_idx)
      ) then (
        let c1 = O.compare ord s' t' = Comp.Lt in
        let c2 = not (Lit.Pos.is_max_term ~ord passive_lit' passive_lit_pos) in
        let c3 = not (BV.get (C.eligible_res (info.passive, sc_p) subst) passive_idx) in
        let c4 = not (C.is_eligible_param (info.active, sc_a) subst ~idx:active_idx) in

        raise (ExitSuperposition (Format.sprintf "bad ordering conditions %b %b %b %b" c1 c2 c3 c4))
        );
      (* Check for superposition at a variable *)
      if info.sup_kind != FluidSup then
        if not @@ Env.flex_get k_sup_at_vars then
          assert (not (T.is_var info.u_p))
        else if T.is_var info.u_p && not (sup_at_var_condition info info.u_p info.t) then (
          Util.debugf ~section 3 "superposition at variable" (fun k->k);
          raise (ExitSuperposition "superposition at variable");
        );

      (* Check for hidden superposition at a variable *)	
      if Env.flex_get k_restrict_hidden_sup_at_vars then (	
        match is_hidden_sup_at_var info with	
          | Some (var,replacement) when not (sup_at_var_condition info var replacement)	
            -> raise (ExitSuperposition "hidden superposition at variable")	
          | _ -> ()	
      );

      (* ordering constraints are ok *)
      let lits_a = CCArray.except_idx (C.lits info.active) active_idx in
      let lits_p = CCArray.except_idx (C.lits info.passive) passive_idx in
      (* replace s\sigma by t\sigma in u|_p\sigma *)
      let new_passive_lit =
        Lit.Pos.replace passive_lit'
          ~at:passive_lit_pos ~by:t' in
      let c_guard = Literal.of_unif_subst renaming us in
      (* apply substitution to other literals *)
      (* Util.debugf 1 "Before unleak: %a, after unleak: %a"
         (fun k -> k Subst.pp subst Subst.pp subst'); *)
      let new_lits =
        new_passive_lit ::
        c_guard @
        Lit.apply_subst_list renaming subst' (lits_a, sc_a) @
        Lit.apply_subst_list renaming subst' (lits_p, sc_p)
      in
      let pos_enclosing_up = Position.until_first_fun passive_lit_pos in
      let fun_context_around_up =  Subst.FO.apply renaming subst' 
          (Lit.Pos.at info.passive_lit pos_enclosing_up, sc_p) in
      let vars = Iter.append (T.Seq.vars fun_context_around_up) (T.Seq.vars t')
                 |> Term.VarSet.of_iter
                 |> Term.VarSet.to_list in
      let skolem_decls = ref [] in
      let sk_with_vars =
        List.fold_left (fun acc t ->
            let sk_decl, new_sk_vars = Term.mk_fresh_skolem vars (Term.ty t) in
            skolem_decls := sk_decl :: !skolem_decls;
            Term.Map.add t new_sk_vars acc)
          Term.Map.empty new_sk in
      let new_lits =
        List.mapi (fun i lit ->
          Lit.map (fun t ->
            Term.Map.fold 
              (fun sk sk_v acc -> Term.replace ~old:sk ~by:sk_v acc)
              sk_with_vars t ) lit) new_lits in
      
      let subst_is_ho = 
        Subst.codomain subst
        |> Iter.exists (fun (t,_) -> 
            Iter.exists (fun t -> T.is_fun t || T.is_comb t) 
              (T.Seq.subterms ~include_builtin:true (T.of_term_unsafe t))) in

      let rule =
        let r = kind_to_str info.sup_kind in
        let sign = if Lit.is_pos passive_lit' then "+" else "-" in
        Proof.Rule.mk (r ^ sign)
      in
      CCList.iter (fun (sym,ty) -> Ctx.declare sym ty) !skolem_decls;
      let tags = (if subst_is_ho || info.sup_kind != Classic 
                  then [Proof.Tag.T_ho] else []) 
                  @ Unif_subst.tags us in
      let proof =
        Proof.Step.inference ~rule ~tags
          [C.proof_parent_subst renaming (info.active,sc_a) subst';
           C.proof_parent_subst renaming (info.passive,sc_p) subst']
      and penalty =
        let pen_a = C.penalty info.active in
        let pen_b = C.penalty info.passive in
        let max_d = max (C.proof_depth info.active) (C.proof_depth info.passive) in

        (if pen_a == 1 && pen_b == 1 then 1 else pen_a + pen_b)
        + (if info.sup_kind == Classic && T.is_var info.s then 1 else 0) (* superposition from app var = bad, unless we are superposing into a formula *)
        + (if info.sup_kind == Classic && T.is_app_var info.s 
           then (if T.is_var (T.head_term info.t) then 2*max_d else max (max_d - 2) 0)
           else 0)
        + (if info.sup_kind == FluidSup then Env.flex_get k_fluidsup_penalty else 0)
        + (if info.sup_kind == DupSup then Env.flex_get k_dupsup_penalty else 0)
        + (if info.sup_kind == LambdaSup then 1 else 0)

      in
      let new_clause = C.create ~trail:new_trail ~penalty new_lits proof in
      (* Format.printf "LS: %a\n" C.pp new_clause;  *)
      Util.debugf ~section 3 "@[... ok, conclusion@ @[%a@]@]" (fun k->k C.pp new_clause);
      if (not (List.for_all (Lit.for_all Term.DB.is_closed) new_lits)) then (
        CCFormat.printf "@[<2>sup, kind %s(%d)@ (@[<2>%a[%d]@ @[s=%a@]@ @[t=%a, t'=%a@]@])@ \
         (@[<2>%a[%d]@ @[passive_lit=%a@]@ @[p=%a@]@])@ with subst=@[%a@]@]"
         (kind_to_str info.sup_kind) (Term.Set.cardinal lambdasup_vars) C.pp info.active sc_a T.pp info.s T.pp info.t
            T.pp t' C.pp info.passive sc_p Lit.pp info.passive_lit
            Position.pp info.passive_pos US.pp info.subst;
        assert false;
      );
      assert(Array.for_all Literal.no_prop_invariant (C.lits new_clause));
      if not (C.lits new_clause |> Literals.vars_distinct) then (
        CCFormat.printf "a:@[%a@]@." C.pp info.active;
        CCFormat.printf "p:@[%a@]@." C.pp info.passive;
        CCFormat.printf "r:@[%a@]@." C.pp new_clause;
        CCFormat.printf "sub:@[%a@]@." Subst.pp subst';
        assert false;
      );
      Some new_clause
    with ExitSuperposition reason ->
      Util.debugf ~section 3 "... cancel, %s" (fun k->k reason);
      None

  (* simultaneous superposition: when rewriting D with C \lor s=t,
      replace s with t everywhere in D rather than at one place. *)
  let do_simultaneous_superposition info =
    let open SupInfo in
    let module P = Position in
    Util.incr_stat stat_superposition_call;
    let sc_a = info.scope_active in
    let sc_p = info.scope_passive in
    Util.debugf ~section 3
      "@[<hv2>simultaneous sup@ \
       @[<2>active@ %a[%d]@ s=@[%a@]@ t=@[%a@]@]@ \
       @[<2>passive@ %a[%d]@ passive_lit=@[%a@]@ p=@[%a@]@]@ with subst=@[%a@]@]"
      (fun k->k C.pp info.active sc_a T.pp info.s T.pp info.t
          C.pp info.passive sc_p Lit.pp info.passive_lit
          Position.pp info.passive_pos US.pp info.subst);
    assert (InnerTerm.DB.closed (info.s:>InnerTerm.t));
    assert (info.sup_kind == LambdaSup || InnerTerm.DB.closed (info.u_p:T.t:>InnerTerm.t));
    assert (not(T.is_var info.u_p) || T.is_ho_var info.u_p || info.sup_kind = FluidSup);
    assert (Env.flex_get k_sup_at_var_headed || info.sup_kind = FluidSup || 
            info.sup_kind = DupSup || not (T.is_var (T.head_term info.u_p)));
    let active_idx = Lits.Pos.idx info.active_pos in
    let passive_idx, passive_lit_pos = Lits.Pos.cut info.passive_pos in
    let shift_vars = if info.sup_kind = LambdaSup then 0 else -1 in
    try
      let renaming = S.Renaming.create () in
      let us = info.subst in
      let subst = US.subst us in
      let t' = S.FO.apply ~shift_vars renaming subst (info.t, sc_a) in
      begin match info.passive_lit, info.passive_pos with
        | Lit.Equation (_, v, true), P.Arg(_, P.Left P.Stop)
        | Lit.Equation (v, _, true), P.Arg(_, P.Right P.Stop) ->
          (* are we in the specific, but no that rare, case where we
             rewrite s=t using s=t (into a tautology t=t)? *)
          let v' = S.FO.apply ~shift_vars renaming subst (v, sc_p) in
          if T.equal t' v'
          then raise (ExitSuperposition "will yield a tautology");
        | _ -> ()
      end;
      let passive_lit' =
        Lit.apply_subst_no_simp renaming subst (info.passive_lit, sc_p)
      in
      let new_trail = C.trail_l [info.active; info.passive] in
      if Env.is_trivial_trail new_trail then raise (ExitSuperposition "trivial trail");
      let s' = S.FO.apply ~shift_vars renaming subst (info.s, sc_a) in
      if (
        O.compare ord s' t' = Comp.Lt ||
        not (Lit.Pos.is_max_term ~ord passive_lit' passive_lit_pos) ||
        not (BV.get (C.eligible_res (info.passive, sc_p) subst) passive_idx) ||
        not (C.is_eligible_param (info.active, sc_a) subst ~idx:active_idx)
      ) then raise (ExitSuperposition "bad ordering conditions");
      (* Check for superposition at a variable *)
      if info.sup_kind != FluidSup then
        if not @@ Env.flex_get k_sup_at_vars then
          assert (not (T.is_var info.u_p))
        else if T.is_var info.u_p && not (sup_at_var_condition info info.u_p info.t) then
          raise (ExitSuperposition "superposition at variable");
      (* ordering constraints are ok, build new active lits (excepted s=t) *)
      let lits_a = CCArray.except_idx (C.lits info.active) active_idx in
      let lits_a = Lit.apply_subst_list renaming subst (lits_a, sc_a) in
      (* build passive literals and replace u|p\sigma with t\sigma *)
      let u' = S.FO.apply ~shift_vars renaming subst (info.u_p, sc_p) in
      assert (Type.equal (T.ty u') (T.ty t'));
      let lits_p = Array.to_list (C.lits info.passive) in
      let lits_p = Lit.apply_subst_list renaming subst (lits_p, sc_p) in
      (* assert (T.equal (Lits.Pos.at (Array.of_list lits_p) info.passive_pos) u'); *)
      let lits_p = List.map (Lit.map (fun t-> T.replace t ~old:u' ~by:t')) lits_p in
      let c_guard = Literal.of_unif_subst renaming us in
      (* build clause *)
      let new_lits = c_guard @ lits_a @ lits_p in
      let rule =
        let r = kind_to_str info.sup_kind in
        let sign = if Lit.is_pos passive_lit' then "+" else "-" in
        Proof.Rule.mk ("s_" ^ r ^ sign)
      in
      let subst_is_ho = 
        Subst.codomain subst
        |> Iter.exists (fun (t,_) -> 
            Iter.exists (fun t -> T.is_fun t || T.is_comb t) 
              (T.Seq.subterms ~include_builtin:true (T.of_term_unsafe t))) in
      let tags = (if subst_is_ho then [Proof.Tag.T_ho] else []) @ Unif_subst.tags us in
      let proof =
        Proof.Step.inference ~rule ~tags
          [C.proof_parent_subst renaming (info.active,sc_a) subst;
           C.proof_parent_subst renaming (info.passive,sc_p) subst]
      and penalty =
        let pen_a = C.penalty info.active in
        let pen_b = C.penalty info.passive in
        (if pen_a == 1 && pen_b == 1 then 1 else pen_a + pen_b + 1)
        + (if T.is_var s' then 2 else 0) (* superposition from var = bad *)
        + (if US.has_constr info.subst then 1 else 0)
      in
      let new_clause = C.create ~trail:new_trail ~penalty new_lits proof in
      Util.debugf ~section 3 "@[... ok, conclusion@ @[%a@]@]" (fun k->k C.pp new_clause);
      assert(C.lits new_clause |> Literals.vars_distinct);
      Some new_clause
    with ExitSuperposition reason ->
      Util.debugf ~section 3 "@[... cancel, %s@]" (fun k->k reason);
      None

  (* choose between regular and simultaneous superposition *)
  let do_superposition info =
    let open SupInfo in
    assert (info.sup_kind=DupSup || info.sup_kind=SubVarSup || Type.equal (T.ty info.s) (T.ty info.t));
    assert (info.sup_kind=DupSup || info.sup_kind=SubVarSup ||
            Unif.Ty.equal ~subst:(US.subst info.subst)
              (T.ty info.s, info.scope_active) (T.ty info.u_p, info.scope_passive));
    let renaming = Subst.Renaming.create () in
    let shift_vars = if info.sup_kind = LambdaSup then 0 else -1 in
    let s = Subst.FO.apply ~shift_vars renaming (US.subst info.subst) (info.s, info.scope_active) in
    let u_p = Subst.FO.apply ~shift_vars renaming (US.subst info.subst) (info.u_p, info.scope_passive) in
    let norm t = T.normalize_bools @@ Lambda.eta_expand @@ Lambda.snf t in
    if info.sup_kind != SubVarSup && 
       not (Term.equal (norm @@ s) (norm @@ u_p) || US.has_constr info.subst) then (
        CCFormat.printf "@[<2>sup, kind %s@ (@[<2>%a[%d]@ @[s=%a@]@ @[t=%a@]@])@ \
          (@[<2>%a[%d]@ @[passive_lit=%a@]@ @[p=%a@]@])@ with subst=@[%a@]@].\n"
              (kind_to_str info.sup_kind) C.pp info.active info.scope_active T.pp info.s T.pp info.t
              C.pp info.passive info.scope_passive Lit.pp info.passive_lit
              Position.pp info.passive_pos US.pp info.subst;
        CCFormat.printf "orig_s:@[%a@]@." T.pp info.s;
        CCFormat.printf "norm_s:@[%a@]@." T.pp (norm s);
        CCFormat.printf "orig_u_p:@[%a@]@." T.pp info.u_p;
        CCFormat.printf "norm_u_p:@[%a@]@." T.pp (norm u_p);

        assert false;
    );
    if Env.flex_get k_use_simultaneous_sup && info.sup_kind != LambdaSup && info.sup_kind != DupSup
    then do_simultaneous_superposition info
    else do_classic_superposition info

  let infer_active_aux ~retrieve_from_index ~process_retrieved clause =
    ZProf.enter_prof prof_infer_active;
    (* no literal can be eligible for paramodulation if some are selected.
       This checks if inferences with i-th literal are needed? *)
    let eligible = C.Eligible.param clause in
    (* do the inferences where clause is active; for this,
       we try to rewrite conditionally other clauses using
       non-minimal sides of every positive literal *)
    let new_clauses =
      Lits.fold_eqn ~sign:true ~ord
        ~both:true ~eligible (C.lits clause)
      |> Iter.flat_map
        (fun (s, t, _, s_pos) ->
           let do_sup u_p with_pos subst =
             (* rewrite u_p with s *)
             if T.DB.is_closed u_p
             then
               let passive = with_pos.C.WithPos.clause in
               let passive_pos = with_pos.C.WithPos.pos in
               let passive_lit, _ = Lits.Pos.lit_at (C.lits passive) passive_pos in
               let info = SupInfo.( {
                   s; t; active=clause; active_pos=s_pos; scope_active=0;
                   u_p; passive; passive_lit; passive_pos; scope_passive=1; subst; sup_kind=Classic
                 }) in
               do_superposition info
             else None
           in
           (* rewrite clauses using s *)
           retrieve_from_index (!_idx_sup_into, 1) (s, 0)
           |> Iter.filter_map (process_retrieved do_sup)
        )
      |> Iter.to_rev_list

    in
    ZProf.exit_prof prof_infer_active;
    new_clauses

  let infer_passive_aux ~retrieve_from_index ~process_retrieved clause =
    ZProf.enter_prof prof_infer_passive;
    (* perform inference on this lit? *)
    let eligible = C.Eligible.(res clause) in
    (* do the inferences in which clause is passive (rewritten),
       so we consider both negative and positive literals *)
    let new_clauses =
      Lits.fold_terms ~vars:(Env.flex_get k_sup_at_vars) 
        ~var_args:(Env.flex_get k_sup_in_var_args)
        ~fun_bodies:(Env.flex_get k_sup_under_lambdas) 
        ~subterms:true ~ord ~which:`Max ~eligible ~ty_args:false 
        (C.lits clause)
      |> Iter.filter (fun (u_p, _) -> not (T.is_var u_p) || T.is_ho_var u_p)
      |> Iter.filter (fun (u_p, _) -> T.DB.is_closed u_p)
      |> Iter.filter (fun (u_p, _) -> 
          Env.flex_get k_sup_at_var_headed || not (T.is_var (T.head_term u_p)))
      |> Iter.flat_map
        (fun (u_p, passive_pos) ->
           let passive_lit, _ = Lits.Pos.lit_at (C.lits clause) passive_pos in
           let do_sup _ with_pos subst =
             let active = with_pos.C.WithPos.clause in
             let s_pos = with_pos.C.WithPos.pos in
             match Lits.View.get_eqn (C.lits active) s_pos with
             | Some (s, t, true) ->
               let info = SupInfo.({
                   s; t; active; active_pos=s_pos; scope_active=1; subst;
                   u_p; passive=clause; passive_lit; passive_pos; scope_passive=0; sup_kind=Classic
                 }) in
               do_superposition info
             | _ -> None
           in
           (* all terms that occur in an equation in the active_set
              and that are potentially unifiable with u_p (u at position p) *)
           retrieve_from_index (!_idx_sup_from, 1) (u_p,0)
           |> Iter.filter_map (process_retrieved do_sup)
        )
      |> Iter.to_rev_list
    in
    ZProf.exit_prof prof_infer_passive;
    new_clauses

  let infer_active clause =
    infer_active_aux
      ~retrieve_from_index:(I.retrieve_unifiables)
      ~process_retrieved:(fun do_sup (u_p, with_pos, subst) -> do_sup u_p with_pos subst)
      clause

  let infer_lambdasup_from clause =
    (* no literal can be eligible for paramodulation if some are selected.
       This checks if inferences with i-th literal are needed? *)
    let eligible = C.Eligible.param clause in
    (* do the inferences where clause is active; for this,
       we try to rewrite conditionally other clauses using
       non-minimal sides of every positive literal *)
    Lits.fold_eqn ~sign:true ~ord  ~both:true ~eligible (C.lits clause)
    |> Iter.flat_map
      (fun (s, t, _, s_pos) ->
         let do_lambdasup u_p with_pos subst =
           (* rewrite u_p with s *)
           let passive = with_pos.C.WithPos.clause in
           let passive_pos = with_pos.C.WithPos.pos in
           let passive_lit, _ = Lits.Pos.lit_at (C.lits passive) passive_pos in
           let info = SupInfo.( {
               s; t; active=clause; active_pos=s_pos; scope_active=0;
               u_p; passive; passive_lit; passive_pos; scope_passive=1;
               subst; sup_kind=LambdaSup
             }) in
           Util.debugf ~section 10 "[Trying lambdasup from %a into %a with term %a into term %a]"
             (fun k -> k C.pp clause C.pp passive T.pp s T.pp u_p);

           do_superposition info
         in
         I.retrieve_unifiables (!_idx_lambdasup_into, 1) (s, 0)
         |> Iter.filter_map (fun (u_p, with_pos, subst) -> do_lambdasup u_p with_pos subst))
    |> Iter.to_rev_list

  let infer_passive clause =
    infer_passive_aux
      ~retrieve_from_index:(I.retrieve_unifiables)
      ~process_retrieved:(fun do_sup (u_p, with_pos, subst) -> do_sup u_p with_pos subst)
      clause

  let infer_lambdasup_into clause =
    (* perform inference on this lit? *)
    let eligible = C.Eligible.(res clause) in
    (* do the inferences in which clause is passive (rewritten),
       so we consider both negative and positive literals *)
    let new_clauses =
      Lits.fold_terms ~vars:(Env.flex_get k_sup_at_vars) 
        ~var_args:(Env.flex_get k_sup_in_var_args)
        ~fun_bodies:true ~subterms:true ~ord
        ~which:`Max ~eligible ~ty_args:false (C.lits clause)
      |> Iter.filter_map (fun (u_p, p) ->
          (* we rewrite only under lambdas  *)
          if not (T.is_fun u_p) then None
          else (let tyargs, body = T.open_fun u_p in
                let hd = T.head_term body in
                let new_pos = List.fold_left (fun p _ -> P.(append p (body stop)) ) p tyargs in
                (* we check normal superposition conditions  *)
                if (not (T.is_var body) || T.is_ho_var body) &&
                   (not (T.is_const hd) || not (ID.is_skolem (T.as_const_exn hd))) &&
                   (Env.flex_get k_sup_at_var_headed || not (T.is_var (T.head_term body))) then
                  Some (body, new_pos)
                else None) )
      |> Iter.flat_map
        (fun (u_p, passive_pos) ->
           let passive_lit, _ = Lits.Pos.lit_at (C.lits clause) passive_pos in
           let do_sup _ with_pos subst =
             let active = with_pos.C.WithPos.clause in
             let s_pos = with_pos.C.WithPos.pos in
             match Lits.View.get_eqn (C.lits active) s_pos with
             | Some (s, t, true) ->
               let info = SupInfo.({
                   s; t; active; active_pos=s_pos; scope_active=1; subst;
                   u_p; passive=clause; passive_lit; passive_pos;
                   scope_passive=0; sup_kind=LambdaSup
                 }) in
               Util.debugf ~section 10 "[Trying lambdasup from %a into %a with term %a into term %a]"
                 (fun k -> k C.pp active C.pp clause T.pp s T.pp u_p);
               do_superposition info
             | _ -> None
           in
           (* all terms that occur in an equation in the active_set
              and that are potentially unifiable with u_p (u at position p) *)
           I.retrieve_unifiables (!_idx_sup_from, 1) (u_p,0)
           |> Iter.filter_map (fun (t,p,s) -> do_sup t p s))
      |> Iter.to_rev_list
    in
    ZProf.exit_prof prof_infer_passive;
    new_clauses
  
  let infer_active_complete_ho clause =
    let inf_res = infer_active_aux
        ~retrieve_from_index:(I.retrieve_unifiables_complete ~unif_alg:(Env.flex_get k_unif_alg))
        ~process_retrieved:(fun do_sup (u_p, with_pos, substs) ->
            (* let penalty = max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause) in *)
            (* /!\ may differ from the actual penalty (by -2) *)
            let parents = [clause; with_pos.clause] in
            let p = max (C.penalty clause) (C.penalty with_pos.clause) in
            Some (p, parents, OSeq.map (CCOpt.flat_map (do_sup u_p with_pos)) substs))
        clause
    in
    let clauses, streams = force_getting_cl inf_res in
    StmQ.add_lst (_stmq()) streams; clauses

  let infer_passive_complete_ho clause =
    let inf_res = infer_passive_aux
        ~retrieve_from_index:(I.retrieve_unifiables_complete ~unif_alg:(Env.flex_get k_unif_alg))
        ~process_retrieved:(fun do_sup (u_p, with_pos, substs) ->
            (* let penalty = max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause) in *)
            (* /!\ may differ from the actual penalty (by -2) *)
            let parents = [clause; with_pos.clause] in
            let p = max (C.penalty clause) (C.penalty with_pos.clause) in
            Some (p, parents, OSeq.map (CCOpt.flat_map (do_sup u_p with_pos)) substs))
        clause
    in
    let clauses, streams = force_getting_cl inf_res in
    StmQ.add_lst (_stmq()) streams; clauses

  let infer_active_pragmatic_ho max_unifs clause =
    let inf_res = infer_active_aux
        ~retrieve_from_index:(I.retrieve_unifiables_complete ~unif_alg:(Env.flex_get k_unif_alg))
        ~process_retrieved:(fun do_sup (u_p, with_pos, substs) ->
            let all_substs = OSeq.to_list @@ OSeq.take max_unifs @@ OSeq.filter_map CCFun.id substs   in
            let res = List.map (fun subst -> do_sup u_p with_pos subst) all_substs in
            Some res
          )
        clause
    in
    inf_res |> CCList.flatten |> List.filter CCOpt.is_some  |> List.map CCOpt.get_exn

  let infer_passive_pragmatic_ho max_unifs clause =
    let inf_res = infer_passive_aux
        ~retrieve_from_index:(I.retrieve_unifiables_complete ~unif_alg:(Env.flex_get k_unif_alg))
        ~process_retrieved:(fun do_sup (u_p, with_pos, substs) ->
            let all_substs = OSeq.to_list @@ OSeq.take max_unifs @@ OSeq.filter_map CCFun.id substs   in
            let res = List.map (fun subst -> do_sup u_p with_pos subst) all_substs in
            Some res   
          )
        clause
    in
    inf_res |> CCList.flatten |> List.filter CCOpt.is_some  |> List.map CCOpt.get_exn

  (* ----------------------------------------------------------------------
   * FluidSup rule (Superposition at applied variables)
   * ---------------------------------------------------------------------- *)

  let infer_fluidsup_active clause =
    ZProf.enter_prof prof_infer_fluidsup_active;
    (* no literal can be eligible for paramodulation if some are selected.
       This checks if inferences with i-th literal are needed? *)
    let eligible = C.Eligible.param clause in
    (* do the inferences where clause is active; for this,
       we try to rewrite conditionally other clauses using
       non-minimal sides of every positive literal *)
    let new_clauses =
      if fluidsup_applicable clause then
        Lits.fold_eqn ~sign:true ~ord ~both:true ~eligible (C.lits clause)
        |> Iter.flat_map
          (fun (s, t, _, s_pos) ->
             I.fold !_idx_fluidsup_into
               (fun acc u_p with_pos ->
                  assert (is_fluid_or_deep with_pos.C.WithPos.clause u_p);
                  assert (T.DB.is_closed u_p);
                  (* Create prefix variable H and use H s = H t for superposition *)
                  let var_h = T.var (HVar.fresh ~ty:(Type.arrow [T.ty s] (Type.var (HVar.fresh ~ty:Type.tType ()))) ()) in
                  let hs = T.app var_h [s] in
                  let ht = T.app var_h [t] in
                  let res = Env.flex_get k_unif_alg (u_p,1) (hs,0) |> OSeq.map (
                      fun osubst ->
                        osubst |> CCOpt.flat_map (
                          fun subst ->
                            let passive = with_pos.C.WithPos.clause in
                            let passive_pos = with_pos.C.WithPos.pos in
                            let passive_lit, _ = Lits.Pos.lit_at (C.lits passive) passive_pos in
                            let info = SupInfo.({
                                s=hs; t=ht; active=clause; active_pos=s_pos; scope_active=0;
                                u_p; passive; passive_lit; passive_pos; scope_passive=1; subst; sup_kind=FluidSup
                              }) in
                            do_superposition info
                        )
                    )
                  in
                  let penalty = 
                    max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause)
                    + (Env.flex_get k_fluidsup_penalty) in
                  (* /!\ may differ from the actual penalty (by -2) *)
                  Iter.cons (penalty,res,[clause;with_pos.clause]) acc
               )
               Iter.empty
          )
        |> Iter.to_rev_list
      else []
    in
    let stm_res = List.map (fun (p,s,parents) -> Stm.make ~penalty:p ~parents s) new_clauses in
    StmQ.add_lst (_stmq()) stm_res;
    ZProf.exit_prof prof_infer_fluidsup_active;
    []

  let infer_fluidsup_passive clause =
    ZProf.enter_prof prof_infer_fluidsup_passive;
    (* perform inference on this lit? *)
    let eligible = C.Eligible.(res clause) in
    (* do the inferences in which clause is passive (rewritten),
       so we consider both negative and positive literals *)
    let new_clauses =
      if fluidsup_applicable clause then
        Lits.fold_terms ~vars:true ~var_args:false ~fun_bodies:false ~subterms:true ~ord
          ~which:`Max ~eligible ~ty_args:false (C.lits clause)
        |> Iter.filter (fun (u_p, _) -> is_fluid_or_deep clause u_p)
        |> Iter.flat_map
          (fun (u_p, passive_pos) ->
             let passive_lit, _ = Lits.Pos.lit_at (C.lits clause) passive_pos in
             I.fold !_idx_sup_from
               (fun acc _ with_pos ->
                  let active = with_pos.C.WithPos.clause in
                  let s_pos = with_pos.C.WithPos.pos in
                  let res = match Lits.View.get_eqn (C.lits active) s_pos with
                    | Some (s, t, true) ->
                      (* Create prefix variable H and use H s = H t for superposition *)
                      let var_h = T.var (HVar.fresh ~ty:(Type.arrow [T.ty s] (Type.var (HVar.fresh ~ty:Type.tType ()))) ()) in
                      let hs = T.app var_h [s] in
                      let ht = T.app var_h [t] in
                      Env.flex_get k_unif_alg (hs,1) (u_p,0)
                      |> OSeq.map
                        (fun osubst ->
                           osubst |> CCOpt.flat_map (fun subst ->
                               let info = SupInfo.({
                                   s = hs; t = ht; active; active_pos=s_pos; scope_active=1; subst;
                                   u_p; passive=clause; passive_lit; passive_pos; scope_passive=0; sup_kind=FluidSup
                                 }) in
                               do_superposition info
                             )
                        )
                    | _ -> assert false
                  in
                  let penalty = 
                    max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause) 
                    + Env.flex_get k_fluidsup_penalty in
                  (* /!\ may differ from the actual penalty (by -2) *)
                  Iter.cons (penalty,res,[clause;with_pos.clause]) acc
               )
               Iter.empty
          )
        |> Iter.to_rev_list
      else []
    in
    let stm_res = List.map (fun (p,s,parents) -> Stm.make ~penalty:p ~parents s) new_clauses in
    StmQ.add_lst (_stmq()) stm_res;
    ZProf.exit_prof prof_infer_fluidsup_passive;
    []

  (* ----------------------------------------------------------------------
   * DupSup rule (Lightweight superposition at applied variables)
   * ---------------------------------------------------------------------- *)

  let infer_dupsup_active clause =
    let eligible = C.Eligible.param clause in
    let new_clauses =
      Lits.fold_eqn ~sign:true ~ord ~both:true ~eligible (C.lits clause)
      |> Iter.flat_map
        (fun (s, t, _, s_pos) ->
           I.fold !_idx_dupsup_into
             (fun acc u_p with_pos ->
                assert (T.is_var (T.head_term u_p));
                assert (T.DB.is_closed u_p);
                if (T.Seq.vars s |> Iter.append (T.Seq.vars t)
                    |> Iter.exists (fun v -> Type.is_tType (HVar.ty v))) then (
                  acc
                )
                else (
                  let scope_passive, scope_active = 0, 1 in
                  let hd_up, args_up = T.as_app u_p in
                  let arg_types = List.map T.ty args_up in
                  let n = List.length args_up in
                  let var_up = T.as_var_exn hd_up in
                  let var_w = HVar.fresh ~ty:(Type.arrow arg_types (T.ty t)) () in
                  let var_z = HVar.fresh ~ty:(Type.arrow (arg_types @ [T.ty t]) (T.ty u_p)) () in
                  let db_args = List.mapi (fun i ty -> T.bvar ~ty (n-1-i)) arg_types in
                  let term_w,term_z = T.var var_w, T.var var_z in
                  let w_db = T.app term_w db_args in
                  let z_db = T.app term_z (db_args @ [w_db]) in
                  let y_subst_val = T.fun_l arg_types z_db in
                  assert (T.DB.is_closed y_subst_val);
                  let subst_y = US.FO.bind (US.empty) (var_up, scope_passive) (y_subst_val, scope_passive) in
                  let w_args = T.app term_w args_up in
                  let w_args = Subst.FO.apply Subst.Renaming.none (US.subst subst_y) (w_args,scope_passive) in
                  let z_args = T.app term_z (args_up @ [t]) in
                  let res = Env.flex_get k_unif_alg (s,scope_active) (w_args,scope_passive) |> OSeq.map (
                      fun osubst ->
                        osubst |> CCOpt.flat_map (
                          fun subst ->
                            let subst = US.merge subst subst_y in
                            let passive = with_pos.C.WithPos.clause in
                            let passive_pos = with_pos.C.WithPos.pos in
                            let passive_lit, _ = Lits.Pos.lit_at (C.lits passive) passive_pos in
                            let info = SupInfo.({
                                s; t=z_args; active=clause; active_pos=s_pos; scope_active;
                                u_p=w_args; passive; passive_lit; passive_pos; scope_passive; subst; 
                                sup_kind=DupSup
                              }) in
                            do_superposition info
                        )
                    )
                  in
                  let penalty = 
                    max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause) 
                    + (Env.flex_get k_fluidsup_penalty / 3) in
                  (* /!\ may differ from the actual penalty (by -2) *)
                  Iter.cons (penalty,res,[clause; with_pos.clause]) acc
                ))
             Iter.empty
        )
      |> Iter.to_rev_list
    in
    let stm_res = List.map (fun (p,s,parents) -> Stm.make ~penalty:p ~parents s) new_clauses in
    StmQ.add_lst (_stmq()) stm_res;
    ZProf.exit_prof prof_infer_fluidsup_active;
    []

  let infer_dupsup_passive clause =
    ZProf.enter_prof prof_infer_fluidsup_passive;
    (* perform inference on this lit? *)
    let eligible = C.Eligible.(res clause) in
    (* do the inferences in which clause is passive (rewritten),
       so we consider both negative and positive literals *)
    let new_clauses =
      Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false ~subterms:true
        ~ord ~which:`Max ~eligible ~ty_args:false (C.lits clause)
      |> Iter.filter (fun (u_p, _) -> 
          (T.is_var (T.head_term u_p) && not (CCList.is_empty @@ T.args u_p)
           && Type.is_ground (T.ty u_p)))
      |> Iter.flat_map
        (fun (u_p, passive_pos) ->
           let passive_lit, _ = Lits.Pos.lit_at (C.lits clause) passive_pos in
           I.fold !_idx_sup_from
             (fun acc _ with_pos ->
                let active = with_pos.C.WithPos.clause in
                let s_pos = with_pos.C.WithPos.pos in
                match Lits.View.get_eqn (C.lits active) s_pos with
                | Some (s, t, true) -> (
                    if (T.Seq.vars s |> Iter.append (T.Seq.vars t)
                        |> Iter.exists (fun v -> Type.is_tType (HVar.ty v))) then (
                      acc
                    )
                    else (
                      let scope_passive, scope_active = 0, 1 in
                      let hd_up, args_up = T.as_app u_p in
                      let arg_types = List.map T.ty args_up in
                      let n = List.length args_up in
                      let var_up = T.as_var_exn hd_up in
                      let var_w = HVar.fresh ~ty:(Type.arrow arg_types (T.ty t)) () in
                      let var_z = HVar.fresh ~ty:(Type.arrow (List.append arg_types [(T.ty t)]) (T.ty u_p)) () in
                      let db_args = List.mapi (fun i ty -> T.bvar ~ty (n-1-i)) arg_types in
                      let term_w,term_z = T.var var_w, T.var var_z in
                      let w_db = T.app term_w db_args in
                      let z_db = T.app term_z (List.append db_args [w_db]) in
                      let y_subst_val = T.fun_l arg_types z_db in
                      assert (T.DB.is_closed y_subst_val);
                      let subst_y = US.FO.bind (US.empty) (var_up, scope_passive) (y_subst_val, scope_passive) in
                      let w_args = T.app term_w args_up in
                      let w_args = Subst.FO.apply Subst.Renaming.none (US.subst subst_y) (w_args,scope_passive) in
                      let z_args = T.app term_z (List.append args_up [t]) in
                      let res = Env.flex_get k_unif_alg (w_args,scope_passive) (s,scope_active) |> OSeq.map (
                          fun osubst ->
                            osubst |> CCOpt.flat_map (
                              fun subst ->
                                let subst = US.merge subst subst_y in
                                let info = SupInfo.({
                                    s; t=z_args; active; active_pos=s_pos; scope_active;
                                    u_p=w_args; passive=clause; passive_lit; passive_pos; scope_passive; subst; 
                                    sup_kind=DupSup
                                  }) in
                                do_superposition info
                            ))
                      in
                      let penalty = 
                        max (C.penalty clause) (C.penalty with_pos.C.WithPos.clause) 
                        + ((Env.flex_get k_fluidsup_penalty) / 3) in
                      (* /!\ may differ from the actual penalty (by -2) *)
                      Iter.cons (penalty,res,[clause;with_pos.clause]) acc))
                | _ -> acc)
             Iter.empty
        )
      |> Iter.to_rev_list
    in
    let stm_res = List.map (fun (p,s,parents) -> Stm.make ~penalty:p ~parents s) new_clauses in
    StmQ.add_lst (_stmq()) stm_res;
    ZProf.exit_prof prof_infer_fluidsup_passive;
    []

  (* ----------------------------------------------------------------------
   * SubVarSup rules
   * ---------------------------------------------------------------------- *)

  let do_subvarsup ~active_pos ~passive_pos =
    (* Variable names in each clause renamed apart *)
    let renaming = Subst.Renaming.create () in
    let rename_term t = Subst.FO.apply renaming Subst.empty t in
    let sc_a, sc_p = 0, 1 in

    let cl_a, cl_p = 
      C.apply_subst ~renaming (active_pos.C.WithPos.clause,sc_a) Subst.empty,
      C.apply_subst ~renaming (passive_pos.C.WithPos.clause,sc_p) Subst.empty in
    let s,t = 
      match Lits.View.get_eqn (C.lits cl_a) active_pos.C.WithPos.pos with
      | Some(l,r,_) -> l,r
      | _ -> invalid_arg "active lit must be an equation" in

    assert(T.is_var t || T.is_app_var t || T.is_comb t);

    let u_p = rename_term (passive_pos.C.WithPos.term,sc_p) in
    let var,args =
      match T.view u_p with 
      | T.Var v -> v,[]
      | T.App(hd, [x]) when T.is_var hd ->
        T.as_var_exn hd, [x]
      | _ -> invalid_arg "u_p must be of the form y or y s" in
    

    let z_ty = Type.arrow [T.ty t] (HVar.ty var) in
    let z = T.app (T.var @@ HVar.fresh ~ty:z_ty ()) [t] in
    let subst = Subst.FO.bind' Subst.empty (var, 0) (z,0) in
    
    let passive_lit,_ = Lits.Pos.lit_at (C.lits cl_p) passive_pos.C.WithPos.pos in

    let sup_info = 
      SupInfo.{
        active = cl_a; active_pos=active_pos.C.WithPos.pos; scope_active=0; s; t=T.app z args;
        passive = cl_p; passive_pos=passive_pos.C.WithPos.pos; scope_passive=0;
        passive_lit; u_p; subst = US.of_subst subst; sup_kind = SubVarSup} in
    do_superposition sup_info
  
  let infer_subvarsup_active clause =
    let eligible = C.Eligible.param clause in
    Lits.fold_eqn ~sign:true ~ord ~both:true ~eligible (C.lits clause)
    |> Iter.filter(fun (_,t,_,_) -> T.is_var t || T.is_app_var t || T.is_comb t) 
    |> Iter.flat_map
      (fun (s, t, _, s_pos) ->
          (* rewrite clauses using s *)
          I.fold !_idx_subvarsup_into
            (fun acc _ with_pos ->
              let active_pos = C.WithPos.{term=s; pos=s_pos; clause} in
              match do_subvarsup ~passive_pos:with_pos ~active_pos with
              | Some c -> 
                Util.debugf ~section 1 "svs: @[%a@]@. @[%a@]. @[%a@]@." 
                  (fun k -> k C.pp clause C.pp with_pos.clause C.pp c);
                Iter.cons c acc
              | None -> acc)
            Iter.empty
      )
    |> Iter.to_rev_list


  let infer_subvarsup_passive clause =
    let eligible = C.Eligible.(res clause) in
    Lits.fold_terms ~vars:true ~var_args:false ~fun_bodies:false ~subterms:true ~ord
      ~which:`Max ~eligible ~ty_args:false (C.lits clause)
    |> Iter.filter( fun (t,pos) -> 
        match T.view t with 
        | T.Var _ -> has_bad_occurrence_elsewhere clause t pos
        | T.App(hd, [x]) -> has_bad_occurrence_elsewhere clause hd pos
        | _ -> false)
    |> Iter.flat_map
      (fun (u_p, passive_pos) ->
          I.fold !_idx_sup_from
            (fun acc _ with_pos ->
              let passive_pos = C.WithPos.{term=u_p; pos=passive_pos; clause} in
              match Lits.View.get_eqn (C.lits with_pos.C.WithPos.clause) with_pos.C.WithPos.pos with
              | Some(l,r,_) when T.is_var r || T.is_app_var r || T.is_comb r->
                begin match do_subvarsup ~passive_pos ~active_pos:with_pos with
                | Some c -> 
                  Util.debugf ~section 1 "svs: @[%a@]@. @[%a@]. @[%a@]@." 
                    (fun k -> k C.pp with_pos.clause C.pp clause C.pp c);
                  Iter.cons c acc
                | None -> acc end
              | _ -> acc)
            Iter.empty
      )
    |> Iter.to_rev_list


  (* ----------------------------------------------------------------------
   * Equality Resolution rule
   * ---------------------------------------------------------------------- *)

  let infer_equality_resolution_aux ~unify ~iterate_substs clause =
    ZProf.enter_prof prof_infer_equality_resolution;
    let eligible = C.Eligible.filter (fun lit -> not @@ Lit.is_predicate_lit lit) in
    (* iterate on those literals *)
    (* CCFormat.printf "eq_res(@[%a@])@." C.pp clause; *)
    let new_clauses =
      Lits.fold_eqn ~sign:false ~ord ~both:false ~eligible (C.lits clause)
      |> Iter.filter_map
        (fun (l, r, _, l_pos) ->
          let do_eq_res us =
            let pos = Lits.Pos.idx l_pos in
            (* CCFormat.printf "trying %d@." pos; *)
            let eligible = BV.get (C.eligible_res_no_subst clause) pos in
            if eligible  
            (* subst(lit) is maximal, we can do the inference *)
            then (
              Util.incr_stat stat_equality_resolution_call;
              let renaming = Subst.Renaming.create () in
              let subst = US.subst us in
              let rule = Proof.Rule.mk "eq_res" in
              let new_lits = CCArray.except_idx (C.lits clause) pos in
              let new_lits = Lit.apply_subst_list renaming subst (new_lits,0) in
              let c_guard = Literal.of_unif_subst renaming us in
              let subst_is_ho = 
                  Subst.codomain subst
                  |> Iter.exists (fun (t,_) -> 
                      Iter.exists (fun t -> T.is_fun t || T.is_comb t) 
                        (T.Seq.subterms ~include_builtin:true (T.of_term_unsafe t))) in
              let tags = (if subst_is_ho then [Proof.Tag.T_ho] else []) @ Unif_subst.tags us in
              let trail = C.trail clause in
              let penalty = if C.penalty clause = 1 then 1 else C.penalty clause + 1 in
              let proof = Proof.Step.inference ~rule ~tags
                  [C.proof_parent_subst renaming (clause,0) subst] in
              let new_clause = C.create ~trail ~penalty (c_guard@new_lits) proof in
              (* CCFormat.printf "success: @[%a@]@." C.pp new_clause; *)
              Util.debugf ~section 1 "@[<hv2>equality resolution on@ @[%a@]@ yields @[%a@],\n subst @[%a@]@]"
                (fun k->k C.pp clause C.pp new_clause US.pp us);
              Some new_clause
            ) else None
          in
          let substs = unify (l, 0) (r, 0) in
          iterate_substs substs do_eq_res
        )
      |> Iter.to_rev_list
    in
    ZProf.exit_prof prof_infer_equality_resolution;
    new_clauses

  let infer_equality_resolution c =
    infer_equality_resolution_aux
      ~unify:(fun l r -> 
        try Some (Unif.FO.unify_full l r) 
        with Unif.Fail -> None)
      ~iterate_substs:(fun substs do_eq_res -> CCOpt.flat_map do_eq_res substs) c

  let infer_equality_resolution_complete_ho clause =
    let inf_res = infer_equality_resolution_aux
        ~unify:(Env.flex_get k_unif_alg)
        ~iterate_substs:(fun substs do_eq_res -> Some (OSeq.map (CCOpt.flat_map do_eq_res) substs))
        clause
    in
    let cls, stm_res = force_getting_cl (List.map (fun stm -> C.penalty clause, [clause], stm)  inf_res) in
    StmQ.add_lst (_stmq()) stm_res; cls

  let infer_equality_resolution_pragmatic_ho max_unifs clause =
    let inf_res = infer_equality_resolution_aux
        ~unify:(Env.flex_get k_unif_alg)
        ~iterate_substs:(fun substs do_eq_res ->
            (* Some (OSeq.map (CCOpt.flat_map do_eq_res) substs) *)
            let all_substs = OSeq.to_list @@ OSeq.take max_unifs @@ OSeq.filter_map CCFun.id substs   in
            let res = List.map (fun subst -> do_eq_res subst) all_substs in
            Some res)
        clause
    in
    inf_res |> CCList.flatten |> List.filter CCOpt.is_some  |> List.map CCOpt.get_exn

  (* ----------------------------------------------------------------------
   * Equality Factoring rule
   * ---------------------------------------------------------------------- *)

  module EqFactInfo = struct
    type t = {
      clause : C.t;
      active_idx : int;
      s : T.t;
      t : T.t;
      u : T.t;
      v : T.t;
      subst : US.t;
      scope : int;
      pred_var_eq_fact : bool
    }
  end

  (* do the inference between given positions, if ordering conditions are respected *)
  let do_eq_factoring info =
    let open EqFactInfo in
    let s = info.s and t = info.t and v = info.v in
    let us = info.subst in
    (* check whether subst(lit) is maximal, and not (subst(s) < subst(t)) *)
    let renaming = S.Renaming.create () in
    let subst = US.subst us in

    if info.pred_var_eq_fact ||
        (O.compare ord (S.FO.apply renaming subst (s, info.scope))
          (S.FO.apply renaming subst (t, info.scope)) <> Comp.Lt
        &&
        (C.is_eligible_param (info.clause,info.scope) subst ~idx:info.active_idx))
    then (
      let subst_is_ho = 
        Subst.codomain subst
        |> Iter.exists (fun (t,_) -> 
            Iter.exists (fun t -> T.is_fun t || T.is_comb t) 
              (T.Seq.subterms ~include_builtin:true (T.of_term_unsafe t))) in
      let tags = (if subst_is_ho then [Proof.Tag.T_ho] else []) @ Unif_subst.tags us in
      Util.incr_stat stat_equality_factoring_call;
      let proof =
        Proof.Step.inference
          ~rule:(Proof.Rule.mk"eq_fact") ~tags
          [C.proof_parent_subst renaming (info.clause,0) subst]
      (* new_lits: literals of the new clause. remove active literal
         and replace it by a t!=v one, and apply subst *)
      and new_lits = CCArray.except_idx (C.lits info.clause) info.active_idx in
      let new_lits = Lit.apply_subst_list renaming subst (new_lits,info.scope) in
      let c_guard = Literal.of_unif_subst renaming us in
      let lit' = Lit.mk_neq
          (S.FO.apply renaming subst (t, info.scope))
          (S.FO.apply renaming subst (v, info.scope))
      in
      let new_lits = lit' :: c_guard @ new_lits in
      let penalty = if C.penalty info.clause = 1 then 1 else C.penalty info.clause + 1 in
      let new_clause =
        C.create ~trail:(C.trail info.clause) ~penalty new_lits proof
      in
      Util.debugf ~section 3 "@[<hv2>equality factoring on@ @[%a@]@ yields @[%a@]@]"
        (fun k->k C.pp info.clause C.pp new_clause);

      Some new_clause
    ) else(None)

  let t_type_is_ho s =
      Type.is_prop (T.ty s) || Type.is_fun (T.ty s)

  (* Given terms s and t, identify maximal common context u
     such that s = u[s1,...,sn] and t = u[t1,...,tn]. Then,
     if some of the disagrements are solvable by a weak
     unification algorihtm (e.g., pattern or fixpoint), filter
     them out and create the unifying substitution. Based on
     k_ho_disagremeents at least one or all of s1...sn have
     to be of functional/boolean type *)
  let find_ho_disagremeents ?(unify=true) (orig_s,s_sc) (orig_t,t_sc) =
    let open CCFun in
    let exception StopSearch in
    let counter = ref 0 in

    let cheap_unify ~subst (s,s_sc) (t,t_sc) =
      let unif_alg =
        if Env.flex_get Combinators.k_enable_combinators then
           (fun s t -> Unif_subst.of_subst @@ Unif.FO.unify_syn ~subst:(Unif_subst.subst subst) s t)
        else if T.is_var s || T.is_var t then (
          FixpointUnif.unify_scoped ~subst ~counter
        ) else PatternUnif.unify_scoped ~subst ~counter in
      
      try
        if not unify then None
        else Some (unif_alg (s,s_sc) (t,t_sc))
      with PatternUnif.NotInFragment | PatternUnif.NotUnifiable | Unif.Fail ->
        None
    in
    
    let rec aux s t =
      if T.equal s t && (s_sc == t_sc || T.is_ground s) then []
      else (
        match T.view s, T.view t with
        | T.App(s_hd, s_args), T.App(t_hd, t_args) 
            when T.is_const s_hd ->
          let (s_hd, s_args), (t_hd, t_args) = 
            CCPair.map_same T.as_app_mono (s,t) in
          if T.equal s_hd t_hd then aux_l s_args t_args
          else [s,t]
        | T.App(s_hd, s_args), T.App(t_hd, t_args) 
            when not (T.equal s_hd t_hd)
                 && T.is_const s_hd && T.is_const t_hd ->
          (* trying to find prefix subterm that is the differing context *)
          let (s_hd, s_args), (t_hd, t_args) = 
            CCPair.map_same T.as_app_mono (s,t) in

          let lhs,rhs,args_lhs,args_rhs = 
            if List.length s_args > List.length t_args then (
              let taken,dropped = 
                CCList.take_drop (List.length s_args - List.length t_args) s_args in
              T.app s_hd taken, t_hd, dropped, t_args
            ) else (
              let taken,dropped = 
                CCList.take_drop (List.length t_args - List.length s_args) t_args in
              s_hd, T.app t_hd taken, s_args, dropped
            ) in
          if T.same_l args_lhs args_rhs && s_sc == t_sc then ([lhs,rhs])
          else [s,t]
        | _ -> [s,t])
    and aux_l xs ys =
      match xs,ys with
      | [],[] -> []
      | x :: xxs, y :: yys -> aux x y @ aux_l xxs yys
      | _ -> invalid_arg "args must be of the same length" in
    
    try
      if not (Type.equal (T.ty orig_s) (T.ty orig_t)) then raise StopSearch;

      if T.equal T.true_ orig_s || T.equal T.true_ orig_t then raise StopSearch;

      let norm = 
        if Env.flex_get Combinators.k_enable_combinators 
        then CCFun.id 
        else Lambda.eta_expand in

      let diss = aux (norm orig_s) (norm orig_t) in
      let hd_is_var t = 
        let _,body = T.open_fun t in
        T.is_var @@ T.head_term body in
      
      if CCList.is_empty diss 
          || List.for_all (fun (s,t) -> hd_is_var s || hd_is_var t) diss
          || List.for_all (fun (s,_) -> not @@ t_type_is_ho s) diss then (
          raise StopSearch
      );

      let _,_,unifscope,init_subst =
        if not unify then (orig_s,orig_t,0,US.empty)
        else US.FO.rename_to_new_scope ~counter (orig_s,s_sc) (orig_t,t_sc) in
      let app_subst subst =
        if not unify then (fun (s,_) -> s)
        else Subst.FO.apply Subst.Renaming.none (US.subst subst) in

      (* Filter out the pairs that are easy to unify *)
      let diss = 
        List.fold_left (fun (dis_acc, subst) (si, ti) ->
          let si',ti' = CCPair.map_same (app_subst subst) ((si,s_sc), (ti,t_sc)) in
          if not (Type.is_ground (T.ty si')) || not (Type.is_ground (T.ty ti')) then (
            (* polymorphism is currently not supported *)
            raise StopSearch
          );
          match cheap_unify ~subst (si',unifscope) (ti', unifscope) with
          | Some subst' -> dis_acc, subst'
          | None -> (si,ti) :: dis_acc, subst)
        ([],init_subst) (diss) in


      (* If no constraints are left or all of pairs are flex-flex
         or all of pairs are FO then we could have done all of 
         this with HO unification or FO superposition *)
      if (CCList.is_empty (fst diss)) then (
          raise StopSearch
      );

      if Env.flex_get k_ho_disagremeents == `AllHo &&
         List.exists (fun (si,_) -> not (t_type_is_ho si)) (fst diss) then (
           raise StopSearch
        );

      Some diss
    with StopSearch -> None

  
    let ext_inst ~parents (s,s_sc) (t,t_sc) =
      assert(not (CCList.is_empty parents));
      assert(CCList.length parents != 2 || s_sc != t_sc);

      let renaming = Subst.Renaming.create () in
      let apply_subst = Subst.FO.apply renaming Subst.empty  in
      let s, t = apply_subst (s,s_sc), apply_subst (t,t_sc) in
      assert(Type.equal (T.ty s) (T.ty t));
      assert(Type.is_fun (T.ty s));
      
      let ty_args, ret  = Type.open_fun (T.ty s) in
      let alpha = T.of_ty @@ List.hd ty_args in
      let beta = T.of_ty @@ Type.arrow (List.tl ty_args) ret in
      let diff_const = Env.flex_get HO.k_diff_const in
      
      let diff_s_t = T.app diff_const [alpha; beta; s; t] in
      let s_diff, t_diff = T.app s [diff_s_t], T.app t [diff_s_t] in

      let neg_lit = Lit.mk_neq s_diff t_diff in
      let pos_lit = Lit.mk_eq s t in
      let new_lits = [neg_lit; pos_lit] in

      let proof =
            Proof.Step.inference (List.map C.proof_parent parents)
              ~rule:(Proof.Rule.mk "ext_inst") in
      let penalty = List.fold_left max 1 (List.map C.penalty parents) in

      C.create ~trail:(C.trail_l parents) ~penalty new_lits proof

  let do_ext_inst ~parents ((from_t,sc_f) as s) ((into_t,sc_t) as t) =
    match find_ho_disagremeents ~unify:false s t  with
    | Some (disagreements, subst) -> 
      assert (US.is_empty subst);
      let ho_dis = List.filter (fun (s,t) -> Type.is_fun (T.ty s)) disagreements in
      (* assert (not (CCList.is_empty ho_dis)); *)

      CCList.map (fun (lhs,rhs) -> ext_inst ~parents (lhs,sc_f) (rhs,sc_t)) ho_dis
    | None -> []

  let ext_inst_or_family_eqfact_aux cl =
    let try_ext_eq_fact (s,t) (u,v) idx =
      let sc = 0 in
      match find_ho_disagremeents (s,sc) (u,sc) with
      | Some (disagrements, subst) ->
        assert(not (US.has_constr subst));
        let subst = US.subst subst in
        let dis_lits = List.map (fun (a,b) -> Lit.mk_neq a b) disagrements in
        let new_lits = 
          dis_lits @ ((Lit.mk_neq t v) :: CCArray.except_idx (C.lits cl) idx)
          |> CCArray.of_list
          |> (fun lits ->
                Literals.apply_subst (Subst.Renaming.create ()) subst (lits, sc))
          |> CCArray.to_list in
        let proof =
          Proof.Step.inference [C.proof_parent cl] 
            ~rule:(Proof.Rule.mk "ext_eqfact") in
        let new_c = C.create ~trail:(C.trail cl) ~penalty:(C.penalty cl) new_lits proof in
        [new_c]
      | None -> [] in

    let try_ext_eq_factinst (s,_) (u,_) =
      do_ext_inst ~parents:[cl] (s,0) (u,0) in

    let try_factorings (s,t) (u,v) idx =
      let ext_family = 
        if (Env.flex_get k_ext_rules_kind = `Both ||
           Env.flex_get k_ext_rules_kind = `ExtFamily) then (
          try_ext_eq_fact (s,t) (u,v) idx
        ) else [] in
      
      let ext_inst = 
        if (Env.flex_get k_ext_rules_kind = `Both ||
           Env.flex_get k_ext_rules_kind = `ExtInst) then (
          try_ext_eq_factinst (s,t) (u,v)
        ) else [] in
      ext_inst @ ext_family in

    let aux_eq_rest (s,t) i lits = 
      CCList.flatten @@ List.mapi (fun j lit -> 
        if i < j then (
          match lit with 
          | Lit.Equation(u,v,true) ->
            try_factorings (s,t) (u,v) i
            @
            try_factorings (s,t) (v,u) i 
          | _ -> []
        ) else []) lits in

    let lits = CCArray.to_list (C.lits cl) in
    let maximal = C.eligible_param (cl,0) Subst.empty in
    CCList.flatten @@ List.mapi (fun i lit ->
      match lit with
      | Lit.Equation (s,t,true) 
        when Env.flex_get k_ext_dec_lits != `OnlyMax ||
             BV.get maximal i ->
        aux_eq_rest (s,t) i lits
      | _ -> []
    ) lits

  
  let ext_eqfact given =
    if ext_rule_eligible given then  
      ZProf.with_prof prof_ext_dec ext_inst_or_family_eqfact_aux given
    else []

  let infer_equality_factoring_aux ~unify ~iterate_substs clause =
    ZProf.enter_prof prof_infer_equality_factoring;
    let eligible = C.Eligible.(filter (function 
      | Equation(_,_,true) -> true
      | Equation(lhs,rhs,false) -> T.is_app_var lhs && T.equal rhs T.true_
      | l -> Lit.is_pos l  )) in
    (* find root terms that are unifiable with s and are not in the
       literal at s_pos. Calls [k] with a position and substitution *)
    let find_unifiable_lits ~var_pred_status idx s _s_pos k =
      let is_pred_var, pred_var_sign = var_pred_status in
      Array.iteri
        (fun i lit ->
           match lit with
           | _ when i = idx -> () (* same index *)
           | Lit.Equation (u, v, sign) ->
             if not sign && not is_pred_var then ()
             else (
               if is_pred_var && T.equal T.true_ v then (
                 if sign == pred_var_sign then (
                   k (u, v, unify (s,0) (u,0))
                 ) else (
                   let u = T.Form.not_ u in
                   k (u, (if sign then T.false_ else T.true_),
                      unify (s,0) (u,0))
                 )
               ) else if sign && ((not is_pred_var) || pred_var_sign) then (
                 k (u, v, unify (s,0) (u,0));
                 k (v, u, unify (s,0) (v,0))
               );
             )
           | _ -> () (* ignore other literals *)
        ) (C.lits clause)
    in
    (* try to do inferences with each positive literal *)
    let new_clauses =
      Lits.fold_eqn ~ord ~both:true ~eligible (C.lits clause)
      |> Iter.flat_map
        (fun (s, t, sign, s_pos) -> (* try with s=t *)
           assert(sign || (T.equal T.true_ t && T.is_app_var s) || (T.equal T.true_ s && T.is_app_var t));
           let active_idx = Lits.Pos.idx s_pos in
           let is_var_pred =
             Env.flex_get k_bool_eq_fact &&
             T.is_app_var s && Type.is_prop (T.ty s) && T.equal T.true_ t in
           let var_pred_status = (is_var_pred, sign) in
           find_unifiable_lits ~var_pred_status active_idx s s_pos
           |> Iter.filter_map
             (fun (u,v,substs) ->
               let t =
                (* the only way we can introduce false on the RHS of the
                   equation is when we flip (u = true) to
                   ((not u) = false)... Then, we also need to flip the original
                   equation F x != true to F x = false, which is done in the
                   next two lines  *)
                if not (is_var_pred) || not (T.equal T.false_ v) then t
                else T.false_ in
               iterate_substs substs
                 (fun subst ->
                     let info = EqFactInfo.({
                         clause; s; t; u; v; active_idx; subst; scope=0; pred_var_eq_fact=is_var_pred
                       }) in
                   do_eq_factoring info)))
      |> Iter.to_rev_list
    in
    ZProf.exit_prof prof_infer_equality_factoring;
    new_clauses

  let infer_equality_factoring c =
    infer_equality_factoring_aux
      ~unify:(fun s t ->
        try Some (Unif.FO.unify_full s t) 
        with Unif.Fail -> 
      None)
      ~iterate_substs:(fun subst do_eq_fact -> CCOpt.flat_map do_eq_fact subst) c

  let infer_equality_factoring_complete_ho clause =
    let inf_res = infer_equality_factoring_aux
        ~unify:(Env.flex_get k_unif_alg)
        ~iterate_substs:(fun substs do_eq_fact -> Some (OSeq.map (CCOpt.flat_map do_eq_fact) substs))
        clause
    in
    let cls, stm_res = force_getting_cl (List.map (fun stm -> C.penalty clause, [clause], stm)  inf_res) in
    StmQ.add_lst (_stmq()) stm_res; cls

  let infer_equality_factoring_pragmatic_ho max_unifs clause =
    let inf_res = infer_equality_factoring_aux
        ~unify:(Env.flex_get k_unif_alg)
        ~iterate_substs:(fun substs do_eq_fact ->
            (* Some (OSeq.map (CCOpt.flat_map do_eq_fact) substs) *)
            let all_substs = OSeq.to_list @@ OSeq.take max_unifs @@ OSeq.filter_map CCFun.id substs in
            let res = List.map (fun subst -> do_eq_fact subst) all_substs in
            Some res)
        clause
    in
    inf_res |> CCList.flatten |> List.filter CCOpt.is_some  |> List.map CCOpt.get_exn

  (* ----------------------------------------------------------------------
   * extraction of a clause from the stream queue (HO feature)
   * ---------------------------------------------------------------------- *)

  let extract_from_stream_queue ~full () =
    ZProf.enter_prof prof_queues;
    let cl =
      if full then
        StmQ.take_fair_anyway (_stmq())
      else
        StmQ.take_stm_nb (_stmq())
    in
    let opt_res = CCOpt.sequence_l (List.filter CCOpt.is_some cl)  in
    ZProf.exit_prof prof_queues;
    match opt_res with
    | None -> []
    | Some l ->  l

  let extract_from_stream_queue_fix_stm ~full () =
    ZProf.enter_prof prof_queues;
    let cl =
      if full then
        StmQ.take_fair_anyway (_stmq())
      else
        StmQ.take_stm_nb_fix_stm (_stmq())
    in
    let opt_res = CCOpt.sequence_l (List.filter CCOpt.is_some cl) in
    ZProf.exit_prof prof_queues;
    match opt_res with
    | None -> []
    | Some l -> l


  (* ----------------------------------------------------------------------
   * simplifications
   * ---------------------------------------------------------------------- *)

  (* TODO: put forward pointers in simpl_set, to make some rewriting steps
      faster? (invalidate when updated, also allows to reclaim memory) *)

  (* TODO: use a record with
     - head
     - args
     - subst
       so as not to rebuild intermediate terms, and also to avoid mixing
       the head normal form and the substitution for (evaluated) arguments.

     Might even convert rules into De Bruijn, because:
     - special restriction (vars rhs ⊆ vars lhs)
     - indexing on first symbol might be sufficient if matching is fast
     - must rewrite matching to work on the record anyway
  *)

  let lazy_false = Lazy.from_val false

  type demod_state = {
    mutable demod_clauses: (C.t * Subst.t * Scoped.scope) list; (* rules used *)
    mutable demod_sc: Scoped.scope; (* current scope *)
  }

  (** Compute normal form of term w.r.t active set. Clauses used to
      rewrite are added to the clauses hashset.
      restrict is an option for restricting demodulation in positive maximal terms *)
  let demod_nf ?(restrict=lazy_false) (st:demod_state) c t : T.t =
    (* compute normal form of subterm. If restrict is true, substitutions that
       are variable renamings are forbidden (since we are at root of a max term) *)
    let rec reduce_at_root ~restrict t k =
      (* find equations l=r that match subterm *)
      let cur_sc = st.demod_sc in
      assert (cur_sc > 0);
      let step =
        UnitIdx.retrieve ~sign:true (!_idx_simpl, cur_sc) (t, 0)
        |> Iter.find_map
          (fun (l, r, (_,_,sign,unit_clause), subst) ->
             let rename = Subst.Renaming.create () in
             (* r is the term subterm is going to be rewritten into *)
             assert (C.is_unit_clause unit_clause);
             if sign &&
                C.trail_subsumes unit_clause c &&
                not (C.equal unit_clause c) &&
                (not (Lazy.force restrict) || not (S.is_renaming subst)) &&
                (O.compare ord
                   (S.FO.apply rename subst (l,cur_sc))
                   (S.FO.apply rename subst (r,cur_sc)) = Comp.Gt)
                (* subst(l) > subst(r) and restriction does not apply, we can rewrite *)
             then (
               Util.debugf ~section 3
                 "@[<hv2>demod(%d):@ @[<hv>t=%a[%d],@ l=%a[%d],@ r=%a[%d]@],@ subst=@[%a@]@]"
                 (fun k->k (C.id c) T.pp t 0 T.pp l cur_sc T.pp r cur_sc S.pp subst);

               let norm t = T.normalize_bools @@ Lambda.eta_reduce @@ Lambda.snf t in
               let t' = norm t in
               let l' = norm @@ Subst.FO.apply Subst.Renaming.none subst (l,cur_sc) in               
               (* sanity checks *)
               assert (Type.equal (T.ty l) (T.ty r));
               assert (T.equal l' t');
               st.demod_clauses <-
                 (unit_clause,subst,cur_sc) :: st.demod_clauses;
               st.demod_sc <- 1 + st.demod_sc; (* allocate new scope *)
               Util.incr_stat stat_demodulate_step;
               Some (r, subst, cur_sc)
             ) else None)
      in
      begin match step with
        | None -> k t (* not found any match, normal form found *)
        | Some (rhs,subst,cur_sc) ->
          (* reduce [rhs] in current scope [cur_sc] *)
          assert (cur_sc < st.demod_sc);
          (* bind variables not occurring in [rhs] to fresh ones *)
          let subst = 
            (InnerTerm.Seq.vars (rhs :> InnerTerm.t)) 
            |> Iter.fold (fun subst v -> 
                if S.mem subst (v, cur_sc) 
                then subst 
                else S.bind subst (v, cur_sc) 
                  (InnerTerm.var (HVar.fresh ~ty:(HVar.ty v) ()), cur_sc)) 
              subst in
          (* If not beta-reduced this can get out of hands --  *)
          let rhs' = Lambda.snf @@ Subst.FO.apply Subst.Renaming.none subst (rhs,cur_sc) in
          Util.debugf ~section 3
            "@[<2>demod(%d):@ rewrite `@[%a@]`@ into `@[%a@]`@ resulting `@[%a@]`@ nf `@[%a@]` using %a[%d]@]"
            (fun k->k (C.id c) T.pp t T.pp rhs T.pp rhs' T.pp (Lambda.snf rhs') Subst.pp subst cur_sc);
          (* NOTE: we retraverse the term several times, but this is simpler *)
          normal_form ~restrict rhs' k (* done one rewriting step, continue *)
      end
    (* rewrite innermost-leftmost of [subst(t,scope)]. The initial scope is
       0, but then we normal_form terms in which variables are really the variables
       of the RHS of a previously applied rule (in context !sc); all those
       variables are bound to terms in context 0 *)
    and normal_form ~restrict t k =
      match T.view t with
      | T.Const _ -> reduce_at_root ~restrict t k
      | T.App (hd, l) ->
        (* rewrite subterms in call by value. *)
        let rewrite_args = Env.flex_get k_demod_in_var_args || not (T.is_var hd) in
        if rewrite_args
        then
          normal_form_l l
            (fun l' ->
               let t' =
                 if T.same_l l l'
                 then t
                 else T.app hd l'
               in
               (* rewrite term at root *)
               reduce_at_root ~restrict t' k)
        else reduce_at_root ~restrict t k
      | T.Fun (ty_arg, body) ->
        (* reduce under lambdas *)
        if Env.flex_get k_lambda_demod
        then
          normal_form ~restrict:lazy_false body
            (fun body' ->
               let u = if T.equal body body' then t else T.fun_ ty_arg body' in
               reduce_at_root ~restrict u k)
        else reduce_at_root ~restrict t k (* TODO: DemodExt *)
      | T.Var _ | T.DB _ -> k t
      | T.AppBuiltin (b, l) ->
        normal_form_l l
          (fun l' ->
             let u =
               if T.same_l l l' then t else T.app_builtin ~ty:(T.ty t) b l'
             in
             reduce_at_root ~restrict u k)
    and normal_form_l l k = match l with
      | [] -> k []
      | t :: tail ->
        normal_form ~restrict:lazy_false t
          (fun t' ->
             normal_form_l tail
               (fun l' -> k (t' :: l')))
    in
    normal_form ~restrict t (fun t->t)

  let[@inline] eq_c_subst (c1,s1,sc1)(c2,s2,sc2) =
    C.equal c1 c2 && sc1=sc2 && Subst.equal s1 s2

  (* Demodulate the clause, with restrictions on which terms to rewrite *)
  let demodulate_ c =
    Util.incr_stat stat_demodulate_call;
    (* state for storing proofs and scope *)
    let st = {
      demod_clauses=[];
      demod_sc=1;
    } in
    (* literals that are eligible for paramodulation. *)
    let eligible_param = lazy (C.eligible_param (c,0) S.empty) in
    (* demodulate literals *)
    let demod_lit i lit =
      (* strictly maximal terms might be blocked *)
      let strictly_max = lazy (
        begin match lit with
          | Lit.Equation (t1,t2,true) -> 
            begin match O.compare ord t1 t2 with
              | Comp.Gt -> [t1] | Comp.Lt -> [t2] | _ -> []
            end 
          | _ -> []
        end
      ) in
      (* shall we restrict a subterm? only for max terms in positive
          equations that are eligible for paramodulation.

         NOTE: E's paper mentions that restrictions should occur for
         literals eligible for {b resolution}, not paramodulation, but
         it seems it might be a typo
      *)
      let restrict_term t = lazy (
        Lit.is_pos lit &&
        BV.get (Lazy.force eligible_param) i &&
        (* restrict max terms in positive literals eligible for resolution *)
        CCList.mem ~eq:T.equal t (Lazy.force strictly_max)
      ) in
      Lit.map
        (fun t -> demod_nf ~restrict:(restrict_term t) st c t)
        lit
    in


    (* demodulate every literal *)
    let lits = Array.mapi demod_lit (C.lits c) in
    if CCList.is_empty st.demod_clauses then (
      (* no rewriting performed *)
      SimplM.return_same c
    ) else (
      assert (not (Lits.equal_com lits (C.lits c)));
      (* construct new clause *)
      st.demod_clauses <- CCList.uniq ~eq:eq_c_subst st.demod_clauses;
      let proof =
        Proof.Step.simp
          ~rule:(Proof.Rule.mk "demod")
          (C.proof_parent c ::
           List.rev_map
             (fun (c,subst,sc) ->
                C.proof_parent_subst Subst.Renaming.none (c,sc) subst)
             st.demod_clauses) in
      let trail = C.trail c in (* we know that demodulating rules have smaller trail *)
      let new_c = C.create_a ~trail ~penalty:(C.penalty c) lits proof in
      Util.debugf ~section 3 "@[<hv2>demodulate@ @[%a@]@ into @[%a@]@ using {@[<hv>%a@]}@]"
        (fun k->
           let pp_c_s out (c,s,sc) =
             Format.fprintf out "(@[%a@ :subst %a[%d]@])" C.pp c Subst.pp s sc in
           k C.pp c C.pp new_c (Util.pp_list pp_c_s) st.demod_clauses);
      assert(C.lits new_c |> Literals.vars_distinct);
      SimplM.return_new new_c
    )

  let demodulate c = 
    assert (Term.VarSet.for_all (fun v -> HVar.id v >= 0) (Literals.vars (C.lits c) |> Term.VarSet.of_list));
    ZProf.with_prof prof_demodulate demodulate_ c

  let local_rewrite c =
    assert(Env.flex_get k_local_rw != `Off);

    let neqs, others =
      CCArray.fold_left (fun (neq_map, others) lit ->
        match lit with
        | Literal.Equation(lhs,rhs,sign) ->
          if sign && T.is_true_or_false rhs then (
            let negate t = if T.equal t T.true_ then T.false_ else T.true_ in
            (T.Map.add lhs (negate rhs) neq_map, others)
          ) else if not sign then (
            match Ordering.compare ord lhs rhs with
            | Gt -> (T.Map.add lhs rhs neq_map, others)
            | Lt -> (T.Map.add rhs lhs neq_map, others)
            | _ -> ((neq_map), lit::others)
          ) else ((neq_map), lit::others)
        | _ -> ((neq_map), lit::others)
      ) ((Term.Map.empty),[]) (C.lits c) in
    
    let normalize ~restrict ~neqs t =
      let only_green_ctx = Env.flex_get k_local_rw == `GreenContext in
      
      let rec aux ~top t =
        match T.Map.get t neqs with
        | Some t' when not restrict || not top -> aux ~top t'
        | _ ->
          begin
            match T.view t with
            | T.App(hd, args) when not (T.is_var hd) || not only_green_ctx ->
              let hd' = aux ~top:false hd in
              let args' = List.map (aux ~top:false) args in
              if T.equal hd hd' && T.same_l args args' then t
              else aux ~top:false (T.app hd' args')
            | T.AppBuiltin(hd, args) ->
              let args' = List.map (aux ~top:false) args in
              if T.same_l args args' then t
              else aux ~top:false (T.app_builtin ~ty:(T.ty t) hd args')
            | T.Fun _ when not only_green_ctx ->
              let pref,body = T.open_fun t in
              let body' = aux ~top:false body in
              if T.equal body body' then t
              else T.fun_l pref body'
            | _ -> t (* do not rewrite under lambdas *)
          end in
      aux ~top:true t in

    let rewritten = ref false in
    let new_lits =
      CCArray.map (function
      | Lit.Equation(lhs,rhs,sign) as l ->
        if sign && T.is_true_or_false rhs then (
          let lhs' = normalize ~restrict:true ~neqs lhs in
          if not (T.equal lhs lhs') then (
            rewritten := true;
            Lit.mk_lit lhs' rhs sign
          ) else l
        ) else if not sign then (
          let lhs', rhs' = 
            match Ordering.compare ord lhs rhs with
            | Gt -> normalize ~restrict:true ~neqs lhs, normalize ~restrict:false ~neqs rhs
            | Lt -> normalize ~restrict:false ~neqs lhs, normalize ~restrict:true ~neqs rhs
            | _ -> normalize ~restrict:false ~neqs lhs, normalize ~restrict:false ~neqs rhs 
          in
          if not (T.equal lhs lhs') || not (T.equal rhs rhs') then (
            rewritten := true;
            Lit.mk_lit lhs' rhs' sign
          ) else l
        ) else (
          let lhs',rhs' = normalize ~restrict:false ~neqs lhs, normalize ~restrict:false ~neqs rhs in
          if not (T.equal lhs lhs') || not (T.equal rhs rhs') then (
              rewritten := true;
              Lit.mk_lit lhs' rhs' sign
          ) else l
        )
      | x -> x) (C.lits c) in
    if not !rewritten then SimplM.return_same c
    else (
      let new_lits = CCArray.to_list new_lits in
      let proof = Proof.Step.simp [C.proof_parent c] ~rule:(Proof.Rule.mk "local_rewriting") in
      let new_c = C.create ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof in
      Util.debugf ~section 1 "local_rw(@[%a@]):@.@[%a@]@." (fun k -> k C.pp c C.pp new_c);
      SimplM.return_new new_c
    )

    

  let canonize_variables c =
    let all_vars = Literals.vars (C.lits c) 
                   |> (fun v -> InnerTerm.VarSet.of_list (v:>InnerTerm.t HVar.t list)) in
    let neg_vars_renaming = Subst.FO.canonize_neg_vars ~var_set:all_vars in 
    if Subst.is_empty neg_vars_renaming then SimplM.return_same c
    else (
      let new_lits = Literals.apply_subst Subst.Renaming.none neg_vars_renaming (C.lits c, 0)
                     |> CCArray.to_list in
      let proof = Proof.Step.inference [C.proof_parent c] ~rule:(Proof.Rule.mk "cannonize vars") in
      let new_c = C.create ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof in
      SimplM.return_new new_c)

  let do_ext_sup from_c from_p from_t into_c into_p into_t = 
    let sc_f, sc_i = 0, 1 in
    if Type.equal (Term.ty from_t) (Term.ty into_t) &&
       not (C.id from_c = C.id into_c && Position.equal from_p into_p) then (

      match find_ho_disagremeents (from_t, sc_f) (into_t, sc_i) with 
      | Some (disagreements, subst) ->
        assert(not @@ US.has_constr subst);        
        let renaming = Subst.Renaming.create () in
        let subst = US.subst subst in
        let lits_f = Lits.apply_subst renaming subst (C.lits from_c, sc_f) in
        let lits_i = Lits.apply_subst renaming subst (C.lits into_c, sc_i) in
        
        let app_subst renaming scoped_t =
          Subst.FO.apply renaming subst scoped_t in
        
        let new_neq_lits = 
          List.map (fun (arg_f, arg_i) ->
            Lit.mk_neq (app_subst renaming (arg_f, sc_f)) (app_subst renaming (arg_i, sc_i))) 
          disagreements  in

        
        let (i, pos_f) = Lits.Pos.cut from_p in
        let from_s = Lits.Pos.at lits_f (Position.arg i (Position.opp pos_f)) in
        Lits.Pos.replace lits_i ~at:into_p ~by:(from_s);
        let new_lits = new_neq_lits @ CCArray.except_idx lits_f i  @ CCArray.to_list lits_i in
        let trail = C.trail_l [from_c; into_c] in
        let penalty = max (C.penalty from_c) (C.penalty into_c) in
        let tags = [Proof.Tag.T_ho] in
        let proof =
          Proof.Step.inference
            [C.proof_parent_subst renaming (from_c, sc_f) subst;
              C.proof_parent_subst renaming  (into_c, sc_i) subst] 
            ~rule:(Proof.Rule.mk "ext_sup") ~tags in
        let new_c = C.create ~trail ~penalty new_lits proof in
        Some new_c
      | None -> None
    ) else None


  (* Given a "from"-clause C \/ f t1 ... tn = s  and 
     "into"-clause D \/ f u1 .. un (~)= v, where some of the t_i 
     (and consequently u_i) are of functional type, construct
     a clause C \/ D \/ t1 ~= u1 \/ ... tn ~= un \/ s (~)= v.

     Intuitively, we are waiting for efficient extensionality rules
     to kick in and fix the problem of not being able to paramodulate
     with this equation.

     Currently with no restrictions or indexing. After initial evaluation,
     will find ways to restrict it somehow. *)
  let retrieve_from_extdec_idx idx id = 
    let cl_map = ID.Map.find_opt id idx in
    match cl_map with
    | None -> Iter.empty
    | Some cl_map -> 
      C.Tbl.to_iter cl_map 
      |> Iter.flat_map (fun (c, l) -> 
          Iter.of_list l
          |> Iter.map (fun (t,p) -> (c,t,p)))

  let ext_sup_act given =
    if ext_rule_eligible given then (
      let eligible = 
        if Env.flex_get k_ext_dec_lits = `OnlyMax then C.Eligible.param given else C.Eligible.always in
      Lits.fold_eqn ~ord ~both:true ~sign:true ~eligible (C.lits given)
      |> Iter.flat_map (fun (l,_,sign,pos) ->
          let hd,args = T.as_app l in
          if T.is_const hd && T.has_ho_subterm l then (
            let inf_partners = retrieve_from_extdec_idx !_ext_dec_into_idx (T.as_const_exn hd) in
            Iter.map (fun (into_c,into_t, into_p) -> 
                do_ext_sup given pos l into_c into_p into_t) inf_partners)
          else Iter.empty)
      |> Iter.filter_map CCFun.id
      |> Iter.to_list)
    else []

  let ext_sup_pas given =
    if ext_rule_eligible given then ( 
      let which, eligible =
        if Env.flex_get k_ext_dec_lits = `OnlyMax then `Max, C.Eligible.res given 
        else `All, C.Eligible.always in
      Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false ~ty_args:false 
        ~ord ~which ~subterms:true ~eligible (C.lits given)
      |> Iter.flat_map (fun (t,p) ->
          let hd, args = T.as_app t in
          if T.is_const hd && T.has_ho_subterm t  then (
            let inf_partners = retrieve_from_extdec_idx !_ext_dec_from_idx (T.as_const_exn hd) in
            Iter.map (fun (from_c,from_t, from_p) -> 
                do_ext_sup from_c from_p from_t given p t) inf_partners) 
          else Iter.empty))
      |> Iter.filter_map CCFun.id
      |> Iter.to_list
    else []

  let ext_inst_sup_act given =
    if ext_rule_eligible given then (
      let eligible =
        if Env.flex_get k_ext_dec_lits = `OnlyMax then C.Eligible.param given else C.Eligible.always in
      Lits.fold_eqn ~ord ~both:true ~sign:true ~eligible (C.lits given)
      |> Iter.flat_map (fun (l,_,sign,pos) ->
          let hd,args = T.as_app l in
          if T.is_const hd && T.has_ho_subterm l then (
            let inf_partners = retrieve_from_extdec_idx !_ext_dec_into_idx (T.as_const_exn hd) in
            Iter.map (fun (into_c,into_t, _) -> 
              do_ext_inst ~parents:[given;into_c] (l, 0) (into_t, 1)
          ) inf_partners)
          else Iter.empty)
      |> Iter.to_list
      |> CCList.flatten)
    else []

  let ext_inst_sup_pas given =
    if ext_rule_eligible given then ( 
      let which, eligible =
        if Env.flex_get k_ext_dec_lits = `OnlyMax then `Max, C.Eligible.res given 
        else `All, C.Eligible.always in
      Lits.fold_terms ~vars:false ~var_args:false ~fun_bodies:false ~ty_args:false 
        ~ord ~which ~subterms:true ~eligible (C.lits given)
      |> Iter.flat_map (fun (t,p) ->
          let hd, args = T.as_app t in
          if T.is_const hd && T.has_ho_subterm t  then (
            Iter.map (fun (from_c,from_t, from_p) -> 
              do_ext_inst ~parents:[from_c; given] (from_t,0) (t,1))
            (retrieve_from_extdec_idx !_ext_dec_from_idx (T.as_const_exn hd)))
          else Iter.empty))
      |> Iter.to_list
      |> CCList.flatten
    else []

  let ext_eqres_aux c =
    let eligible = C.Eligible.always in
    if ext_rule_eligible c then (
      let res = 
        Literals.fold_eqn (C.lits c) ~eligible ~ord ~both:false ~sign:false
        |> Iter.to_list
        |> CCList.filter_map (fun (lhs,rhs,sign,pos) ->
            assert(sign = false);
            let idx = Lits.Pos.idx pos in
            if Env.flex_get k_ext_dec_lits != `OnlyMax ||
               BV.get (C.eligible_res_no_subst c) idx then (
              let sc = 0 in
              match find_ho_disagremeents (lhs,sc) (rhs, sc) with
              | Some (disagremeents, subst) ->
                let new_neq_lits =
                  List.map (fun (s,t) -> Lit.mk_neq s t) disagremeents in
                let i, _ = Literals.Pos.cut pos in
                let new_lits =
                  (Array.of_list @@ new_neq_lits @ CCArray.except_idx (C.lits c) i, sc)
                  |> Literals.apply_subst (Subst.Renaming.create()) (US.subst subst)
                  |> Array.to_list in
                let proof =
                  Proof.Step.inference [C.proof_parent c] ~rule:(Proof.Rule.mk "ext_eqres") in
                let new_c =
                  C.create ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof in
                Some new_c
              | None -> None)
            else None)
        in
      Util.incr_stat stat_ext_dec;
      res
    ) else []

  let ext_inst_eqres c =
    let eligible = C.Eligible.always in
    if ext_rule_eligible c then (
      let res = 
        Literals.fold_eqn (C.lits c) ~eligible ~ord ~both:false ~sign:false
        |> Iter.to_list
        |> CCList.flat_map (fun (lhs,rhs,sign,pos) ->
            assert(sign = false);
            let idx = Lits.Pos.idx pos in
            if Env.flex_get k_ext_dec_lits != `OnlyMax ||
               BV.get (C.eligible_res_no_subst c) idx then (
              do_ext_inst ~parents:[c] (lhs,0) (rhs,0))
            else [])
        in
      Util.incr_stat stat_ext_inst;
      res
    ) else []


  let ext_eqres given = 
    ZProf.with_prof prof_ext_dec ext_eqres_aux given

  (* complete [f = g] into [f x1…xn = g x1…xn] for each [n ≥ 1] *)
  let complete_eq_args (c:C.t) : C.t list =
    let var_offset = C.Seq.vars c |> Type.Seq.max_var |> succ in
    let eligible = C.Eligible.param c in
    let aux ?(start=1) ~poly lits lit_idx t u =
      let n_ty_args, ty_args, _ = Type.open_poly_fun (T.ty t) in
      assert (n_ty_args = 0);
      assert (ty_args <> []);
      let vars =
        List.mapi
          (fun i ty -> HVar.make ~ty (i+var_offset) |> T.var)
          ty_args
      in
      CCList.(start -- List.length vars)
      |> List.map
        (fun prefix_len ->
          let vars_prefix = CCList.take prefix_len vars in
          let new_lit = Literal.mk_eq (T.app t vars_prefix) (T.app u vars_prefix) in
          let new_lits = new_lit :: CCArray.except_idx lits lit_idx in
          let proof =
            Proof.Step.inference [C.proof_parent c]
              (* THIS NAME IS USED IN HEURISTICS -- CHANGE CAREFULLY! *)
              ~rule:(Proof.Rule.mk "ho_complete_eq")
              ~tags:[Proof.Tag.T_ho;Proof.Tag.T_dont_increase_depth]
          in
          let penalty = C.penalty c + (if poly then 1 else 0) in
          let new_c =
            C.create new_lits proof ~penalty ~trail:(C.trail c) in

          if poly then (
            C.set_flag SClause.flag_poly_arg_cong_res new_c true;
          );

          new_c)
      in
      let is_poly_arg_cong_res = C.get_flag SClause.flag_poly_arg_cong_res c in
      let new_c =
        C.lits c
        |> Iter.of_array |> Util.seq_zipi
        |> Iter.filter (fun (idx,lit) -> eligible idx lit)
        |> Iter.flat_map_l
          (fun (lit_idx,lit) -> match lit with
            | Literal.Equation (t, u, true) when Type.is_fun (T.ty t) ->
              aux ~poly:false (C.lits c) lit_idx t u
            | Literal.Equation (t, u, true) 
              when Type.is_var (T.ty t) && not is_poly_arg_cong_res ->
              (* A polymorphic variable might be functional on the ground level *)
              let ty_args = 
                OSeq.iterate [Type.var @@ HVar.fresh ~ty:Type.tType ()] 
                  (fun types_w -> 
                    Type.var (HVar.fresh ~ty:Type.tType ()) :: types_w) in
              let res = 
                ty_args
                |> OSeq.mapi (fun arrarg_idx arrow_args -> 
                    let var = Type.as_var_exn (T.ty t) in
                    let funty = 
                      T.of_ty 
                        (Type.arrow arrow_args (Type.var (HVar.fresh ~ty:Type.tType ()))) in
                    let subst = Unif_subst.FO.singleton (var,0) (funty,0) in
                    let renaming, subst = Subst.Renaming.none, Unif_subst.subst subst in
                    let lits' = Lits.apply_subst renaming subst (C.lits c, 0) in
                    let t' = Subst.FO.apply renaming subst (t, 0) in
                    let u' = Subst.FO.apply renaming subst (u, 0) in
                    let new_cl = aux ~poly:true ~start:(arrarg_idx+1) lits' lit_idx t' u' in
                    assert(List.length new_cl == 1);
                    List.hd new_cl
                ) in
              let first_two, rest = 
                OSeq.take 2 res, OSeq.map CCOpt.return (OSeq.drop 2 res) in
              let stm =  Stm.make ~penalty:(C.penalty c + 20) ~parents:[c] rest in
              StmQ.add (_stmq()) stm;
              
              OSeq.to_list first_two
            | _ -> [])
        |> Iter.to_rev_list
      in
      if new_c<>[] then (
        Util.add_stat stat_complete_eq (List.length new_c);
        Util.debugf ~section 4
          "(@[complete-eq@ :clause %a@ :yields (@[<hv>%a@])@])"
          (fun k->k C.pp c (Util.pp_list ~sep:" " C.pp) new_c);
      );
      new_c

  (** Find clauses that [given] may demodulate, add them to set *)
  let backward_demodulate set given =
    ZProf.enter_prof prof_back_demodulate;
    let renaming = Subst.Renaming.create () in
    (* find clauses that might be rewritten by l -> r *)
    let recurse ~oriented set l r =
      I.retrieve_specializations (!_idx_back_demod,1) (l,0)
      |> Iter.fold
        (fun set (_t',with_pos,subst) ->
           let c = with_pos.C.WithPos.clause in
           (* subst(l) matches t' and is > subst(r), very likely to rewrite! *)
           if (C.trail_subsumes c given && (oriented ||
                                            O.compare ord
                                              (S.FO.apply renaming subst (l,0))
                                              (S.FO.apply renaming subst (r,0)) = Comp.Gt
                                           )
              )
           then  (* add the clause to the set, it may be rewritten by l -> r *)
             C.ClauseSet.add c set
           else set)
        set
    in
    let set' = match C.lits given with
      | [|Lit.Equation (l,r,true) |] ->
        begin match Ordering.compare ord l r with
          | Comp.Gt -> recurse ~oriented:true set l r
          | Comp.Lt -> recurse ~oriented:true set r l
          | _ ->
            let set' = recurse ~oriented:false set l r in
            recurse ~oriented:false set' r l
            (* both sides can rewrite, but we need to check ordering *)
        end
      | _ -> set
    in
    ZProf.exit_prof prof_back_demodulate;
    set'

  let is_tautology c =
    let is_tauto = Lits.is_trivial (C.lits c) || Trail.is_trivial (C.trail c) in
    if is_tauto then Util.debugf ~section 3 "@[@[%a@]@ is a tautology@]" (fun k->k C.pp c);
    is_tauto

  (* semantic tautology deletion, using a congruence closure algorithm
     to see if negative literals imply some positive literal *)
  let is_semantic_tautology_real (c:C.t) : bool =
    (* create the congruence closure of all negative equations of [c] *)
    let cc = Congruence.FO.create ~size:8 () in
    let cc =
      Array.fold_left
        (fun cc lit -> match lit with
           | Lit.Equation (l, r, false) ->
             Congruence.FO.mk_eq cc l r
           | _ -> cc)
        cc (C.lits c)
    in
    let res = CCArray.exists
        (function
          | Lit.Equation (l, r, true) ->
            (* if l=r is implied by the congruence, then the clause is redundant *)
            Congruence.FO.is_eq cc l r
          | _ -> false)
        (C.lits c)
    in
    if res then (
      Util.incr_stat stat_semantic_tautology;
      Util.debugf ~section 2 "@[@[%a@]@ is a semantic tautology@]" (fun k->k C.pp c);
    );
    res

  let is_semantic_tautology_ c =
    if Array.length (C.lits c) >= 2 &&
       CCArray.exists Lit.is_neg (C.lits c) &&
       CCArray.exists Lit.is_pos (C.lits c)
    then is_semantic_tautology_real c
    else false

  let is_semantic_tautology c =
    ZProf.with_prof prof_semantic_tautology is_semantic_tautology_ c

  let var_in_subst_ us v sc =
    S.mem (US.subst us) ((v:T.var:>InnerTerm.t HVar.t),sc)

  let basic_simplify c =
    if C.get_flag flag_simplified c
    then SimplM.return_same c
    else (
      ZProf.enter_prof prof_basic_simplify;
      Util.incr_stat stat_basic_simplify_calls;
      let lits = C.lits c in
      let has_changed = ref false in
      let tags = ref [] in
      (* bv: literals to keep *)
      let bv = BV.create ~size:(Array.length lits) true in
      (* eliminate absurd lits *)
      Array.iteri
        (fun i lit ->
           if Lit.is_absurd lit then (
             has_changed := true;
             tags := Lit.is_absurd_tags lit @ !tags;
             BV.reset bv i
           ))
        lits;
      (* eliminate inequations x != t *)
      let us = ref US.empty in
      let try_unif i t1 sc1 t2 sc2 =
        try
          let subst' = Unif.FO.unify_full ~subst:!us (t1,sc1) (t2,sc2) in
          has_changed := true;
          BV.reset bv i;
          us := subst';
        with Unif.Fail -> ()
      in
      Array.iteri
        (fun i lit ->
           let can_destr_eq_var v =
             not (var_in_subst_ !us v 0) && not (Type.is_fun (HVar.ty v))
           in
           if BV.get bv i then match lit with
             | Lit.Equation (l, r, false) when not (T.is_true_or_false r) ->
               begin match T.view l, T.view r with
                 | T.Var v, _ when can_destr_eq_var v ->
                   (* eligible for destructive Equality Resolution, try to update
                       [subst]. Careful: in the case [X!=a | X!=b | C] we must
                       bind X only to [a] or [b], not unify [a] with [b].

                      NOTE: this also works for HO constraints for unshielded vars *)
                   try_unif i l 0 r 0
                 | _, T.Var v when can_destr_eq_var v ->
                   try_unif i r 0 l 0
                 | _ -> ()
               end
             | _ -> ())
        lits;
      let new_lits = BV.select bv lits in
      let new_lits =
        if US.is_empty !us then new_lits
        else (
          assert !has_changed;
          let subst = US.subst !us in
          let tgs = US.tags !us in
          tags := tgs @ !tags;
          let c_guard = Literal.of_unif_subst Subst.Renaming.none !us in
          c_guard @ Lit.apply_subst_list Subst.Renaming.none subst (new_lits,0)
        )
      in
      let new_lits = CCList.uniq ~eq:Lit.equal_com new_lits in
      if not !has_changed && List.length new_lits = Array.length lits then (
        ZProf.exit_prof prof_basic_simplify;
        C.set_flag flag_simplified c true;
        SimplM.return_same c  (* no simplification *)
      ) else (
        let parent =
          if Subst.is_empty (US.subst !us) then C.proof_parent c
          else C.proof_parent_subst Subst.Renaming.none (c,0) (US.subst !us)
        in
        let proof =
          Proof.Step.simp [parent]
            ~tags:!tags ~rule:(Proof.Rule.mk "simplify") in
        let new_lits = if List.exists Lit.is_trivial new_lits then [Lit.mk_tauto] else new_lits in
        let new_clause =
          C.create ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof
        in
        Util.debugf ~section 3
          "@[<>@[%a@]@ @[<2>basic_simplifies into@ @[%a@]@]@ with @[%a@]@]"
          (fun k->k C.pp c C.pp new_clause US.pp !us);
        Util.incr_stat stat_basic_simplify;
        ZProf.exit_prof prof_basic_simplify;
        SimplM.return_new new_clause
      )
    )

  let handle_distinct_constants lit =
    match lit with
    | Lit.Equation (l, r, sign) when T.is_const l && T.is_const r ->
      let s1 = T.head_exn l and s2 = T.head_exn r in
      if ID.is_distinct_object s1 && ID.is_distinct_object s2
      then
        if sign = (ID.equal s1 s2)
        then Some (Lit.mk_tauto,[],[Proof.Tag.T_distinct])  (* "a" = "a", or "a" != "b" *)
        else Some (Lit.mk_absurd,[],[Proof.Tag.T_distinct]) (* "a" = "b" or "a" != "a" *)
      else None
    | _ -> None

  exception FoundMatch of T.t * C.t * S.t

  let positive_simplify_reflect c =
    ZProf.enter_prof prof_pos_simplify_reflect;
    (* iterate through literals and try to resolve negative ones *)
    let rec iterate_lits acc lits clauses = match lits with
      | [] -> List.rev acc, clauses
      | (Lit.Equation (s, t, false) as lit)::lits' ->
        begin match equatable_terms clauses s t with
          | None -> (* keep literal *)
            iterate_lits (lit::acc) lits' clauses
          | Some new_clauses -> (* drop literal, remember clauses *)
            iterate_lits acc lits' new_clauses
        end
      | lit::lits' -> iterate_lits (lit::acc) lits' clauses
    (* try to make the terms equal using some positive unit clauses
       from active_set *)
    and equatable_terms clauses t1 t2 =
      match T.Classic.view t1, T.Classic.view t2 with
      | _ when T.equal t1 t2 -> Some clauses  (* trivial *)
      | T.Classic.App (f, ss), T.Classic.App (g, ts)
        when ID.equal f g && List.length ss = List.length ts ->
        (* try to make the terms equal directly *)
        begin match equate_root clauses t1 t2 with
          | None -> (* otherwise try to make subterms pairwise equal *)
            let ok, clauses = List.fold_left2
                (fun (ok, clauses) t1' t2' ->
                   if ok
                   then match equatable_terms clauses t1' t2' with
                     | None -> false, []
                     | Some clauses -> true, clauses
                   else false, [])
                (true, clauses) ss ts
            in
            if ok then Some clauses else None
          | Some clauses -> Some clauses
        end
      | _ -> equate_root clauses t1 t2 (* try to solve it with a unit equality *)
    (* try to equate terms with a positive unit clause that match them *)
    and equate_root clauses t1 t2 =
      try
        UnitIdx.retrieve ~sign:true (!_idx_simpl,1)(t1,0)
        |> Iter.iter
          (fun (l,r,(_,_,_,c'),subst) ->
             let app_sub t = 
              Term.normalize_bools @@ Lambda.eta_expand @@ Lambda.snf @@ 
                Subst.FO.apply Subst.Renaming.none subst t in
             assert(T.equal (app_sub (l,1)) (app_sub (t1, 0)));
             if C.trail_subsumes c' c &&
                Term.equal (app_sub (r,1)) (app_sub (t2,0))
             then begin
               (* t1!=t2 is refuted by l\sigma = r\sigma *)
               Util.debugf ~section 4
                 "@[<2>equate @[%a@]@ and @[%a@]@ using @[%a@]@]"
                 (fun k->k T.pp t1 T.pp t2 C.pp c');
               raise (FoundMatch (r, c', subst)) (* success *)
             end
          );
        None (* no match *)
      with FoundMatch (_r, c', subst) ->
        Some (C.proof_parent_subst Subst.Renaming.none (c',1) subst :: clauses)  (* success *)
    in
    (* fold over literals *)
    let lits, premises = iterate_lits [] (C.lits c |> Array.to_list) [] in
    if List.length lits = Array.length (C.lits c)
    then (
      (* no literal removed, keep c *)
      ZProf.exit_prof prof_pos_simplify_reflect;
      SimplM.return_same c
    ) else (
      let proof =
        Proof.Step.simp ~rule:(Proof.Rule.mk "simplify_reflect+")
          (C.proof_parent c::premises) in
      let trail = C.trail c and penalty = C.penalty c in
      let new_c = C.create ~trail ~penalty lits proof in
      Util.debugf ~section 3 "@[@[%a@]@ pos_simplify_reflect into @[%a@]@]"
        (fun k->k C.pp c C.pp new_c);
      ZProf.exit_prof prof_pos_simplify_reflect;
      SimplM.return_new new_c
    )

  let negative_simplify_reflect c =
    ZProf.enter_prof prof_neg_simplify_reflect;
    (* iterate through literals and try to resolve positive ones *)
    let rec iterate_lits acc lits clauses = match lits with
      | [] -> List.rev acc, clauses
      | (Lit.Equation (s, t, true) as lit)::lits' ->
        begin match can_refute s t, can_refute t s with
          | None, None -> (* keep literal *)
            iterate_lits (lit::acc) lits' clauses
          | Some new_clause, _ | _, Some new_clause -> (* drop literal, remember clause *)
            iterate_lits acc lits' (new_clause :: clauses)
        end
      | lit::lits' -> iterate_lits (lit::acc) lits' clauses
    (* try to remove the literal using a negative unit clause *)
    and can_refute s t =
      try
        UnitIdx.retrieve ~sign:false (!_idx_simpl,1) (s,0)
        |> Iter.iter
          (fun (l, r, (_,_,_,c'), subst) ->
             assert (Unif.FO.equal ~subst (l, 1) (s, 0));
             Util.debugf ~section 3 "@[neg_reflect trying to eliminate@ @[%a=%a@]@ with @[%a@]@]"
               (fun k->k T.pp s T.pp t C.pp c');
             if C.trail_subsumes c' c && Unif.FO.equal ~subst (r, 1) (t, 0)
             then begin
               (* TODO: useless? *)
               let subst = Unif.FO.matching ~subst ~pattern:(r, 1) (t, 0) in
               Util.debugf ~section 3 "@[neg_reflect eliminates@ @[%a=%a@]@ with @[%a@]@]"
                 (fun k->k T.pp s T.pp t C.pp c');
               raise (FoundMatch (r, c', subst)) (* success *)
             end
          );
        None (* no match *)
      with FoundMatch (_r, c', subst) ->
        Some (C.proof_parent_subst Subst.Renaming.none (c',1) subst) (* success *)
    in
    (* fold over literals *)
    let lits, premises = iterate_lits [] (C.lits c |> Array.to_list) [] in
    if List.length lits = Array.length (C.lits c)
    then (
      (* no literal removed *)
      ZProf.exit_prof prof_neg_simplify_reflect;
      Util.debug ~section 3 "neg_reflect did not simplify the clause";
      SimplM.return_same c
    ) else (
      let proof =
        Proof.Step.simp
          ~rule:(Proof.Rule.mk "simplify_reflect-")
          (C.proof_parent c :: premises) in
      let new_c = C.create ~trail:(C.trail c) ~penalty:(C.penalty c) lits proof in
      Util.debugf ~section 3 "@[@[%a@]@ neg_simplify_reflect into @[%a@]@]"
        (fun k->k C.pp c C.pp new_c);
      ZProf.exit_prof prof_neg_simplify_reflect;
      SimplM.return_new new_c
    )

  (* ----------------------------------------------------------------------
   * subsumption
   * ---------------------------------------------------------------------- *)

  (** raised when a subsuming substitution is found *)
  exception SubsumptionFound of S.t

  (** check that every literal in a matches at least one literal in b *)
  let all_lits_match a sc_a b sc_b =
    CCArray.for_all
      (fun lita ->
         CCArray.exists
           (fun litb ->
              not (Iter.is_empty (Lit.subsumes (lita, sc_a) (litb, sc_b))))
           b)
      a

  (** Compare literals by subsumption difficulty
      (see "towards efficient subsumption", Tammet).
      We sort by increasing order, so non-ground, deep, heavy literals are
      smaller (thus tested early) *)
  let compare_literals_subsumption lita litb =
    CCOrd.(
      (* ground literal is bigger *)
      bool (Lit.is_ground lita) (Lit.is_ground litb)
      (* deep literal is smaller *)
      <?> (map Lit.depth (opp int), lita, litb)
      (* heavy literal is smaller *)
      <?> (map Lit.weight (opp int), lita, litb)
    )

  (* replace the bitvector system by some backtracking scheme?
     XXX: maybe not a good idea. the algorithm is actually quite subtle
     and needs tight control over the traversal (lookahead of free
     variables in next literals, see [check_vars]...) *)

  (** Check whether [a] subsumes [b], and if it does, return the
      corresponding substitution *)
  let subsumes_with_ (a,sc_a) (b,sc_b) : _ option =
    (* a must not have more literals, and it must be possible to bind
        all its vars during subsumption *)
    if Array.length a > Array.length b
    || not (all_lits_match a sc_a b sc_b)
    then None
    else (
      (* sort a copy of [a] by decreasing difficulty *)
      let a = Array.copy a in
      let tags = ref [] in
      (* try to subsumes literals of b whose index are not in bv, with [subst] *)
      let rec try_permutations i subst bv =
        if i = Array.length a
        then raise (SubsumptionFound subst)
        else
          let lita = a.(i) in
          find_matched lita i subst bv 0
      (* find literals of b that are not bv and that are matched by lita *)
      and find_matched lita i subst bv j =
        if j = Array.length b then ()
        (* if litb is already matched, continue *)
        else if BV.get bv j then find_matched lita i subst bv (j+1)
        else (
          let litb = b.(j) in
          BV.set bv j;
          (* match lita and litb, then flag litb as used, and try with next literal of a *)
          let n_subst = ref 0 in
          Lit.subsumes ~subst (lita, sc_a) (litb, sc_b)
            (fun (subst',tgs) ->
               incr n_subst;
               tags := tgs @ !tags;
               try_permutations (i+1) subst' bv);
          BV.reset bv j;
          (* some variable of lita occur in a[j+1...], try another literal of b *)
          if !n_subst > 0 && not (check_vars lita (i+1))
          then () (* no backtracking for litb *)
          else find_matched lita i subst bv (j+1)
        )
      (* does some literal in a[j...] contain a variable in l or r? *)
      and check_vars lit j =
        let vars = Lit.vars lit in
        if vars = []
        then false
        else
          try
            for k = j to Array.length a - 1 do
              if List.exists (fun v -> Lit.var_occurs v a.(k)) vars
              then raise Exit
            done;
            false
          with Exit -> true
      in
      try
        Array.sort compare_literals_subsumption a;
        let bv = BV.empty () in
        try_permutations 0 S.empty bv;
        None
      with (SubsumptionFound subst) ->
        Util.debugf ~section 2 "(@[<hv>subsumes@ :c1 @[%a@]@ :c2 @[%a@]@ :subst %a%a@]"
          (fun k->k Lits.pp a Lits.pp b Subst.pp subst Proof.pp_tags !tags);
        Some (subst, !tags)
    )

  let subsumes_with a b =
    ZProf.enter_prof prof_subsumption;
    Util.incr_stat stat_subsumption_call;
    let (c_a, _), (c_b, _) = a,b in
    let w_a = CCArray.fold (fun acc l -> acc + Lit.weight l) 0 c_a in
    let w_b = CCArray.fold (fun acc l -> acc + Lit.weight l) 0 c_b in

    if w_a = w_b && Literals.equal_com c_a c_b then Some (Subst.empty, [])
    else (
      let res = if w_a <= w_b then subsumes_with_ a b else None in
      ZProf.exit_prof prof_subsumption;
      res
    )

  let subsumes_classic a b = match subsumes_with (a,0) (b,1) with
    | None -> false
    | Some _ -> true

  let subsumes a b = 
    let module SS = SolidSubsumption.Make(struct let st = Env.flex_state () end) in

    if not @@ Env.flex_get k_solid_subsumption 
       || Env.flex_get Combinators.k_enable_combinators
    then subsumes_classic a b 
    else (
      try 
        SS.subsumes a b
      with SolidSubsumption.UnsupportedLiteralKind -> 
        subsumes_classic a b)

  (* anti-unification of the two terms with at most one disagreement point *)
  let anti_unify (t:T.t)(u:T.t): (T.t * T.t) option =
    match Unif.FO.anti_unify ~cut:1 t u with
    | Some [pair] -> Some pair
    | _ -> None

  let eq_subsumes_with (a,sc_a) (b,sc_b) =
    (* subsume a literal using a = b *)
    let rec equate_lit_with a b lit = match lit with
      | Lit.Equation (u, v, true) when not (T.equal u v) -> equate_terms a b u v
      | _ -> None
    (* make u=v using a=b once *)
    and equate_terms a b u v =
      begin match anti_unify u v with
        | None -> None
        | Some (u', v') -> equate_root a b u' v'
      end
    (* check whether a\sigma = u and b\sigma = v, for some sigma;
       or the commutation thereof *)
    and equate_root a b u v: Subst.t option =
      let check_ a b u v =
        try
          if Term.size a > Term.size u || Term.size b > Term.size v then
            raise Unif.Fail;
          let subst = Unif.FO.matching ~pattern:(a, sc_a) (u, sc_b) in
          let subst = Unif.FO.matching ~subst ~pattern:(b, sc_a) (v, sc_b) in
          Some subst
        with Unif.Fail -> None
      in
      begin match check_ a b u v with
        | Some _ as s -> s
        | None -> check_ b a u v
      end
    in
    (* check for each literal *)
    ZProf.enter_prof prof_eq_subsumption;
    Util.incr_stat stat_eq_subsumption_call;
    let res = match a with
      | [|Lit.Equation (s, t, true)|] ->
        let res = CCArray.find_map (equate_lit_with s t) b in
        begin match res with
          | None -> None
          | Some subst ->
            Util.debugf ~section 3 "@[<2>@[%a@]@ eq-subsumes @[%a@]@ :subst %a@]"
              (fun k->k Lits.pp a Lits.pp b Subst.pp subst);
            Util.incr_stat stat_eq_subsumption_success;
            Some subst
        end
      | _ -> None (* only a positive unit clause unit-subsumes a clause *)
    in
    ZProf.exit_prof prof_eq_subsumption;
    res

  let eq_subsumes a b = CCOpt.is_some (eq_subsumes_with (a,1) (b,0))

  let subsumed_by_active_set c =
    ZProf.enter_prof prof_subsumption_set;
    Util.incr_stat stat_subsumed_by_active_set_call;
    (* if there is an equation in c, try equality subsumption *)
    let try_eq_subsumption = CCArray.exists Lit.is_eqn (C.lits c) in
    (* use feature vector indexing *)
    let c = if Env.flex_get k_ground_subs_check > 0 then  C.ground_clause c else c in
    let res =
      SubsumIdx.retrieve_subsuming_c !_idx_fv c
      |> Iter.exists
        (fun c' ->
           C.trail_subsumes c' c
           &&
           ( (try_eq_subsumption && eq_subsumes (C.lits c') (C.lits c))
             ||
             subsumes (C.lits c') (C.lits c)
           ))
    in
    ZProf.exit_prof prof_subsumption_set;
    if res then (
      Util.debugf ~section 2 "@[<2>@[%a@]@ subsumed by active set@]" (fun k->k C.pp c);
      Util.incr_stat stat_clauses_subsumed;
    );
    res

  let subsumed_in_active_set acc c =
    ZProf.enter_prof prof_subsumption_in_set;
    Util.incr_stat stat_subsumed_in_active_set_call;
    (* if c is a single unit clause *)
    let try_eq_subsumption =
      C.is_unit_clause c && Lit.is_pos (C.lits c).(0)
    in
    (* use feature vector indexing *)
    let res =
      SubsumIdx.retrieve_subsumed_c !_idx_fv c
      |> Iter.fold
        (fun res c' ->
           if C.trail_subsumes c c'
           then
             let c' = if Env.flex_get k_ground_subs_check > 1 then C.ground_clause c' else c' in
             let redundant =
               (try_eq_subsumption && eq_subsumes (C.lits c) (C.lits c'))
               || subsumes (C.lits c) (C.lits c')
             in
             if redundant then (
               Util.incr_stat stat_clauses_subsumed;
               C.ClauseSet.add c' res
             ) else res
           else res)
        acc
    in
    ZProf.exit_prof prof_subsumption_in_set;
    res

  (* Number of equational lits. Used as an estimation for the difficulty of the subsumption
     check for this clause. *)
  let num_equational lits =
    Array.fold_left
      (fun acc lit -> match lit with
         | Lit.Equation _ -> acc+1
         | _ -> acc
      ) 0 lits

  (* ----------------------------------------------------------------------
   * contextual literal cutting
   * ---------------------------------------------------------------------- *)

  (* Performs successive contextual literal cuttings *)
  let rec contextual_literal_cutting_rec c =
    let open SimplM.Infix in
    if Array.length (C.lits c) <= 1
    || num_equational (C.lits c) > 3
    || Array.length (C.lits c) > 8
    then SimplM.return_same c
    else (
      (* do we need to try to use equality subsumption? *)
      let try_eq_subsumption = CCArray.exists Lit.is_eqn (C.lits c) in
      (* try to remove one literal from the literal array *)
      let remove_one_lit lits =
        Iter.of_array_i lits
        |> Iter.filter (fun (_,lit) -> not (Lit.is_constraint lit))
        |> Iter.find_map
          (fun (i,old_lit) ->
             (* negate literal *)
             lits.(i) <- Lit.negate old_lit;
             (* test for subsumption *)
             SubsumIdx.retrieve_subsuming !_idx_fv
               (Lits.Seq.to_form lits) (C.trail c |> Trail.labels)
             |> Iter.filter (fun c' -> C.trail_subsumes c' c)
             |> Iter.find_map
               (fun c' ->
                  let subst =
                    match
                      if try_eq_subsumption
                      then eq_subsumes_with (C.lits c',1) (lits,0)
                      else None
                    with
                    | Some s -> Some (s, [])
                    | None -> subsumes_with (C.lits c',1) (lits,0)
                  in
                  subst
                  |> CCOpt.map
                    (fun (subst,tags) ->
                       (* remove the literal and recurse *)
                       CCArray.except_idx lits i, i, c', subst, tags))
             |> CCFun.tap
               (fun _ ->
                  (* restore literal *)
                  lits.(i) <- old_lit))
      in
      begin match remove_one_lit (Array.copy (C.lits c)) with
        | None ->
          SimplM.return_same c (* no literal removed *)
        | Some (new_lits, _, c',subst,tags) ->
          (* hc' allowed us to cut a literal *)
          assert (List.length new_lits + 1 = Array.length (C.lits c));
          let proof =
            Proof.Step.simp
              ~rule:(Proof.Rule.mk "clc") ~tags
              [C.proof_parent c;
               C.proof_parent_subst Subst.Renaming.none (c',1) subst] in
          let new_c = C.create ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof in
          Util.debugf ~section 3
            "@[<2>contextual literal cutting@ in @[%a@]@ using @[%a@]@ gives @[%a@]@]"
            (fun k->k C.pp c C.pp c' C.pp new_c);
          Util.incr_stat stat_clc;
          (* try to cut another literal *)
          SimplM.return_new new_c >>= contextual_literal_cutting_rec
      end
    )

  let contextual_literal_cutting c =
    ZProf.enter_prof prof_clc;
    let res = contextual_literal_cutting_rec c in
    ZProf.exit_prof prof_clc;
    res

  (* ----------------------------------------------------------------------
   * contraction (condensation)
   * ---------------------------------------------------------------------- *)

  exception CondensedInto of Lit.t array * S.t * Subst.Renaming.t * Proof.tag list

  (** performs condensation on the clause. It looks for two literals l1 and l2 of same
      sign such that l1\sigma = l2, and hc\sigma \ {l2} subsumes hc. Then
      hc is simplified into hc\sigma \ {l2}.
      If there are too many equational literals, the simplification is disabled to
      avoid pathologically expensive subsumption checks.
      TODO remove this limitation after an efficient subsumption check is implemented. *)
  let rec condensation_rec c =
    let open SimplM.Infix in
    if Array.length (C.lits c) <= 1
    || num_equational (C.lits c) > 3
    || Array.length (C.lits c) > 8
    then SimplM.return_same c
    else
      (* scope is used to rename literals for subsumption *)
      let lits = C.lits c in
      let n = Array.length lits in
      try
        for i = 0 to n - 1 do
          let lit = lits.(i) in
          for j = i+1 to n - 1 do
            let lit' = lits.(j) in
            (* see whether [lit |= lit'], and if removing [lit] gives a clause
               that subsumes c. Also try to swap [lit] and [lit']. *)
            let subst_remove_lit =
              Lit.subsumes (lit, 0) (lit', 0)
              |> Iter.map (fun s -> s, i)
            and subst_remove_lit' =
              Lit.subsumes (lit', 0) (lit, 0)
              |> Iter.map (fun s -> s, j)
            in
            (* potential condensing substitutions *)
            let substs = Iter.append subst_remove_lit subst_remove_lit' in
            Iter.iter
              (fun ((subst,tags),idx_to_remove) ->
                 let new_lits = Array.sub lits 0 (n - 1) in
                 if idx_to_remove <> n-1
                 then new_lits.(idx_to_remove) <- lits.(n-1);  (* remove lit *)
                 let renaming = Subst.Renaming.create () in
                 let new_lits = Lits.apply_subst renaming subst (new_lits,0) in
                 (* check subsumption *)
                 if subsumes new_lits lits then (
                   raise (CondensedInto (new_lits, subst, renaming, tags))
                 ))
              substs
          done;
        done;
        SimplM.return_same c
      with CondensedInto (new_lits, subst, renaming, tags) ->
        (* clause is simplified *)
        let proof =
          Proof.Step.simp
            ~rule:(Proof.Rule.mk "condensation") ~tags
            [C.proof_parent_subst renaming (c,0) subst] in
        let c' = C.create_a ~trail:(C.trail c) ~penalty:(C.penalty c) new_lits proof in
        Util.debugf ~section 3
          "@[<2>condensation@ of @[%a@] (with @[%a@])@ gives @[%a@]@]"
          (fun k->k C.pp c S.pp subst C.pp c');
        (* try to condense further *)
        Util.incr_stat stat_condensation;
        SimplM.return_new c' >>= condensation_rec

  let condensation c =
    ZProf.with_prof prof_condensation condensation_rec c
  
  let subsumption_weight c =
    C.Seq.terms c
    |> Iter.fold (fun acc t -> (T.weight ~var:1 ~sym:(fun _ -> 2) t) + acc ) 0

  let immediate_subsume c immediate =
    let subsumes subsumer subsumee =
      (subsumption_weight subsumer <= subsumption_weight subsumee) &&
      C.trail_subsumes subsumer subsumee &&
      ((Array.exists Lit.is_eqn (C.lits subsumee) && 
          eq_subsumes (C.lits subsumer) (C.lits subsumee)) ||
        subsumes (C.lits subsumer) (C.lits subsumee)) in

    let immediate = Iter.filter (fun c' -> not (subsumes c c')) immediate in
    if Iter.exists C.is_empty immediate then None 
    else (
      immediate
      |> Iter.find_map (fun c' -> 
        if (subsumes c' c) then (
          C.mark_redundant c;
          Env.remove_active (Iter.singleton c);
          Env.remove_simpl (Iter.singleton c);
          Util.debugf ~section 1 "immediate subsume @[%a@]@." (fun k -> k C.pp c);
          Some c'
        ) else None))
    |> (function 
        | Some subsumer -> Some (Iter.singleton subsumer)
        | None -> Some immediate)

  let is_orphaned c =
    let res = not (C.is_empty c) && C.is_orphaned c in
    if res then (
      Util.incr_stat stat_orphan_checks
    );
    res

  let recognize_injectivity c =
    let exception Fail in

    (* avoiding cascading if-then-elses *)
    let fail_on condition =
      if condition then raise Fail in

    let find_in_args var args =
      fst @@ CCOpt.get_or ~default:(-1, T.true_)
        (CCList.find_idx (T.equal var) args) in

    try 
      fail_on (C.length c != 2);

      match C.lits c with
      | [|lit1; lit2|] ->
        fail_on (not ((Lit.is_pos lit1 || Lit.is_pos lit2) &&
                     (Lit.is_neg lit1 || Lit.is_neg lit2)));

        let pos_lit,neg_lit = 
          if Lit.is_pos lit1 then lit1, lit2 else lit2,lit1 in
       
        begin match pos_lit, neg_lit with
        | Equation(x,y,true), Equation(lhs,rhs,sign) ->
          fail_on (not (T.is_var x && T.is_var y));
          fail_on (T.equal x y);

          let (hd_lhs, lhs_args), (hd_rhs, rhs_args) = 
            CCPair.map_same T.as_app_mono (lhs,rhs) in
          
          fail_on (not (T.is_const hd_lhs && T.is_const hd_rhs));
          fail_on (not (T.equal hd_lhs hd_rhs));
          fail_on (not (List.length lhs_args == List.length rhs_args));

          fail_on (not ((find_in_args x lhs_args) != (-1) ||
                        (find_in_args x rhs_args) != (-1)));
          fail_on (not ((find_in_args y lhs_args) != (-1) ||
                        (find_in_args y rhs_args) != (-1)));
          
          (* reorient equations so that x appears in lhs *)
          let lhs,rhs,lhs_args,rhs_args =
            if find_in_args x lhs_args != -1 
            then (lhs, rhs, lhs_args, rhs_args)
            else (rhs, lhs, rhs_args, lhs_args) in

          fail_on (find_in_args x lhs_args != find_in_args y rhs_args);
          
          let same_vars, diff_eqns = List.fold_left (fun (same, diff) (s,t) -> 
            fail_on (not (T.is_var s && T.is_var t));
            if T.equal s t then (s :: same, diff)
            else (same, (s,t)::diff)
          ) ([],[]) (List.combine lhs_args rhs_args) in

          let same_set = T.Set.of_list same_vars in
          let diff_lhs_set, diff_rhs_set = 
            CCPair.map_same T.Set.of_list (CCList.split diff_eqns) in
          
          (* variables in each group are unique *)
          fail_on (List.length same_vars != T.Set.cardinal same_set);
          fail_on (List.length diff_eqns != T.Set.cardinal diff_lhs_set);
          fail_on (List.length diff_eqns != T.Set.cardinal diff_rhs_set);

          (* variable groups do not intersect *)
          fail_on (not (T.Set.is_empty (T.Set.inter diff_lhs_set diff_rhs_set)));
          fail_on (not (T.Set.is_empty (T.Set.inter diff_lhs_set same_set)));
          fail_on (not (T.Set.is_empty (T.Set.inter diff_rhs_set same_set)));

          let (sk_id, sk_ty),inv_sk = 
            Term.mk_fresh_skolem 
              (List.map T.as_var_exn same_vars) 
              (Type.arrow [T.ty lhs] (T.ty x)) in
          let inv_sk = T.app inv_sk [lhs] in
          let inv_lit = [Lit.mk_eq inv_sk x] in

           let proof = Proof.Step.inference ~rule:(Proof.Rule.mk "inj_rec") 
              [C.proof_parent c] in
          Ctx.declare sk_id sk_ty;
          let new_clause = 
            C.create ~trail:(C.trail c) ~penalty:(C.penalty c) inv_lit proof in
          Util.debugf ~section 1 "Injectivity recognized: %a |---| %a" 
            (fun k -> k C.pp c C.pp new_clause);
          [new_clause]
        | _ -> assert false; end
      | _ -> assert false;
    with Fail -> []

  (* Resolve negative literals that are implied by
     equational theory stored in _cc_simpl *)
  let cc_resolve_lits cl =
    let is_resolved l = match l with 
      | Lit.Equation(lhs, rhs, false) 
          when Term.is_ground lhs && Term.is_ground rhs &&
          Congruence.FO.is_eq !_cc_simpl lhs rhs ->
        None
      | _ -> Some l in
    let new_lits = CCList.filter_map is_resolved (CCArray.to_list (C.lits cl)) in
    if CCList.length new_lits != C.length cl then (
      let step = Proof.Step.simp ~rule:(Proof.Rule.mk "cc_resolve_neg") [C.proof_parent cl] in
      let res = C.create ~penalty:(C.penalty cl) ~trail:(C.trail cl) new_lits step in
      SimplM.return_new res
    ) else SimplM.return_same cl

  (* Remove the clause if it has  *)
  let is_cc_tautology cl =
    let is_cc_trivial = function
    | Lit.Equation(lhs, rhs, true) ->
      T.is_ground lhs && T.is_ground rhs &&
      Congruence.FO.is_eq !_cc_simpl lhs rhs
    | _ -> false in
    (* Because literals from the passive set are also added,
       then unit positive equation from the passive set can make
       itself tautology when it is chosen for processing...
       
       Two ways to avoid this:
        1. Do tautology checking on non-unit clauses
        2. Do the check on clauses with AVATAR asertions --
           the clauses added to CC are not asserted and thus
           cannot make themselves tautologies.
       *)
    (C.length cl > 1 || not (Trail.is_empty (C.trail cl))) &&
    Array.exists is_cc_trivial (C.lits cl)


  (** {2 Registration} *)

  (* print index into file *)
  let _print_idx ~f file idx =
    CCIO.with_out file
      (fun oc ->
         let out = Format.formatter_of_out_channel oc in
         Format.fprintf out "@[%a@]@." f idx;
         flush oc)

  let setup_dot_printers () =
    let pp_leaf _ _ = () in
    CCOpt.iter
      (fun file ->
         Signal.once Signals.on_dot_output
           (fun () -> _print_idx ~f:(TermIndex.to_dot pp_leaf) file !_idx_sup_into))
    @@ Env.flex_get k_dot_sup_into;
    CCOpt.iter
      (fun file ->
         Signal.once Signals.on_dot_output
           (fun () -> _print_idx ~f:(TermIndex.to_dot pp_leaf) file !_idx_sup_from))
    @@ Env.flex_get k_dot_sup_from;
    CCOpt.iter
      (fun file ->
         Signal.once Signals.on_dot_output
           (fun () -> _print_idx ~f:UnitIdx.to_dot file !_idx_simpl))
    @@ Env.flex_get k_dot_simpl;
    CCOpt.iter
      (fun file ->
         Signal.once Signals.on_dot_output
           (fun () -> _print_idx ~f:(TermIndex.to_dot pp_leaf) file !_idx_back_demod))
    @@ Env.flex_get k_dot_demod_into;
    ()

  let register () =

    let open SimplM.Infix in
    let rw_simplify c =
      canonize_variables c
      >>= demodulate
      >>= basic_simplify
      >>= positive_simplify_reflect
      >>= negative_simplify_reflect
    and active_simplify c =
      condensation c
      >>= contextual_literal_cutting
    and backward_simplify c =
      let set = C.ClauseSet.empty in
      backward_demodulate set c
    and redundant = subsumed_by_active_set
    and backward_redundant = subsumed_in_active_set
    and is_trivial = is_tautology in

    if Env.flex_get k_local_rw != `Off then (
      Env.add_basic_simplify local_rewrite
    );

    if Env.flex_get k_cc_simplify then (
      let insert_into_cc c =
        (match C.lits c with 
        | [| Lit.Equation(lhs, rhs, true) |] ->
          if Term.is_ground lhs && Term.is_ground rhs && Trail.is_empty (C.trail c) then (
            _cc_simpl := Congruence.FO.mk_eq !_cc_simpl lhs rhs
          )
        | _ -> ());
        Signal.ContinueListening 
      in

      Signal.on Env.ProofState.PassiveSet.on_add_clause insert_into_cc;

      Env.add_basic_simplify cc_resolve_lits;
      Env.add_is_trivial is_cc_tautology;
    );

    Env.flex_add k_stmq (StmQ.default ());

    if Env.flex_get Combinators.k_enable_combinators
       && Env.flex_get k_subvarsup then (
      Env.add_binary_inf "subvarsup" infer_subvarsup_active;
      Env.add_binary_inf "subvarsup" infer_subvarsup_passive;
    );

    if Env.flex_get k_arg_cong then ( 
      Env.add_unary_inf "ho_complete_eq" complete_eq_args
    );
    if Env.flex_get k_switch_stream_extraction then (
      Env.add_generate ~priority:0 "stream_queue_extraction" extract_from_stream_queue_fix_stm)
    else (
      Env.add_generate ~priority:0 "stream_queue_extraction" extract_from_stream_queue);

    if Env.flex_get k_recognize_injectivity then (
      Env.add_unary_inf "recognize injectivity" recognize_injectivity;
    );

    if Env.flex_get k_trigger_bool_ind > 0 then (
      Env.add_unary_inf "trigger bool ind" trigger_induction
    );

    if Env.flex_get k_ext_rules_kind == `ExtFamily ||
       Env.flex_get k_ext_rules_kind == `Both then (
      Env.add_binary_inf "ext_dec_act" ext_sup_act;
      Env.add_binary_inf "ext_dec_pas" ext_sup_pas;
      Env.add_unary_inf "ext_eqres_dec" ext_eqres;
    );

    if Env.flex_get k_ext_rules_kind = `ExtInst ||
       Env.flex_get k_ext_rules_kind = `Both then (
      Env.add_binary_inf "ext_dec_act" ext_inst_sup_act;
      Env.add_binary_inf "ext_dec_pas" ext_inst_sup_pas;
      Env.add_unary_inf "ext_eqres_dec" ext_inst_eqres;
    );

    if Env.flex_get k_ext_rules_kind != `Off then (
      Env.add_unary_inf "ext_eqfact_both" ext_inst_or_family_eqfact_aux;
    );

    if Env.flex_get k_complete_ho_unification
    then (
      if (Env.flex_get k_max_infs) = -1 then (
        Env.add_binary_inf "superposition_passive" infer_passive_complete_ho;
        Env.add_binary_inf "superposition_active" infer_active_complete_ho;
        Env.add_unary_inf "equality_factoring" infer_equality_factoring_complete_ho;
        Env.add_unary_inf "equality_resolution" infer_equality_resolution_complete_ho;
      )
      else (
        assert((Env.flex_get k_max_infs) > 0);
        Env.add_binary_inf "superposition_passive" (infer_passive_pragmatic_ho (Env.flex_get k_max_infs));
        Env.add_binary_inf "superposition_active" (infer_active_pragmatic_ho (Env.flex_get k_max_infs));
        Env.add_unary_inf "equality_factoring" (infer_equality_factoring_pragmatic_ho (Env.flex_get k_max_infs));
        Env.add_unary_inf "equality_resolution" (infer_equality_resolution_pragmatic_ho (Env.flex_get k_max_infs));
      );

      if Env.flex_get k_fluidsup then (
        Env.add_binary_inf "fluidsup_passive" infer_fluidsup_passive;
        Env.add_binary_inf "fluidsup_active" infer_fluidsup_active;
      );
      if Env.flex_get k_dupsup then (
        Env.add_binary_inf "dupsup_passive(into)" infer_dupsup_passive;
        Env.add_binary_inf "dupsup_active(from)" infer_dupsup_active;
      );
      if Env.flex_get k_lambdasup != -1 then (
        Env.add_binary_inf "lambdasup_active(from)" infer_lambdasup_from;
        Env.add_binary_inf "lambdasup_passive(into)" infer_lambdasup_into;
      );
      if Env.flex_get k_trigger_bool_inst > 0 then (
        Signal.on Env.on_pred_var_elimination handle_new_pred_var_clause;
        Signal.on Env.on_pred_skolem_introduction handle_new_skolem_sym;
      );
    )
    else (
      Env.add_binary_inf "superposition_passive" infer_passive;
      Env.add_binary_inf "superposition_active" infer_active;
      Env.add_unary_inf "equality_factoring" infer_equality_factoring;
      Env.add_unary_inf "equality_resolution" infer_equality_resolution;
    );
    if not (Env.flex_get k_dont_simplify) then (
      Env.add_rw_simplify rw_simplify;
      Env.add_basic_simplify canonize_variables;
      Env.add_basic_simplify basic_simplify;
      Env.add_active_simplify active_simplify;
      Env.add_backward_simplify backward_simplify
    );
    Env.add_redundant redundant;
    Env.add_backward_redundant backward_redundant;
    if Env.flex_get k_use_semantic_tauto
    then Env.add_is_trivial is_semantic_tautology;
    Env.add_is_trivial is_trivial;
    Env.add_lit_rule "distinct_symbol" handle_distinct_constants;
    if Env.flex_get k_immediate_simplification then (
      Env.add_immediate_simpl_rule immediate_subsume
    );
    setup_dot_printers ();
    ()
end

let _use_semantic_tauto = ref true
let _use_simultaneous_sup = ref true
let _dot_sup_into = ref None
let _dot_sup_from = ref None
let _dot_simpl = ref None
let _dont_simplify = ref false
let _sup_at_vars = ref false
let _sup_at_var_headed = ref true
let _sup_from_var_headed = ref true
let _sup_in_var_args = ref true
let _sup_under_lambdas = ref true
let _lambda_demod = ref false
let _demod_in_var_args = ref true
let _dot_demod_into = ref None
let _complete_ho_unification = ref false
let _switch_stream_extraction = ref false
let _fluidsup_penalty = ref 9
let _dupsup_penalty = ref 2
let _fluidsup = ref true
let _subvarsup = ref true
let _dupsup = ref true
let _trigger_bool_inst = ref (-1)
let _trigger_bool_ind = ref (-1)
let _recognize_injectivity = ref false
let _restrict_fluidsup = ref false
let _check_sup_at_var_cond = ref true
let _restrict_hidden_sup_at_vars = ref false
let _cc_simplify = ref false
let _local_rw = ref `Off

let _lambdasup = ref (-1)
let _max_infs = ref (-1)
let ext_rules_max_depth = ref (-1)
let ext_rules_kind = ref (`Off)

let _ext_dec_lits = ref `OnlyMax
let _unif_alg = ref `NewJPFull
let _unif_level = ref `Full
let _ground_subs_check = ref 0
let _solid_subsumption = ref false

let _skip_multiplier = ref 2.0
let _imit_first = ref false
let _max_depth = ref 2
let _max_rigid_imitations = ref 2
let _max_app_projections = ref 1
let _max_elims = ref 0
let _max_identifications = ref 0
let _pattern_decider = ref true
let _fixpoint_decider = ref false
let _solid_decider = ref false
let _solidification_limit = ref 3
let _max_unifs_solid_ff = ref 60
let _use_weight_for_solid_subsumption = ref false
let _sort_constraints = ref false
let _ho_disagremeents = ref `SomeHo
let _bool_demod = ref false
let _immediate_simplification = ref false
let _arg_cong = ref true
let _try_lfho_unif = ref true
let _bool_eq_fact = ref true

let _guard = ref 20
let _ratio = ref 70
let _clause_num = ref 7

let key = Flex_state.create_key ()

let unif_params_to_def () =
  _max_depth := 2;
  _max_app_projections := 1;
  _max_rigid_imitations := 2;
  _max_identifications := 0;
  _max_elims           := 0;
  _max_infs := -1

let register ~sup =
  let module Sup = (val sup : S) in
  let module E = Sup.Env in

  E.update_flex_state (Flex_state.add key sup);
  E.flex_add k_trigger_bool_inst !_trigger_bool_inst;
  E.flex_add k_trigger_bool_ind !_trigger_bool_ind;
  E.flex_add k_sup_at_vars !_sup_at_vars;
  E.flex_add k_sup_in_var_args !_sup_in_var_args;
  E.flex_add k_sup_under_lambdas !_sup_under_lambdas;
  E.flex_add k_sup_at_var_headed !_sup_at_var_headed;
  E.flex_add k_sup_from_var_headed !_sup_from_var_headed;
  E.flex_add k_fluidsup !_fluidsup;
  E.flex_add k_subvarsup !_subvarsup;
  E.flex_add k_dupsup !_dupsup;
  E.flex_add k_lambdasup !_lambdasup;
  E.flex_add k_restrict_fluidsup !_restrict_fluidsup;
  E.flex_add k_check_sup_at_var_cond !_check_sup_at_var_cond;
  E.flex_add k_restrict_hidden_sup_at_vars !_restrict_hidden_sup_at_vars;
  E.flex_add k_demod_in_var_args !_demod_in_var_args;
  E.flex_add k_lambda_demod !_lambda_demod;
  E.flex_add k_ext_dec_lits !_ext_dec_lits;
  E.flex_add k_ext_rules_max_depth !ext_rules_max_depth;
  E.flex_add k_ext_rules_kind !ext_rules_kind;

  E.flex_add k_use_simultaneous_sup !_use_simultaneous_sup;  
  E.flex_add k_fluidsup_penalty !_fluidsup_penalty;
  E.flex_add k_dupsup_penalty !_dupsup_penalty;
  E.flex_add k_ground_subs_check !_ground_subs_check;
  E.flex_add k_solid_subsumption !_solid_subsumption;
  E.flex_add k_dot_sup_into !_dot_sup_into;
  E.flex_add k_dot_sup_from !_dot_sup_from;
  E.flex_add k_dot_simpl !_dot_simpl;
  E.flex_add k_dot_demod_into !_dot_demod_into;
  E.flex_add k_recognize_injectivity !_recognize_injectivity;
  E.flex_add k_complete_ho_unification !_complete_ho_unification;
  E.flex_add k_max_infs !_max_infs;
  E.flex_add k_switch_stream_extraction !_switch_stream_extraction;
  E.flex_add k_dont_simplify !_dont_simplify;
  E.flex_add k_use_semantic_tauto !_use_semantic_tauto;
  E.flex_add k_ho_disagremeents !_ho_disagremeents;
  E.flex_add k_bool_demod !_bool_demod;
  E.flex_add k_immediate_simplification !_immediate_simplification;
  E.flex_add k_arg_cong !_arg_cong;
  E.flex_add k_bool_eq_fact !_bool_eq_fact;


  E.flex_add PragUnifParams.k_max_inferences !_max_infs;
  E.flex_add PragUnifParams.k_skip_multiplier !_skip_multiplier;
  E.flex_add PragUnifParams.k_imit_first !_imit_first;
  E.flex_add PragUnifParams.k_max_depth !_max_depth;
  E.flex_add PragUnifParams.k_max_rigid_imitations !_max_rigid_imitations;
  E.flex_add PragUnifParams.k_max_app_projections !_max_app_projections;
  E.flex_add PragUnifParams.k_max_elims !_max_elims;
  E.flex_add PragUnifParams.k_max_identifications !_max_identifications;
  E.flex_add PragUnifParams.k_pattern_decider !_pattern_decider;
  E.flex_add PragUnifParams.k_fixpoint_decider !_fixpoint_decider;
  E.flex_add PragUnifParams.k_solid_decider !_solid_decider;
  E.flex_add PragUnifParams.k_solidification_limit !_solidification_limit;
  E.flex_add PragUnifParams.k_max_unifs_solid_ff !_max_unifs_solid_ff;
  E.flex_add PragUnifParams.k_use_weight_for_solid_subsumption !_use_weight_for_solid_subsumption;
  E.flex_add PragUnifParams.k_sort_constraints !_sort_constraints;
  E.flex_add PragUnifParams.k_try_lfho !_try_lfho_unif;

  E.flex_add StreamQueue.k_guard !_guard;
  E.flex_add StreamQueue.k_ratio !_ratio;
  E.flex_add StreamQueue.k_clause_num !_clause_num;

  E.flex_add k_cc_simplify !_cc_simplify;
  E.flex_add k_local_rw !_local_rw;

  let module JPF = JPFull.Make(struct let st = E.flex_state () end) in
  let module JPP = PUnif.Make(struct let st = E.flex_state () end) in
  begin match !_unif_alg with 
    | `OldJP -> E.flex_add k_unif_alg JP_unif.unify_scoped
    | `NewJPFull -> E.flex_add k_unif_alg JPF.unify_scoped
    | `NewJPPragmatic -> E.flex_add k_unif_alg JPP.unify_scoped end

(* TODO: move DOT index printing into the extension *)

let extension =
  let action env =
    let module E = (val env : Env.S) in
    let module Sup = Make(E) in
    register ~sup:(module Sup : S);
    Sup.register();
  in
  { Extensions.default with Extensions.
                         name="superposition";
                         env_actions = [action];
  }

let () =
  Params.add_opts
    [
      "--arg-cong", Arg.Bool (fun v -> _arg_cong := v), " enable/disable ArgCong"; 
      "--semantic-tauto", Arg.Bool (fun v -> _use_semantic_tauto := v), " enable/disable semantic tautology check";
      "--dot-sup-into", Arg.String (fun s -> _dot_sup_into := Some s), " print superposition-into index into file";
      "--dot-sup-from", Arg.String (fun s -> _dot_sup_from := Some s), " print superposition-from index into file";
      "--dot-demod", Arg.String (fun s -> _dot_simpl := Some s), " print forward rewriting index into file";
      "--dot-demod-into", Arg.String (fun s -> _dot_demod_into := Some s), " print backward rewriting index into file"; 
      "--simultaneous-sup", Arg.Bool (fun b -> _use_simultaneous_sup := b), " enable/disable simultaneous superposition";
      "--dont-simplify", Arg.Set _dont_simplify, " disable simplification rules";
      "--sup-at-vars", Arg.Bool (fun v -> _sup_at_vars := v), " enable/disable superposition at variables under certain ordering conditions";
      "--sup-at-var-headed", Arg.Bool (fun b -> _sup_at_var_headed := b), " enable/disable superposition at variable headed terms";
      "--sup-from-var-headed", Arg.Bool (fun b -> _sup_from_var_headed := b), " enable/disable superposition from variable headed terms";
      "--sup-in-var-args", Arg.Bool (fun b -> _sup_in_var_args := b), " enable/disable superposition in arguments of applied variables";
      "--sup-under-lambdas", Arg.Bool (fun b -> _sup_under_lambdas := b), " enable/disable superposition in bodies of lambda-expressions";
      "--lambda-demod", Arg.Bool (fun b -> _lambda_demod := b), " enable/disable demodulation in bodies of lambda-expressions";
      "--demod-in-var-args", Arg.Bool (fun b -> _demod_in_var_args := b), " enable demodulation in arguments of variables";
      "--complete-ho-unif", Arg.Bool (fun b -> _complete_ho_unification := b), " enable complete higher-order unification algorithm (Jensen-Pietrzykowski)";
      "--switch-stream-extract", Arg.Bool (fun b -> _switch_stream_extraction := b), " in ho mode, switches heuristic of clause extraction from the stream queue";
      "--ext-rules-max-depth", Arg.Set_int ext_rules_max_depth, 
        " Sets the maximal proof depth of the clause eligible for Ext-* or ExtInst inferences";
      "--ext-rules", Arg.Symbol (["off"; "ext-inst"; "ext-family"; "both"], (
        function 
        | "off" -> ext_rules_kind := `Off; ext_rules_max_depth:=-1;
        | "ext-inst" -> ext_rules_kind := `ExtInst;
        | "ext-family" -> ext_rules_kind := `ExtFamily;
        | "both" -> ext_rules_kind := `Both
        |  _ -> assert false)),
        " Chooses the kind of extensionality rules to use";
      "--ext-decompose-lits", Arg.Symbol (["all";"max"], (fun str -> 
          _ext_dec_lits := if String.equal str "all" then `All else `OnlyMax))
      , " Sets the maximal number of literals clause can have for ExtDec inference.";
      "--ext-decompose-ho-disagreements", Arg.Symbol (["all-ho";"some-ho"], (fun str -> 
          _ho_disagremeents := if String.equal str "all-ho" then `AllHo else `SomeHo))
      , " Perform Ext-Sup, Ext-EqFact, or Ext-EqRes rules only when all disagreements are HO" ^
        " or when there exists a HO disagremeent";
      "--fluidsup-penalty", Arg.Int (fun p -> _fluidsup_penalty := p), " penalty for FluidSup inferences";
      "--dupsup-penalty", Arg.Int (fun p -> _dupsup_penalty := p), " penalty for DupSup inferences";
      "--bool-eq-fact", Arg.Bool ((:=) _bool_eq_fact), " turn bool eq-fact on or off";
      "--fluidsup", Arg.Bool (fun b -> _fluidsup :=b), " enable/disable FluidSup inferences (only effective when complete higher-order unification is enabled)";
      "--subvarsup", Arg.Bool ((:=) _subvarsup), " enable/disable SubVarSup inferences";
      "--lambdasup", Arg.Int (fun l -> 
          if l < 0 then 
            raise (Util.Error ("argument parsing", 
                               "lambdaSup argument should be non-negative"));
          _lambdasup := l), 
      " enable LambdaSup -- argument is the maximum number of skolems introduced in an inference";
      "--dupsup", Arg.Bool (fun v -> _dupsup := v), " enable/disable DupSup inferences";
      "--ground-before-subs", Arg.Set_int _ground_subs_check, " set the level of grounding before substitution. 0 - no grounding. 1 - only active. 2 - both.";
      "--solid-subsumption", Arg.Bool (fun v -> _solid_subsumption := v), " set solid subsumption on or off";
      "--recognize-injectivity", Arg.Bool (fun v -> _recognize_injectivity := v), " recognize injectivity axiom and axiomatize corresponding inverse";
      "--restrict-fluidsup" , Arg.Bool (fun v -> _restrict_fluidsup := v), " enable/disable restriction of fluidSup to up to two literal or inital clauses";
      "--use-weight-for-solid-subsumption", Arg.Bool (fun v -> _use_weight_for_solid_subsumption := v), 
      " enable/disable superposition to and from pure variable equations";
      "--trigger-bool-inst", Arg.Set_int _trigger_bool_inst
      , " instantiate predicate variables with boolean terms already in the proof state. Argument is the maximal proof depth of predicate variable";
       "--trigger-bool-ind", Arg.Set_int _trigger_bool_ind
      , " abstract away constants from the goal and use them to trigger axioms of induction";
      "--ho-unif-level",
      Arg.Symbol (["full-framework";"full"; "pragmatic-framework";], (fun str ->
          _unif_alg := if (String.equal "full" str) then `OldJP
            else if (String.equal "full-framework" str) then (
              unif_params_to_def ();
              `NewJPFull)
            else if (String.equal "pragmatic-framework" str) then `NewJPPragmatic
            else invalid_arg "unknown argument")), "set the level of HO unification";
      "--ho-imitation-first",Arg.Bool (fun v -> _imit_first:=v), " Use imitation rule before projection rule";
      "--ho-unif-max-depth", Arg.Set_int _max_depth, " set pragmatic unification max depth";
      "--ho-max-app-projections", Arg.Set_int _max_app_projections, " set maximal number of functional type projections";
      "--ho-max-elims", Arg.Set_int _max_elims, " set maximal number of eliminations";
      "--ho-max-identifications", Arg.Set_int _max_identifications, " set maximal number of flex-flex identifications";
      "--ho-skip-multiplier", Arg.Set_float _skip_multiplier, " set maximal number of flex-flex identifications";
      "--ho-max-rigid-imitations", Arg.Set_int _max_rigid_imitations, " set maximal number of rigid imitations";
      "--ho-max-solidification", Arg.Set_int _solidification_limit, " set maximal number of rigid imitations";
      "--ho-max-unifs-solid-flex-flex", Arg.Set_int _max_unifs_solid_ff, " set maximal number of found unifiers for solid flex-flex pairs. -1 stands for finding the MGU";
      "--ho-pattern-decider", Arg.Bool (fun b -> _pattern_decider := b), "turn pattern decider on or off";
      "--ho-solid-decider", Arg.Bool (fun b -> _solid_decider := b), "turn solid decider on or off";
      "--ho-fixpoint-decider", Arg.Bool (fun b -> _fixpoint_decider := b), "turn fixpoint decider on or off";
      "--max-inferences", Arg.Int (fun p -> _max_infs := p), " set maximal number of inferences";
      "--stream-queue-guard", Arg.Set_int _guard, "set value of guard for streamQueue";
      "--stream-queue-ratio", Arg.Set_int _ratio, "set value of ratio for streamQueue";
      "--bool-demod", Arg.Bool ((:=) _bool_demod), " turn BoolDemod on/off";
      "--cc-simplify", Arg.Bool ((:=) _cc_simplify), " use cong-closure of all positive ground unit eqs to simplify the clauses";
      "--local-rw", Arg.Symbol (["any-context"; "green-context"; "off"], (fun opt -> 
        match opt with
        | "any-context" -> _local_rw := `AnyContext
        | "green-context" -> _local_rw := `GreenContext
        | "off" -> _local_rw := `Off
        | _ -> invalid_arg "possible arugments are: [any-context; green-context; off]"
      )), " turn local rewriting rule on/off";
      "--immediate-simplification", Arg.Bool ((:=) _immediate_simplification), " turn immediate simplification on/off";
      "--try-lfho-unif", Arg.Bool ((:=) _try_lfho_unif), " if term is of the right shape, try LFHO unification before HO unification";
      "--stream-clause-num", Arg.Set_int _clause_num, "how many clauses to take from streamQueue; by default as many as there are streams";
      "--ho-sort-constraints", Arg.Bool (fun b -> _sort_constraints := b), "sort constraints in unification algorithm by weight";
      "--check-sup-at-var-cond", Arg.Bool (fun b -> _check_sup_at_var_cond := b), " enable/disable superposition at variable monotonicity check";
      "--restrict-hidden-sup-at-vars", Arg.Bool (fun b -> _restrict_hidden_sup_at_vars :=	b), " enable/disable hidden superposition at variables only under certain ordering conditions"
    ];

  Params.add_to_mode "ho-complete-basic" (fun () ->
      _use_simultaneous_sup := false;
      (* _local_rw := `GreenContext; *)
      _sup_at_vars := true;
      _sup_in_var_args := false;
      _sup_under_lambdas := false;
      _lambda_demod := false;
      _demod_in_var_args := false;
      _complete_ho_unification := true;
      _sup_at_var_headed := false;
      _unif_alg := `NewJPFull;
      _lambdasup := -1;
      _dupsup := false;
    );
  Params.add_to_mode "ho-pragmatic" (fun () ->
      _use_simultaneous_sup := false;
      _sup_at_vars := true;
      _sup_in_var_args := false;
      _sup_under_lambdas := false;
      _lambda_demod := false;
      (* _local_rw := `AnyContext; *)
      _demod_in_var_args := false;
      _complete_ho_unification := true;
      _unif_alg := `NewJPPragmatic;
      _sup_at_var_headed := true;
      _lambdasup := -1;
      _dupsup := false;
      _max_infs := 4;
      _max_depth := 2;
      _max_app_projections := 0;
      _max_rigid_imitations := 2;
      _max_identifications := 1;
      _max_elims := 0;
      _fluidsup := false;
    );
  Params.add_to_mode "ho-competitive" (fun () ->
      _use_simultaneous_sup := false;
      _sup_at_vars := true;
      _sup_in_var_args := false;
      _sup_under_lambdas := false;
      _lambda_demod := false;
      _demod_in_var_args := false;
      _complete_ho_unification := true;
      _unif_alg := `NewJPFull;
      (* _local_rw := `AnyContext; *)
      _sup_at_var_headed := true;
      _lambdasup := -1;
      _dupsup := false;
      _fluidsup := false;
    );
  Params.add_to_mode "fo-complete-basic" (fun () ->
      _use_simultaneous_sup := false;
      _arg_cong := false;
      (* _local_rw := `GreenContext *)
    );
  Params.add_to_modes 
    [ "lambda-free-intensional"
    ; "lambda-free-extensional"
    ; "ho-comb-complete"
    ; "lambda-free-purify-intensional"
    ; "lambda-free-purify-extensional"] (fun () ->
    _use_simultaneous_sup := false;
    _sup_in_var_args := true;
    _demod_in_var_args := true;
    (* _local_rw := `GreenContext; *)
    _dupsup := false;
    _complete_ho_unification := false;
    _lambdasup := -1;
    _fluidsup := false;
  );
  Params.add_to_modes 
    [ "lambda-free-extensional"
    ; "ho-comb-complete"
    ; "lambda-free-purify-extensional"] (fun () ->
    _restrict_hidden_sup_at_vars := true;
  );
  Params.add_to_modes 
    [ "lambda-free-intensional"
    ; "lambda-free-purify-intensional"] (fun () ->
    _restrict_hidden_sup_at_vars := false;
  );
  Params.add_to_modes
    [ "lambda-free-intensional"
    ; "lambda-free-extensional"
    ; "ho-comb-complete"] (fun () ->
      _sup_at_vars := true;
  );
  Params.add_to_modes
    [ "lambda-free-purify-intensional"
    ; "lambda-free-purify-extensional"] (fun () ->
      _sup_at_vars := false;
      _check_sup_at_var_cond := false;
  );
OCaml

Innovation. Community. Security.