Source file compiler.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
open Elpi_util
open Elpi_parser
open Elpi_runtime
open Util
let ErrorFun { anomaly } = error_fun ~component:"Compiler"
module F = Ast.Func
module R = Runtime_trace_off
module D = Data
let elpi_language = Compiler_data.elpi_language
type flags = {
defined_variables : StrSet.t;
print_units : bool;
time_typechecking : bool;
skip_det_checking: bool;
max_errors: int;
builtin_stubs: bool;
}
[@@deriving show]
let default_flags = {
defined_variables = StrSet.empty;
print_units = false;
time_typechecking = false;
skip_det_checking = false;
max_errors = 0;
builtin_stubs = false;
}
let time_this r f =
let t0 = Unix.gettimeofday () in
try
let rc = f () in
let t1 = Unix.gettimeofday () in
r := !r +. (t1 -. t0);
rc
with e ->
let t1 = Unix.gettimeofday () in
r := !r +. (t1 -. t0);
raise e
let parser : (module Parse.Parser) option D.State.component = D.State.declare
~descriptor:D.elpi_state_descriptor
~name:"elpi:parser"
~pp:(fun fmt _ -> Format.fprintf fmt "<parser>")
~clause_compilation_is_over:(fun x -> x)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun _ -> None)
~init:(fun () -> None)
()
let : StrSet.t D.State.component = D.State.declare
~descriptor:D.elpi_state_descriptor
~name:"elpi:header_units"
~pp:(fun fmt _ -> Format.fprintf fmt "<header units>")
~clause_compilation_is_over:(fun x -> x)
~compilation_is_over:(fun _ -> None)
~execution_is_over:(fun _ -> None)
~init:(fun () -> StrSet.empty)
()
let filter1_if { defined_variables } proj c =
match proj c with
| None -> true
| Some e when StrSet.mem e defined_variables -> true
| Some _ -> false
module SymbolMap : sig
type table [@@deriving show]
val pp_table : Format.formatter -> table -> unit
val same_constants : table -> table -> bool
val empty : unit -> table
val allocate_global_symbol : D.State.t -> table -> D.Symbol.t -> table * (constant * D.term)
val allocate_bound_symbol : D.State.t -> table -> constant -> table * D.term
val get_global_symbol : table -> D.Symbol.t -> constant option
val get_canonical : D.State.t -> table -> constant -> D.term
val global_name : D.State.t -> table -> constant -> F.t
val compile : table -> D.symbol_table
val compile_s2c : table -> (constant * D.term) D.Symbol.RawMap.t
end = struct
open Compiler_data
type table = {
ast2ct : (constant * D.term) D.Symbol.RawMap.t;
c2t : D.term Constants.Map.t;
c2s : Symbol.t Constants.Map.t;
last_constant : int;
}
[@@deriving show]
let same_constants m1 m2 = m1.last_constant = m2.last_constant
let global_symbol (x:D.Symbol.t) =
match D.Symbol.get_provenance x with
| Builtin _ | Core -> D.Symbol.RawMap.find_opt x D.Global_symbols.table.s2ct
| File _ -> None
let global_constant c =
match Util.Constants.Map.find_opt c D.Global_symbols.table.c2s with
| Some s -> Option.map (fun (_, t) -> s, t) (D.Symbol.RawMap.find_opt s D.Global_symbols.table.s2ct)
| None -> None
let compile { last_constant; c2t; c2s; _ } =
{ D.c2s; c2t = Hashtbl.create (Util.Constants.Map.cardinal c2t);
frozen_constants = last_constant; first_frozen = last_constant + 1 }
let compile_s2c { ast2ct } = ast2ct
let allocate_global_symbol_aux (x:D.Symbol.t) ({ c2t; c2s; ast2ct; last_constant } as table) =
match D.Symbol.RawMap.find_opt x ast2ct with
| Some p -> table, p
| None ->
match global_symbol x with
| Some p -> table, p
| None ->
let last_constant = last_constant + 1 in
let n = last_constant in
D.Global_symbols.check_no_overlap_prog_csts_w_glob_csts n;
let xx = D.Term.Const n in
let p = n,xx in
let c2t = Util.Constants.Map.add n xx c2t in
let ast2ct = D.Symbol.RawMap.add x p ast2ct in
let c2s = Util.Constants.Map.add n x c2s in
{ c2t; c2s; ast2ct; last_constant }, p
let get_global_symbol { ast2ct } s =
match D.Symbol.RawMap.find_opt s ast2ct with
| Some (c, _) -> Some c
| None -> Option.map fst (global_symbol s)
let empty () = {
ast2ct = D.Symbol.RawMap.empty;
last_constant = D.Global_symbols.bottom - 1;
c2s = Util.Constants.Map.empty;
c2t = Util.Constants.Map.empty;
}
let allocate_global_symbol state table (x:D.Symbol.t) =
if not (D.State.get D.while_compiling state) then
anomaly (Format.asprintf "Cannot allocate a symbol for %a. Global symbols can only be allocated during compilation" D.Symbol.pp x);
allocate_global_symbol_aux x table
let allocate_bound_symbol_aux n ({ c2t; ast2ct } as table) =
try table, Util.Constants.Map.find n c2t
with Not_found ->
let xx = D.Term.Const n in
let c2t = Util.Constants.Map.add n xx c2t in
{ table with c2t; ast2ct }, xx
let allocate_bound_symbol state table n =
if n < 0 then
anomaly "bound variables are positive";
allocate_bound_symbol_aux n table
;;
let get_canonical state table c =
if not (D.State.get D.while_compiling state) then
D.Const c
else
match Util.Constants.Map.find_opt c table.c2t with
| Some t -> t
| None ->
match global_constant c with
| Some (_, t) -> t
| None -> anomaly ("unknown symbol " ^ string_of_int c)
let global_name state table c =
if not (D.State.get D.while_compiling state) then
anomaly "get_canonical can only be used during compilation";
match Util.Constants.Map.find_opt c table.c2s with
| Some s -> Symbol.get_func s
| None ->
match global_constant c with
| Some (s, _) -> Symbol.get_func s
| None -> anomaly ("unknown symbol " ^ string_of_int c)
end
module Builtins : sig
type t
val pp : Format.formatter -> t -> unit
val register : t -> D.BuiltInPredicate.t -> constant -> t
val is_declared : t -> constant -> bool
val fold : (constant -> Data.BuiltInPredicate.t -> 'a -> 'a) -> t -> 'a -> 'a
val empty : t
end = struct
type t = Data.BuiltInPredicate.t Constants.Map.t
[@@deriving show]
let empty = Constants.Map.empty
let fold = Constants.Map.fold
let register t (D.BuiltInPredicate.(Pred(s,_,_) | ContextualPred(s,_,_,_)) as b) idx =
if s = "" then anomaly "Built-in predicate name must be non empty";
if Constants.Map.mem idx t then
anomaly ("Duplicate built-in predicate " ^ s);
Constants.Map.add idx b t
;;
let is_declared t x = Constants.Map.mem x t
end
open Data
module C = Constants
open Compiler_data
module UF = Symbol.UF
type macro_declaration = (ScopedTerm.t * Loc.t) F.Map.t
[@@ deriving show, ord]
module Scoped = struct
type program = {
pbody : pbody;
toplevel_macros : macro_declaration;
macro_uses : macro_use list;
}
and macro_use = { name_loc : Loc.t; expansion_loc : Loc.t; macro : F.t; macro_loc : Loc.t; args : ScopedTerm.t list }
and pbody = {
kinds : Arity.t F.Map.t;
types : ScopeTypeExpressionUniqueList.t F.Map.t;
type_abbrevs : (F.t * ScopedTypeExpression.t) list;
body : block list;
pred_symbols : F.Set.t;
ty_symbols : F.Set.t;
}
and block =
| Clauses of (ScopedTerm.t,Ast.Structured.attribute,bool,bool) Ast.Clause.t list
| Namespace of string * pbody
| Shorten of F.t Ast.Structured.shorthand list * pbody
| Constraints of (F.t,ScopedTerm.t) Ast.Structured.block_constraint * pbody
| Block of pbody
[@@deriving show]
end
type declared_builtins = string
[@@deriving show]
let ErrorFun { error = builtins_error } = error_fun ~component:"Builtins"
let ErrorFun { error = compiler_error } = error_fun ~component:"Compiler"
let declared_builtins = ref StrMap.empty
let build_predmap l =
let m = ref StrMap.empty in
l |> List.iter (function
| BuiltInPredicate.MLCode ((Pred(name,_,_) | ContextualPred(name,_,_,_)) as p, _) ->
if StrMap.mem name !m then
builtins_error ("Multiple declarations for builtin predicate " ^ name);
m := StrMap.add name p !m
| _ -> ()
);
!m
let declare_builtins ~file_name l =
if Util.StrMap.mem file_name !declared_builtins then
builtins_error ("Canno declare builtins " ^ file_name ^ " twice");
declared_builtins := Util.StrMap.add file_name (build_predmap l,l) !declared_builtins;
file_name
let is_declared_builtins ~file_name = Util.StrMap.mem file_name !declared_builtins
let declared_builtins_of_file ~file_name =
if Util.StrMap.mem file_name !declared_builtins then file_name
else builtins_error ("Builtins for file " ^ file_name ^ " were not declared")
let declared_builtins ~file_name =
try Util.StrMap.find file_name !declared_builtins
with Not_found -> builtins_error ("Builtins for file " ^ file_name ^ " were not declared")
let file_of_declared_builtins x = x
let document_fmt fmt file_name =
let _, l = declared_builtins ~file_name in
Data.BuiltInPredicate.document fmt l
let document_file ?header:_ ~file:name file_name =
let _, l = declared_builtins ~file_name in
let oc = open_out name in
let fmt = Format.formatter_of_out_channel oc in
Data.BuiltInPredicate.document fmt l;
Format.pp_print_flush fmt ();
close_out oc
let bind_mlconstants ?(stubs = false) ~file_name decls ({ Ast.ast } as p : Ast.Program.t) =
let name_variant c =
match Util.Constants.Map.find_opt c D.Global_symbols.table.c2s with
| Some s ->
(match D.Symbol.get_provenance s with
| Builtin { variant } -> D.Symbol.get_str s, variant
| _ -> builtins_error (Printf.sprintf "MLConstants of %s: %s is a symbol of the language" file_name (D.Symbol.get_str s)))
| None -> builtins_error (Printf.sprintf "MLConstants of %s: %d is not a constant of Constants.declare_global_symbol" file_name c) in
let compare_nv (n1, v1) (n2, v2) = match String.compare n1 n2 with 0 -> String.compare v1 v2 | c -> c in
let constants =
List.sort_uniq compare_nv (
List.concat_map (function
| BuiltInPredicate.MLData { Conversion.constants } -> List.map name_variant constants
| BuiltInPredicate.MLDataC { ContextualConversion.constants } -> List.map name_variant constants
| BuiltInPredicate.MLConstants l -> List.map name_variant l
| BuiltInPredicate.MLCalc ops -> List.map (fun (c, _) -> name_variant c) ops
| _ -> []) decls) in
let mlcode = decls |> List.filter_map (function
| BuiltInPredicate.MLCode ((Pred(name,_,_) | ContextualPred(name,_,_,_)), _) -> Some name
| _ -> None) in
let bound = ref [] in
let bind_once ~loc name v =
if List.exists (fun (k, w) -> String.equal k name && String.equal w v) !bound then
builtins_error ~loc (Printf.sprintf "%s%s, an OCaml symbol of %s, is declared twice by its text" name (D.Global_symbols.show_variant_annotation v) file_name);
bound := (name, v) :: !bound in
let variants name = List.filter_map (fun (k, v) -> if String.equal k name then Some v else None) constants in
let bind ~ns ~pred ({ Ast.Type.name; attributes; loc } as t) =
let name = String.concat "." (List.rev (F.show name :: ns)) in
let annotation = List.find_map (function Ast.External o -> Some o | _ -> None) attributes in
match annotation, variants name with
| Some (Some "core"), _ -> t
| Some None, _ when pred ->
if not stubs && not (List.exists (String.equal name) mlcode) then
builtins_error ~loc (Printf.sprintf "%s is declared builtin but no MLCode of %s implements it%s" name file_name
(match variants name with [] -> "" | _ -> ": it is in the MLConstants, drop builtin"));
t
| Some (Some s), vs ->
if List.exists (String.equal s) vs then (bind_once ~loc name s; t)
else if stubs then t
else builtins_error ~loc (Printf.sprintf "%s = \"%s\" is not an OCaml symbol of %s (MLData, MLConstants)" name s file_name)
| Some None, _ -> builtins_error ~loc (Printf.sprintf "builtin symb %s: only the symbols of the language are builtin" name)
| None, vs when List.exists (String.equal "") vs ->
bind_once ~loc name ""; { t with attributes = Ast.External (Some "") :: attributes }
| None, [] when not pred && D.Global_symbols.is_default_symbol name ->
builtins_error ~loc (Printf.sprintf "%s is the name of an OCaml symbol (Constants.declare_global_symbol) that %s does not list: add it to its MLConstants" name file_name)
| None, [] -> t
| None, vs ->
builtins_error ~loc (Printf.sprintf "%s is the name of OCaml symbols with a variant: choose one with %s"
name (String.concat " or " (List.map (fun v -> Printf.sprintf "= \"%s\"" v) (List.sort String.compare vs)))) in
let rec bind_all stack = function
| [] -> []
| d :: rest ->
let ns = List.concat stack in
let d, stack =
match d with
| Ast.Program.Type l -> Ast.Program.Type (List.map (bind ~ns ~pred:false) l), stack
| Ast.Program.Pred t -> Ast.Program.Pred (bind ~ns ~pred:true t), stack
| Ast.Program.Namespace (_, n) -> d, [F.show n] :: stack
| Ast.Program.Begin _ | Ast.Program.Constraint _ -> d, [] :: stack
| Ast.Program.End _ -> d, (match stack with _ :: s -> s | [] -> [])
| d -> d, stack in
d :: bind_all stack rest in
let ast = bind_all [] ast in
constants |> List.iter (fun (name, variant) ->
if not (List.exists (fun (k, v) -> String.equal k name && String.equal v variant) !bound) then
builtins_error (Printf.sprintf "%s%s, an OCaml symbol of %s, is not declared by its text (symb, pred or func)" name (D.Global_symbols.show_variant_annotation variant) file_name));
{ p with ast }
let is_plugin_unit file_name =
String.length file_name > 1 && file_name.[0] = '+' && is_declared_builtins ~file_name
let text_of_builtins ~file_name =
let _, decls = declared_builtins ~file_name in
Data.BuiltInPredicate.document_to_string decls
let bind_builtins ?stubs ~file_name (p : Ast.Program.t) =
let _, decls = declared_builtins ~file_name in
bind_mlconstants ?stubs ~file_name decls p
let ast_of_builtins ~stubs ~(parser: (module Parse.Parser)) ~file_name =
let text = match declared_builtins ~file_name with
| _, [ BuiltInPredicate.LPCode s ] -> s
| _ -> text_of_builtins ~file_name in
let lexbuf = Lexing.from_string text in
let module P = (val parser) in
match P.program_from ~loc:(Util.Loc.initial file_name) ~digest:(Digest.string text) lexbuf with
| p, [], [] -> bind_builtins ~stubs ~file_name p
| _, errors, warnings ->
let { Util.loc; message; _ } =
match errors, warnings with
| e :: _, _ -> e
| [], { Util.warning } :: _ -> warning
| [], [] -> assert false in
List.iteri (fun i s ->
Printf.eprintf "%4d: %s\n" (i+1) s)
(Re.Str.(split_delim (regexp_string "\n") text));
begin match loc with
| Some loc ->
begin try Printf.eprintf "Excerpt of %s:\n%s\n" file_name
(String.sub text loc.Util.Loc.line_starts_at
Util.Loc.(loc.source_stop - loc.line_starts_at))
with _ -> (); end
| None -> () end;
anomaly ?loc message
let namespace_separatorc = '.'
let namespace_separator = String.make 1 namespace_separatorc
module Namespaces : sig
type t
val pp : Format.formatter -> t -> unit
val empty : t
val of_symbols : preds:F.Set.t -> tys:F.Set.t -> t
val union : t -> t -> t
val preds : t -> string list -> F.Set.t
val tys : t -> string list -> F.Set.t
end = struct
type members = { preds : F.Set.t; tys : F.Set.t }
[@@deriving show]
type t = members StrMap.t
let pp fmt t =
StrMap.iter (fun k m -> Format.fprintf fmt "@[<hov 2>%s:@ %a@]@ " k pp_members m) t
let empty = StrMap.empty
let union_members a b = { preds = F.Set.union a.preds b.preds; tys = F.Set.union a.tys b.tys }
let union = StrMap.union (fun _ a b -> Some (union_members a b))
let add pick t c =
let s = F.show c in
let len = String.length s in
let rec aux t i =
match String.index_from_opt s i namespace_separatorc with
| Some j when j + 1 < len ->
let t =
if j = 0 then t else
let prefix = String.sub s 0 j in
let name = F.from_string (String.sub s (j + 1) (len - j - 1)) in
let m = Option.value ~default:{ preds = F.Set.empty; tys = F.Set.empty } (StrMap.find_opt prefix t) in
StrMap.add prefix (pick m name) t in
aux t (j + 1)
| _ -> t in
aux t 0
let of_symbols ~preds ~tys =
let t = F.Set.fold (fun c t -> add (fun m x -> { m with preds = F.Set.add x m.preds }) t c) preds empty in
F.Set.fold (fun c t -> add (fun m x -> { m with tys = F.Set.add x m.tys }) t c) tys t
let find t prefix = StrMap.find_opt (String.concat namespace_separator prefix) t
let preds t prefix = match find t prefix with Some m -> m.preds | None -> F.Set.empty
let tys t prefix = match find t prefix with Some m -> m.tys | None -> F.Set.empty
end
module Flat = struct
type unchecked_signature = {
toplevel_macros : macro_declaration;
kinds : Arity.t F.Map.t;
types : ScopeTypeExpressionUniqueList.t F.Map.t;
type_abbrevs : (F.t * ScopedTypeExpression.t) list;
namespaces : Namespaces.t;
}
[@@deriving show]
type program = {
signature : unchecked_signature;
clauses : (ScopedTerm.t,Ast.Structured.attribute,bool,bool) Ast.Clause.t list;
chr : (F.t,ScopedTerm.t) Ast.Structured.block_constraint list;
builtins : declared_builtins option;
}
[@@deriving show]
end
module Assembled = struct
type signature = {
toplevel_macros : macro_declaration;
kinds : Arity.t F.Map.t;
types : TypingEnv.t;
type_abbrevs : Type_checker.type_abbrevs;
ty_names : Loc.t F.Map.t;
namespaces : Namespaces.t;
}
[@@deriving show]
type program = {
clauses : (Ast.Structured.insertion option * string option * constant * clause) list;
signature : signature;
total_type_checking_time : float;
total_det_checking_time : float;
builtins : Builtins.t;
prolog_program : index;
indexing : pred_info C.Map.t;
chr : CHR.t;
symbols : SymbolMap.table;
hash : string;
}
[@@deriving show]
let empty_signature () = {
kinds = F.Map.empty;
types = TypingEnv.empty;
type_abbrevs = F.Map.empty;
toplevel_macros = F.Map.empty;
ty_names = F.Map.empty;
namespaces = Namespaces.empty;
}
let empty () = {
clauses = [];
prolog_program = { idx = Ptmap.empty; time = 0; times = StrMap.empty };
indexing = C.Map.empty;
chr = CHR.empty;
symbols = SymbolMap.empty ();
total_type_checking_time = 0.0;
total_det_checking_time = 0.0;
hash = "";
builtins = Builtins.empty;
signature = empty_signature ()
}
end
module CheckedFlat = struct
type program = {
signature : Assembled.signature;
clauses : (ScopedTerm.t,Ast.Structured.attribute,bool,bool) Ast.Clause.t list;
chr : (Symbol.t,ScopedTerm.t) Ast.Structured.block_constraint list;
builtins : ((Symbol.t * string) list * declared_builtins) option;
as_written : (Loc.t * ScopedTerm.t) list;
}
[@@deriving show]
end
type scoped_program = {
version : string;
code : Scoped.program;
builtins : declared_builtins option;
file_name : string;
digest : Digest.t;
deps : Ast.dependencies;
}
[@@deriving show]
let scoped_program_name x = x.file_name
let scoped_program_digest x = x.digest
let scoped_program_deps x = x.deps
type unchecked_compilation_unit = {
version : string;
code : Flat.program;
file_name : string;
digest : Digest.t;
deps : Ast.dependencies;
}
[@@deriving show]
let hash_base x = string_of_int @@ Hashtbl.hash x
type checked_compilation_unit = {
version : string;
checked_code : CheckedFlat.program;
base_hash : string;
type_checking_time : float;
det_checking_time : float;
file_name : string;
digest : Digest.t;
deps : Ast.dependencies;
}
[@@deriving show]
let checked_compilation_unit_name x = x.file_name
let checked_compilation_unit_digest x = x.digest
let checked_compilation_unit_deps x = x.deps
type checked_compilation_unit_signature = {
signature: Assembled.signature;
file_name: string;
digest: Digest.t;
}
[@@deriving show]
let checked_compilation_unit_signature_name x = x.file_name
let checked_compilation_unit_signature_digest x = x.digest
let signature_of_checked_compilation_unit { checked_code = { CheckedFlat.signature }; file_name; digest; } = { file_name; signature; digest }
type program = State.t * Assembled.program
module WithMain = struct
type query = {
prolog_program : index;
chr : CHR.t;
symbols : SymbolMap.table;
runtime_types : Type_checker.runtime_types;
initial_goal : term;
assignments : term StrMap.t;
compiler_state : State.t;
total_type_checking_time : float;
total_det_checking_time : float;
builtins : Builtins.t;
}
[@@deriving show]
end
type query = WithMain.query
let valid_functional = function [] -> Some Ast.Structured.Relation | [Ast.Functional] -> Some Function | _ -> None
module RecoverStructure : sig
val run : errs:Errors.t -> State.t -> Ast.Program.t -> Ast.Structured.t list
val structure_type_expression : Loc.t -> 'a -> (Ast.raw_attribute list -> 'a option) -> Ast.raw_attribute list Ast.TypeExpression.t -> 'a Ast.TypeExpression.t
end = struct
let ErrorFun { error } = error_fun ~component:"Structure"
open Ast.Structured
open Ast
let cl2b = function
| [] -> []
| clauses -> [Clauses (List.rev clauses)]
let structure_clause_attributes ({ Clause.attributes; loc } as c) =
let duplicate_err s =
error ~loc ("duplicate attribute " ^ s) in
let illegal_err a =
error ~loc ("illegal attribute " ^ show_raw_attribute a) in
let illegal_replace s =
error ~loc ("replacing rule for "^ s ^" cannot have a name attribute") in
let illegal_remove_id s =
error ~loc ("remove rule for "^ s ^" cannot have a name attribute") in
let rec aux_attrs r = function
| [] -> r
| Name s :: rest ->
if r.id <> None then duplicate_err "name";
aux_attrs { r with id = Some s } rest
| After s :: rest ->
if r.insertion <> None then duplicate_err "insertion";
aux_attrs { r with insertion = Some (Insert (After s)) } rest
| Before s :: rest ->
if r.insertion <> None then duplicate_err "insertion";
aux_attrs { r with insertion = Some (Insert (Before s)) } rest
| Replace s :: rest ->
if r.insertion <> None then duplicate_err "insertion";
aux_attrs { r with insertion = Some (Replace s) } rest
| Remove s :: rest ->
if r.insertion <> None then duplicate_err "insertion";
aux_attrs { r with insertion = Some (Remove s) } rest
| If s :: rest ->
if r.ifexpr <> None then duplicate_err "if";
aux_attrs { r with ifexpr = Some s } rest
| Untyped :: rest -> aux_attrs { r with typecheck = false } rest
| AutoSpill :: rest -> aux_attrs { r with autospill = true } rest
| (NoOC
| External _ | Index _ | Functional) as a :: _-> illegal_err a
in
let attributes = aux_attrs { insertion = None; id = None; ifexpr = None; typecheck = true; occur_check = true; autospill = false } attributes in
begin
match attributes.insertion, attributes.id with
| Some (Replace x), Some _ -> illegal_replace x
| Some (Remove x), Some _ -> illegal_remove_id x
| _ -> ()
end;
{ c with Clause.attributes }
let structure_chr_attributes ({ Chr.attributes; loc } as c) =
let duplicate_err s =
error ~loc ("duplicate attribute " ^ s) in
let illegal_err a =
error ~loc ("illegal attribute " ^ show_raw_attribute a) in
let rec aux_chr r = function
| [] -> r
| Name s :: rest ->
aux_chr { r with cid = s } rest
| If s :: rest ->
if r.cifexpr <> None then duplicate_err "if";
aux_chr { r with cifexpr = Some s } rest
| (Before _ | After _ | Replace _ | Remove _ | External _ | Index _ | Functional | Untyped | NoOC | AutoSpill) as a :: _ -> illegal_err a
in
let cid = Loc.show loc in
{ c with Chr.attributes = aux_chr { cid; cifexpr = None } attributes }
let rec structure_type_expression_aux ~loc valid t = { t with TypeExpression.tit =
match t.TypeExpression.tit with
| TPred(att,p,v) when valid att <> None -> TPred(Option.get (valid att),List.map (fun (m,p) -> m, structure_type_expression_aux ~loc valid p) p,v)
| TPred([], _,_) -> assert false
| TPred(a :: _, _, _) -> error ~loc ("illegal attribute " ^ show_raw_attribute a)
| TArr(s,t) -> TArr(structure_type_expression_aux ~loc valid s,structure_type_expression_aux ~loc valid t)
| TApp(c,x,xs) -> TApp(c,structure_type_expression_aux ~loc valid x,List.map (structure_type_expression_aux ~loc valid) xs)
| TConst c -> TConst c
}
let flatten_arrows toplevel_func =
let is_propf f = F.equal F.propf f in
let rec is_pred = function
| Ast.TypeExpression.TConst a -> is_propf a
| TArr(_,r) -> is_pred r.tit
| TApp (_, _, _) | TPred (_, _, _) -> false
in
let rec flatten tloc = function
| Ast.TypeExpression.TArr (l,r) -> (Ast.Mode.Output, l) :: flatten_loc r
| TConst c when is_propf c -> []
| tit -> [Output,{tit;tloc}]
and flatten_loc {tit;tloc} = flatten tloc tit
and main = function
| Ast.TypeExpression.TPred (b, l,v) ->
Ast.TypeExpression.TPred (b, List.map (fun (a, b) -> a, main_loc b) l,v)
| TConst _ as t -> t
| TApp (n, x, xs) -> TApp (n, main_loc x, List.map main_loc xs)
| TArr (l, r) when is_pred r.tit -> TPred (toplevel_func, (Output, main_loc l) :: flatten_loc r,false)
| TArr (l, r) -> TArr(main_loc l, main_loc r)
and main_loc {tit;tloc} = {tit=main tit;tloc}
in main_loc
let structure_type_expression loc toplevel_func valid t =
let res = match t.TypeExpression.tit with
| TPred([],p,v) ->
{ t with tit = TPred(toplevel_func,List.map (fun (m,p) -> m, structure_type_expression_aux ~loc valid p) p,v) }
| x -> structure_type_expression_aux ~loc valid t
in flatten_arrows toplevel_func res
let structure_kind_attributes { Type.attributes; loc; name; ty; doc } =
let ty = structure_type_expression loc () (function [] -> Some () | _ -> None) ty in
match attributes with
| [] -> { Type.attributes = (); loc; name; ty; doc }
| x :: _ -> error ~loc ("illegal attribute " ^ show_raw_attribute x)
let structure_external ~loc = function
| None -> Builtin { variant = "" }
| Some "core" -> Core
| Some variant -> Builtin { variant }
let structure_type_attributes { Type.attributes; loc; name; ty; doc } : (symbol_attribute, functionality) Type.t=
let duplicate_err s =
error ~loc ("duplicate attribute " ^ s) in
let illegal_err a =
error ~loc ("illegal attribute " ^ show_raw_attribute a) in
let rec aux_tatt (r : symbol_attribute) f = function
| [] -> r, f
| External o :: rest ->
begin match r.availability with
| Structured.Elpi -> aux_tatt { r with availability = Structured.OCaml (structure_external ~loc o) } f rest
| Structured.OCaml _ -> duplicate_err "builtin"
end
| Index(i,index_type) :: rest ->
let it =
match index_type with
| None -> None
| Some "Map" -> Some Map
| Some "Hash" -> Some HashMap
| Some "DTree" -> Some DiscriminationTree
| Some s -> error ~loc ("unknown indexing directive " ^ s ^ ". Valid ones are: Map, Hash, DTree.") in
begin match r.index with
| None -> aux_tatt { r with index = Some (Structured.Index(i,it)) } f rest
| Some _ -> duplicate_err "index"
end
| NoOC :: rest -> aux_tatt { r with occur_check_pred = false } f rest
| Functional :: rest -> aux_tatt r Structured.Function rest
| (Before _ | After _ | Replace _ | Remove _ | Name _ | If _ | Untyped | AutoSpill) as a :: _ -> illegal_err a
in
let attributes, toplevel_func = aux_tatt { availability = Elpi; index = None; occur_check_pred = true } Structured.Relation attributes in
let is_functional_from_ty () = match ty.tit with
| TPred (l, _,_) -> List.mem Functional l | _ -> false in
let attributes =
match attributes.index with
| None ->
{ attributes with index =
if toplevel_func = Function || is_functional_from_ty () then Some MaximizeForFunctional
else None }
| Some _ -> attributes in
let ty = structure_type_expression loc toplevel_func valid_functional ty in
{ Type.attributes; loc; name; ty; doc }
let structure_type_abbreviation { TypeAbbreviation.name; value; nparams; loc } =
let rec aux = function
| TypeAbbreviation.Lam(c,loc,t) -> TypeAbbreviation.Lam(c,loc,aux t)
| TypeAbbreviation.Ty t -> TypeAbbreviation.Ty (structure_type_expression loc Relation valid_functional t)
in
{ TypeAbbreviation.name; value = aux value; nparams; loc }
let run ~errs _ { file_name; digest; ast = dl } =
let catch_error f x = Errors.catch_error errs f x in
let report_error ?loc msg = Errors.report_error errs error ?loc msg in
let rec aux_run ns blocks clauses macros kinds types tabbrs chr = function
| Program.Ignored _ :: rest ->
aux_run ns blocks clauses macros kinds types tabbrs chr rest
| (Program.End _ :: _ | []) as rest ->
{ body = List.rev (cl2b clauses @ blocks);
types = types;
kinds = List.rev kinds;
type_abbrevs = List.rev tabbrs;
macros = List.rev macros },
List.rev chr,
rest
| Program.Begin loc :: rest ->
let p, chr1, rest = aux_run ns [] [] [] [] [] [] [] rest in
if chr1 <> [] then
report_error ~loc "CHR cannot be declared inside an anonymous block";
aux_end_block loc ns (Block p :: cl2b clauses @ blocks)
[] macros kinds types tabbrs chr rest
| Program.Constraint (loc, ctx_filter, clique) :: rest ->
if chr <> [] then
report_error ~loc "Constraint blocks cannot be nested";
let p, chr, rest = aux_run ns [] [] [] [] [] [] [] rest in
aux_end_block loc ns (Constraints({loc;ctx_filter;clique;rules=chr},p) :: cl2b clauses @ blocks)
[] macros kinds types tabbrs [] rest
| Program.Namespace (loc, n) :: rest ->
let p, chr1, rest = aux_run (n::ns) [] [] [] [] [] [] [] rest in
if chr1 <> [] then
report_error ~loc "CHR cannot be declared inside a namespace block";
aux_end_block loc ns (Namespace (n,p) :: cl2b clauses @ blocks)
[] macros kinds types tabbrs chr rest
| Program.Shorten (loc,[]) :: _ ->
anomaly ~loc "parser returns empty list of shorten directives"
| Program.Shorten (loc,directives) :: rest ->
let shorthand (full_name,short_name) = { iloc = loc; full_name; short_name } in
let shorthands = List.map shorthand directives in
let p, chr1, rest = aux_run ns [] [] [] [] [] [] [] rest in
if chr1 <> [] then
report_error ~loc "CHR cannot be declared after a shorthand";
aux_run ns ((Shorten(shorthands,p) :: cl2b clauses @ blocks))
[] macros kinds types tabbrs chr rest
| Program.Accumulated (loc,l) :: rest ->
Errors.warn errs ~component:"Structure" ~id:NestedAccumulate ~loc "accumulate outside file header";
aux_run ns blocks clauses macros kinds types tabbrs chr
(List.concat_map (fun x -> Program.Begin loc :: x.ast @ [Program.End loc]) l @ rest)
| Program.Clause c :: rest ->
let c = catch_error structure_clause_attributes c in
aux_run ns blocks (c @? clauses) macros kinds types tabbrs chr rest
| Program.Macro m :: rest ->
aux_run ns blocks clauses (m::macros) kinds types tabbrs chr rest
| Program.Pred t :: rest ->
let t = catch_error structure_type_attributes t in
aux_run ns blocks clauses macros kinds (t @? types) tabbrs chr rest
| Program.Kind [] :: rest ->
aux_run ns blocks clauses macros kinds types tabbrs chr rest
| Program.Kind (k::ks) :: rest ->
let k = catch_error structure_kind_attributes k in
aux_run ns blocks clauses macros (k @? kinds) types tabbrs chr (Program.Kind ks :: rest)
| Program.Type [] :: rest ->
aux_run ns blocks clauses macros kinds types tabbrs chr rest
| Program.Type (t::ts) :: rest ->
let structure_type (t : (_,_) Ast.Type.t) =
if List.mem Functional t.Ast.Type.attributes then error ~loc:t.Ast.Type.loc "functional attribute only applies to pred";
structure_type_attributes t in
let t = catch_error structure_type t in
aux_run ns blocks clauses macros kinds (t @? types) tabbrs chr (Program.Type ts :: rest)
| Program.TypeAbbreviation abbr :: rest ->
let abbr = catch_error structure_type_abbreviation abbr in
aux_run ns blocks clauses macros kinds types (abbr @? tabbrs) chr rest
| Program.Chr r :: rest ->
let r = catch_error structure_chr_attributes r in
aux_run ns blocks clauses macros kinds types tabbrs (r @? chr) rest
and aux_end_block loc ns blocks clauses macros kinds types tabbrs chr rest =
match rest with
| Program.End _ :: rest ->
aux_run ns blocks clauses macros kinds types tabbrs chr rest
| _ ->
report_error ~loc "matching } is missing";
aux_run ns blocks clauses macros kinds types tabbrs chr rest
in
let rec aux_accumulate file_name digest accs deps = function
| Program.Accumulated (_,[]) :: rest -> aux_accumulate file_name digest accs deps rest
| Program.Accumulated (loc,x :: more) :: rest ->
let rest = Program.Accumulated (loc, more) :: rest in
let deps = (x.file_name,x.digest) :: deps in
if StrSet.mem x.digest accs then
aux_accumulate file_name digest accs deps rest
else
let files, accs = aux_accumulate x.file_name x.digest (StrSet.add x.digest accs) [] x.ast in
let more_files, accs = aux_accumulate file_name digest accs deps rest in
files @ more_files, accs
| rest -> [{ file_name; deps = List.rev deps; digest; ast = rest }], accs
in
let files, _ = aux_accumulate file_name digest StrSet.empty [] dl in
files |> List.map (fun x ->
let rec top (acc : Structured.program option) chr_acc ast =
let p, chr, rest = aux_run [] [] [] [] [] [] [] [] ast in
let p =
match acc with
| None -> p
| Some a ->
{ body = a.body @ p.body; types = p.types @ a.types; kinds = a.kinds @ p.kinds;
type_abbrevs = a.type_abbrevs @ p.type_abbrevs; macros = a.macros @ p.macros } in
let chr_acc = chr_acc @ chr in
match rest with
| [] -> p, chr_acc
| Program.End loc :: more -> report_error ~loc "extra }"; top (Some p) chr_acc more
| _ -> assert false in
let blocks, chr = top None [] x.ast in
if chr <> [] then
report_error "CHR cannot be declared outside a Constraint block";
{ x with ast = blocks })
end
module Quotation = struct
let named_quotations : QuotationHooks.quotation StrMap.t State.component = State.declare
~descriptor:elpi_state_descriptor
~name:"elpi:named_quotations"
~pp:(fun _ _ -> ())
~clause_compilation_is_over:(fun b -> b)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun x -> Some x)
~init:(fun () -> StrMap.empty)
()
let default_quotation : QuotationHooks.quotation option State.component = State.declare
~descriptor:elpi_state_descriptor
~name:"elpi:default_quotation"
~pp:(fun _ _ -> ())
~clause_compilation_is_over:(fun b -> b)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun x -> Some x)
~init:(fun () -> None)
()
end
include Quotation
module CustomFunctorCompilation = struct
let is_singlequote x =
let s = F.show x in
let len = String.length s in
len > 2 && s.[0] == '\'' && s.[len-1] == '\''
let is_backtick x =
let s = F.show x in
let len = String.length s in
len > 2 && s.[0] == '`' && s.[len-1] == '`'
let singlequote : (string * QuotationHooks.quotation) option State.component = State.declare
~descriptor:elpi_state_descriptor
~name:"elpi:singlequote"
~pp:(fun _ _ -> ())
~clause_compilation_is_over:(fun b -> b)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun x -> Some x)
~init:(fun () -> None)
()
let backtick : (string * QuotationHooks.quotation) option State.component = State.declare
~descriptor:elpi_state_descriptor
~name:"elpi:backtick"
~pp:(fun _ _ -> ())
~clause_compilation_is_over:(fun b -> b)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun x -> Some x)
~init:(fun () -> None)
()
let scope_singlequote ~loc state x =
match State.get singlequote state with
| None -> ScopedTerm.mkGlobalApp ~loc x []
| Some (language,f) -> ScopedTerm.(unlock @@ of_simple_term_loc @@ f ~language state loc (F.show x))
let scope_backtick ~loc state x =
match State.get backtick state with
| None -> ScopedTerm.mkGlobalApp ~loc x []
| Some (language,f) -> ScopedTerm.(unlock @@ of_simple_term_loc @@ f ~language state loc (F.show x))
end
let prefix_const prefix c =
F.from_string (String.concat namespace_separator (prefix @ [F.show c]))
let prepend p s =
F.Set.map (prefix_const p) s
let has_dot f =
try let _ = String.index (F.show f) namespace_separatorc in true
with Not_found -> false
type mtm = {
macros : (ScopedTerm.t * Loc.t) F.Map.t;
ctx: F.Set.t;
needs_spilling : bool ref;
macro_uses : Scoped.macro_use list ref option;
}
let empty_mtm = { macros = F.Map.empty; ctx = F.Set.empty; needs_spilling = ref false; macro_uses = None }
let todopp name _fmt _ = compiler_error ("pp not implemented for field: "^name)
let get_mtm, set_mtm, _drop_mtm, update_mtm =
let mtm =
State.declare
~name:"elpi:mtm" ~pp:(todopp "elpi:mtm")
~descriptor:D.elpi_state_descriptor
~clause_compilation_is_over:(fun _ -> empty_mtm)
~compilation_is_over:(fun _ -> None)
~execution_is_over:(fun _ -> None)
~init:(fun () -> empty_mtm)
() in
State.(get mtm, set mtm, drop mtm, update mtm)
module Scope_Quotation_Macro : sig
val run : errs:Errors.t -> State.t -> toplevel_macros:macro_declaration -> Ast.Structured.program -> Scoped.program
val scope_loc_term : state:State.t -> Ast.Term.t -> ScopedTerm.t
end = struct
let ErrorFun { error } = error_fun ~component:"Scope"
let map_append env Ast.Type.{name;loc} v m =
let k = name in
try
let l = F.Map.find k m in
F.Map.add k (ScopeTypeExpressionUniqueList.merge env v l) m
with Not_found ->
F.Map.add k v m
let is_uvar_name f = F.is_uvar_name f
let is_global f = (F.show f).[0] = '.'
let of_global f =
let s = F.show f in
F.from_string @@ String.sub s 1 (String.length s - 1)
let is_discard f =
F.(equal f dummyname) ||
let c = (F.show f).[0] in
c = '_'
let is_macro_name f =
let c = (F.show f).[0] in
c = '@'
let rec pred2arr ctx ~loc func variadic = function
| [] -> ScopedTypeExpression.Prop func
| [m,x] when variadic -> Arrow (m,Variadic,scope_loc_tye ctx x, {loc; it=ScopedTypeExpression.Prop func})
| (m,x)::xs -> Arrow (m,NotVariadic,scope_loc_tye ctx x, {loc; it=pred2arr ctx ~loc func variadic xs})
and scope_tye ctx ~loc t : ScopedTypeExpression.t_ =
match t with
| Ast.TypeExpression.TConst c when F.equal F.propf c -> Prop Relation
| TConst c when F.show c = "any" -> Any
| TConst c when F.Set.mem c ctx -> Const(Bound elpi_language,c)
| TConst c when is_global c -> Const(Scope.mkGlobal ~escape_ns:true (),of_global c)
| TConst c -> Const(Scope.mkGlobal(),c)
| TApp(c,x,[y]) when F.show c = "variadic" ->
Arrow(Input, Variadic,scope_loc_tye ctx x,scope_loc_tye ctx y)
| TApp(c,x,xs) when is_global c ->
App(Scope.mkGlobal ~escape_ns:true (), of_global c, scope_loc_tye ctx x, List.map (scope_loc_tye ctx) xs)
| TApp(c,x,xs) ->
if F.Set.mem c ctx || is_uvar_name c then error ~loc "type schema parameters cannot be type formers";
App(Scope.mkGlobal (),c,scope_loc_tye ctx x, List.map (scope_loc_tye ctx) xs)
| TPred(m,xs,v) -> pred2arr ctx ~loc m v xs
| TArr(s,t) -> Arrow(Output, NotVariadic, scope_loc_tye ctx s, scope_loc_tye ctx t)
and scope_loc_tye ctx { tloc; tit } = { loc = tloc; it = scope_tye ctx ~loc:tloc tit }
let scope_loc_tye ctx (t: Ast.Structured.functionality Ast.TypeExpression.t) =
scope_loc_tye ctx t
let compile_type { Ast.Type.name; loc; doc; attributes = { Ast.Structured.index; availability; occur_check_pred }; ty } =
let open ScopedTypeExpression in
let value = scope_loc_tye F.Set.empty ty in
let vars =
let rec aux e { it } =
match it with
| App(_,_,x,xs) -> List.fold_left aux e (x :: xs)
| Const(Bound _, _) -> assert false
| Const(Global _,c) when is_uvar_name c -> F.Set.add c e
| Const(Global _,_) -> e
| Any | Prop _ -> e
| Arrow(_,_,x,y) -> aux (aux e x) y
in
aux F.Set.empty value in
let value = scope_loc_tye vars ty in
let nparams = F.Set.cardinal vars in
let value =
let rec close s t =
if F.Set.is_empty s then t
else
let c = F.Set.choose s in
let s = F.Set.remove c s in
close s (Lam(c,t)) in
close vars (Ty value) in
{ ScopedTypeExpression.name; index; availability; occur_check = occur_check_pred; loc; doc; nparams; value }
let scope_term_macro ~loc ~name_loc ~state c args =
let { macros; macro_uses } = get_mtm state in
match F.Map.find_opt c macros with
| None -> error ~loc (Format.asprintf "@[<hv>Unknown macro %a.@ Known macros: %a@]" F.pp c (pplist F.pp ", ") (F.Map.bindings macros|>List.map fst))
| Some (t, macro_loc) ->
Option.iter (fun uses -> uses := { Scoped.name_loc; expansion_loc = loc; macro = c; macro_loc; args } :: !uses) macro_uses;
ScopedTerm.(beta (clone_loc ~loc t) args)
let rec scope_term ~state ctx ~loc t =
let open Ast.Term in
match t with
| Parens { loc; it } -> scope_term ~state ctx ~loc it
| Const c when is_discard c -> ScopedTerm.Discard { heapify = false }
| Const c when is_macro_name c ->
scope_term_macro ~loc ~name_loc:loc ~state c []
| Const c when F.Set.mem c ctx -> ScopedTerm.mkBoundApp ~lang:elpi_language ~loc c []
| Const c ->
if is_uvar_name c then ScopedTerm.mkUVar ~loc c []
else if CustomFunctorCompilation.is_singlequote c then CustomFunctorCompilation.scope_singlequote ~loc state c
else if CustomFunctorCompilation.is_backtick c then CustomFunctorCompilation.scope_backtick ~loc state c
else if is_global c then ScopedTerm.mkGlobalApp ~escape_ns:true ~loc (of_global c) []
else ScopedTerm.mkGlobalApp ~loc c []
| App ({ it = App (f,l1) },l2) -> scope_term ~state ctx ~loc (App(f, l1 @ l2))
| App ({ it = Parens f },l) -> scope_term ~state ctx ~loc (App(f, l))
| App({ it = Const c }, [x]) when F.equal c F.spillf ->
let { needs_spilling } = get_mtm state in
needs_spilling := true;
ScopedTerm.Spill (scope_loc_term ~state ctx x,ref ScopedTerm.NoInfo)
| App({ it = Const c; loc = cloc }, l) when ScopedTerm.SimpleTerm.is_implf c ->
begin match l with
| [t1;t2] ->
Impl (ScopedTerm.SimpleTerm.func_to_impl_kind c, cloc, scope_loc_term ~state ctx t1, scope_loc_term ~state ctx t2)
| _ -> error ~loc "implication is a binary operator"
end
| App({ it = Const c; loc = cloc }, xs) ->
if is_discard c then error ~loc "Applied discard";
let xs = List.map (scope_loc_term ~state ctx) xs in
if is_macro_name c then
scope_term_macro ~loc ~name_loc:cloc ~state c xs
else
let bound = F.Set.mem c ctx in
if bound then ScopedTerm.mkBoundApp ~lang:elpi_language ~loc:cloc c xs
else if is_uvar_name c then ScopedTerm.mkUVar ~loc:cloc c xs
else if is_global c then ScopedTerm.mkGlobalApp ~escape_ns:true ~loc:cloc (of_global c) xs
else ScopedTerm.mkGlobalApp ~loc:cloc c xs
| Cast (t,ty) ->
let t = scope_loc_term ~state ctx t in
let ty = scope_loc_tye F.Set.empty (RecoverStructure.structure_type_expression ty.Ast.TypeExpression.tloc Ast.Structured.Relation valid_functional ty) in
ScopedTerm.Cast(t,ty)
| Lam (c,_,ty,b) when is_discard c ->
let ty = ty |> Option.map (fun ty -> scope_loc_tye F.Set.empty (RecoverStructure.structure_type_expression ty.Ast.TypeExpression.tloc Ast.Structured.Relation valid_functional ty)) in
ScopedTerm.Lam (None,ty, scope_loc_term ~state ctx b)
| Lam (c,cloc,ty,b) ->
if has_dot c then error ~loc "Bound variables cannot contain the namespaec separator '.'";
let ty = ty |> Option.map (fun ty -> scope_loc_tye F.Set.empty (RecoverStructure.structure_type_expression ty.Ast.TypeExpression.tloc Ast.Structured.Relation valid_functional ty)) in
let name = Some (ScopedTerm.mk_binder ~lang:elpi_language c ~loc:cloc) in
ScopedTerm.Lam (name,ty,scope_loc_term ~state (F.Set.add c ctx) b)
| CData c -> ScopedTerm.CData c
| App ({ it = Lam _},_) ->
error ~loc "Beta-redexes not allowed, use something like (F = x\\x, F a)"
| App ({ it = CData _},_) ->
error ~loc "Applied literal"
| App ({ it = Quoted _},_) ->
error ~loc "Applied quotation"
| App({ it = Cast _},_) ->
error ~loc "Casted app not supported yet"
| Quoted _ -> assert false
and scope_loc_term ~state ctx { Ast.Term.it; loc } =
match it with
| Quoted { Ast.Term.data; kind; qloc } ->
let unquote =
match kind with
| None ->
let default_quotation = State.get default_quotation state in
if Option.is_none default_quotation then
error ~loc "{{ ... }}: no default quotation is declared (by the host, or by a plugin loaded before Setup.init, e.g. by preload in elpi.toml)";
option_get default_quotation ~language:"default"
| Some name ->
let named_quotations = State.get named_quotations state in
try StrMap.find name named_quotations ~language:name
with Not_found ->
let known = match StrMap.bindings named_quotations with
| [] -> "none is declared"
| l -> "the declared ones are " ^ String.concat ", " (List.map fst l) in
error ~loc (Printf.sprintf "{{:%s ... }}: no quotation %s (%s)" name name known) in
let state = update_mtm state (fun x -> { x with ctx }) in
let simple_t =
try unquote state qloc data
with Elpi_parser.Parser_config.ParseError(loc,msg) -> error ~loc msg in
ScopedTerm.of_simple_term_loc simple_t
| _ ->
let it = scope_term ~state ctx ~loc it in
{ ScopedTerm.it; loc; ty = TypeAssignment.new_ty () }
let scope_loc_term ~state =
let { ctx } = get_mtm state in
scope_loc_term ~state ctx
let scope_type_abbrev { Ast.TypeAbbreviation.name; value; nparams; loc } =
let rec aux ctx = function
| Ast.TypeAbbreviation.Lam(c,loc,t) when is_uvar_name c ->
if F.Set.mem c ctx then error ~loc "duplicate type schema variable";
ScopedTypeExpression.Lam(c,aux (F.Set.add c ctx) t)
| Ast.TypeAbbreviation.Lam(c,loc,_) -> error ~loc "only variables can be abstracted in type schema"
| Ast.TypeAbbreviation.Ty t -> ScopedTypeExpression.Ty (scope_loc_tye ctx t)
in
{ ScopedTypeExpression.name; value = aux F.Set.empty value; nparams; loc; doc = None; index = None; occur_check = true; availability = Elpi }
let compile_type_abbrev ({ Ast.TypeAbbreviation.name; nparams; loc } as ab) =
let ab = scope_type_abbrev ab in
name, ab
let defs_of_map m = F.Map.bindings m |> List.fold_left (fun x (a,_) -> F.Set.add a x) F.Set.empty
let defs_of_assoclist m = m |> List.fold_left (fun x (a,_) -> F.Set.add a x) F.Set.empty
let global_hd_symbols_of_clause { Ast.Clause.body; loc } =
let open ScopedTerm in
let add1 ~loc s t =
match t.it with
| App({ scope = Global _; name = c },_) -> F.Set.add c s
| Impl(R2L,_,{ it = (App({ scope = Global _; name = c },_)) }, _) -> F.Set.add c s
| Impl(R2L,_,{ it = (UVar _) }, _) | UVar _ -> error ~loc "Variables cannot be used as predicate names"
| _ -> error ~loc "Cannot determine the predicate for this rule" in
match body.it with
| App({ scope = Global _; name = c },xs) when F.equal F.andf c ->
List.fold_left (add1 ~loc) F.Set.empty xs
| _ -> add1 ~loc F.Set.empty body
let with_macros ?(needs_spilling = empty_mtm.needs_spilling) state macros =
update_mtm state (fun { macro_uses } -> { empty_mtm with macros; needs_spilling; macro_uses })
let compile_clause state macros { Ast.Clause.body; attributes; loc; needs_spilling = () } =
let needs_spilling = ref false in
let state = with_macros ~needs_spilling state macros in
let body = scope_loc_term ~state body in
{ Ast.Clause.body; attributes; loc; needs_spilling = !needs_spilling }
let compile_sequent state macros { Ast.Chr.eigen; context; conclusion } =
let state = with_macros state macros in
{ Ast.Chr.eigen = scope_loc_term ~state eigen; context = scope_loc_term ~state context; conclusion = scope_loc_term ~state conclusion }
let compile_chr_rule state macros { Ast.Chr.to_match; to_remove; guard; new_goal; attributes; loc } =
let to_match = List.map (compile_sequent state macros) to_match in
let to_remove = List.map (compile_sequent state macros) to_remove in
let guard = Option.map (scope_loc_term ~state:(with_macros state macros)) guard in
let new_goal = Option.map (compile_sequent state macros) new_goal in
{ Ast.Chr.to_match; to_remove; guard; new_goal; attributes; loc }
let compile_kind kinds { Ast.Type.name; ty; loc } =
let open Ast.TypeExpression in
let rec count = function
| TArr({ tit = TConst c },t) when F.equal c F.typef -> 1 + count t.tit
| TConst c when F.equal c F.typef -> 0
| x -> error ~loc "Syntax error: illformed kind.\nExamples:\nkind bool type.\nkind list type -> type.\n"
in
F.Map.add name (count ty.tit, loc) kinds
let compile_macro state (am,m) { Ast.Macro.loc; name; body } =
try
let _, oloc = F.Map.find name m in
error ~loc (Format.asprintf "duplicate macro %a, previous declaration %a" F.pp name Loc.pp oloc)
with Not_found ->
let body = scope_loc_term ~state:(with_macros state m) body in
F.Map.add name (body,loc) am, F.Map.add name (body,loc) m
let rec ast_heads (t : Ast.Term.t) =
match t.Ast.Term.it with
| Ast.Term.App ({ it = Const c }, [ hd; _ ]) when F.equal c F.rimplf -> ast_heads hd
| Ast.Term.App ({ it = Const c }, args) when F.equal c F.andf -> List.concat_map ast_heads args
| Ast.Term.App ({ it = Const c }, _) | Ast.Term.Const c -> if is_uvar_name c then [] else [c]
| Ast.Term.Parens t -> ast_heads t
| _ -> []
let run ~errs state ~toplevel_macros p : Scoped.program =
let guard ~default f = Errors.protect errs ~default f in
let macro_uses = ref [] in
let state = update_mtm state (fun m -> { m with macro_uses = Some macro_uses }) in
let rec compile_program omacros state { Ast.Structured.macros; kinds; types; type_abbrevs; body } =
let toplevel_macros, active_macros =
Errors.protect_fold_left ~errs (compile_macro state) (F.Map.empty,omacros) macros in
let type_abbrevs = Errors.protect_list_map ~errs compile_type_abbrev type_abbrevs in
let kinds = Errors.protect_fold_left ~errs compile_kind F.Map.empty kinds in
let types = Errors.protect_fold_left ~errs (fun m t -> map_append TypingEnv.empty t (ScopeTypeExpressionUniqueList.make @@ compile_type t) m) F.Map.empty (List.rev types) in
let type_abbrevs =
Errors.protect_list_filter ~errs (fun (ta, tad) ->
match F.Map.find_opt ta kinds with
| None -> true
| Some (_, oloc) ->
error ~loc:tad.ScopedTypeExpression.loc ("Illegal type abbreviation for " ^ F.show ta ^ ". A type with the same name already exists in " ^ Loc.show oloc))
type_abbrevs in
let defs_k = defs_of_map kinds in
let defs_t = defs_of_map types in
let defs_ta = defs_of_assoclist type_abbrevs in
let kinds, types, type_abbrevs, defs_b, defs_ty, body =
compile_body active_macros kinds types type_abbrevs F.Set.empty F.Set.empty state body in
let ty_symbols = F.Set.(union defs_k (union defs_ta defs_ty)) in
let pred_symbols = F.Set.(union defs_t defs_b) in
toplevel_macros,
{ Scoped.types; kinds; type_abbrevs; body; ty_symbols; pred_symbols }
and compile_body macros kinds types type_abbrevs (defs : F.Set.t) (ty_defs : F.Set.t) state = function
| [] -> kinds, types, type_abbrevs, defs, ty_defs, []
| Clauses cl :: rest ->
let compiled = List.map (fun (cl : _ Ast.Clause.t) ->
guard ~default:(None, F.Set.of_list (ast_heads cl.Ast.Clause.body)) (fun () ->
let c = compile_clause state macros cl in
Some c, global_hd_symbols_of_clause c)) cl in
let compiled_cl = List.filter_map fst compiled in
let defs = List.fold_left (fun defs (_, hd) -> F.Set.union defs hd) defs compiled in
let kinds, types, type_abbrevs, defs, ty_defs, compiled_rest =
compile_body macros kinds types type_abbrevs defs ty_defs state rest in
let compiled_rest =
match compiled_rest with
| Scoped.Clauses l :: rest -> Scoped.Clauses (compiled_cl @ l) :: rest
| rest -> Scoped.Clauses compiled_cl :: rest in
kinds, types, type_abbrevs, defs, ty_defs, compiled_rest
| Namespace (prefix, p) :: rest ->
let prefix = F.show prefix in
let _, p = compile_program macros state p in
let kinds, types, type_abbrevs, defs, ty_defs, compiled_rest =
compile_body macros kinds types type_abbrevs defs ty_defs state rest in
let ty_symbols = prepend [prefix] p.Scoped.ty_symbols in
let pred_symbols = prepend [prefix] p.Scoped.pred_symbols in
kinds, types, type_abbrevs, F.Set.union defs pred_symbols, F.Set.union ty_defs ty_symbols,
Scoped.Namespace(prefix, p) :: compiled_rest
| Shorten(shorthands,p) :: rest ->
let shorts = List.fold_left (fun s { Ast.Structured.short_name } ->
F.Set.add short_name s) F.Set.empty shorthands in
let _, p = compile_program macros state p in
let kinds, types, type_abbrevs, defs, ty_defs, compiled_rest =
compile_body macros kinds types type_abbrevs defs ty_defs state rest in
kinds, types, type_abbrevs,
F.Set.union defs (F.Set.diff p.Scoped.pred_symbols shorts),
F.Set.union ty_defs (F.Set.diff p.Scoped.ty_symbols shorts),
Scoped.Shorten(shorthands, p) :: compiled_rest
| Constraints ({loc;ctx_filter; clique; rules}, p) :: rest ->
let rules = Errors.protect_list_map ~errs (compile_chr_rule state macros) rules in
let _, p = compile_program macros state p in
let kinds, types, type_abbrevs, defs, ty_defs, compiled_rest =
compile_body macros kinds types type_abbrevs defs ty_defs state rest in
kinds, types, type_abbrevs,
F.Set.union defs p.Scoped.pred_symbols,
F.Set.union ty_defs p.Scoped.ty_symbols,
Scoped.Constraints({loc;ctx_filter; clique; rules},p) :: compiled_rest
| Block p :: rest ->
let _, p = compile_program macros state p in
let kinds, types, type_abbrevs, defs, ty_defs, compiled_rest =
compile_body macros kinds types type_abbrevs defs ty_defs state rest in
kinds, types, type_abbrevs,
F.Set.union defs p.Scoped.pred_symbols,
F.Set.union ty_defs p.Scoped.ty_symbols,
Scoped.Block p :: compiled_rest
in
let toplevel_macros, pbody = compile_program toplevel_macros state p in
{ Scoped.pbody; toplevel_macros; macro_uses = List.rev !macro_uses }
end
module Flatten : sig
val run : errs:Errors.t -> base:Assembled.signature -> State.t -> Scoped.program -> Flat.program
val merge_kinds :
errs:Errors.t ->
Arity.t F.Map.t ->
Arity.t F.Map.t ->
Arity.t F.Map.t
val merge_type_assignments :
TypingEnv.t ->
TypingEnv.t ->
TypingEnv.t
val merge_checked_type_abbrevs :
errs:Errors.t ->
Type_checker.type_abbrevs ->
Type_checker.type_abbrevs ->
Type_checker.type_abbrevs
val merge_toplevel_macros :
errs:Errors.t ->
TypingEnv.t ->
(ScopedTerm.t * Loc.t) F.Map.t ->
(ScopedTerm.t * Loc.t) F.Map.t -> (ScopedTerm.t * Loc.t) F.Map.t
end = struct
let ErrorFun { error } = error_fun ~component:"Flatten"
let report_error errs ?loc msg = Errors.report_error errs error ?loc msg
type subst = { old_prefix : string list; subst : F.t F.Map.t }
let empty_subst = { old_prefix = []; subst = F.Map.empty }
let push_subst symbols_affected { old_prefix; subst = oldsubst } =
let new_prefix = old_prefix @ [extra_prefix] in
let newsubst =
F.Set.fold (fun c subst ->
let c1 = prefix_const new_prefix c in
F.Map.add c c1 subst) symbols_affected oldsubst in
{ old_prefix = new_prefix; subst = newsubst }
let push_subst_shorthands shorthands { old_prefix; subst = oldsubst } =
let push1 m { Ast.Structured.short_name; full_name } =
F.Map.add short_name
(try F.Map.find full_name m with Not_found -> full_name) m
in
{ old_prefix; subst = List.fold_left push1 oldsubst shorthands }
let smart_map_scoped_term f ~tyf:tyf t =
let open ScopedTerm in
let rec aux it =
match it with
| Impl(b,lb,t1,t2) ->
let t1' = aux_loc t1 in
let t2' = aux_loc t2 in
if t1 == t1' && t2 == t2' then it
else Impl(b,lb,t1',t2')
| Spill(t,n) -> let t' = aux_loc t in if t' == t then it else Spill(t',n)
| App({scope; name = c; ty; loc},xs) ->
let c' = match scope with Global { escape_ns = false } -> f c | _ -> c in
let xs' = smart_map aux_loc xs in
if c == c' && xs == xs' then it
else App({scope = Scope.mkGlobal (); name = c'; ty; loc},xs')
| Lam(n,ty,b) ->
let b' = aux_loc b in
let ty' = option_smart_map (ScopedTypeExpression.smart_map_scoped_loc_ty tyf) ty in
if b == b' && ty' == ty then it else Lam(n,ty',b')
| UVar(c,l) ->
let l' = smart_map aux_loc l in
if l == l' then it else UVar(c,l')
| Cast(t,ty) ->
let t' = aux_loc t in
let ty' = ScopedTypeExpression.smart_map_scoped_loc_ty tyf ty in
if t' == t && ty' == ty then it else Cast(t',ty')
| Discard _ -> it
| CData _ -> it
and aux_loc ({ it; loc; ty } as orig) =
let it' = aux it in
if it == it' then orig
else { it = it'; loc; ty }
in
aux_loc t
let smart_map_clause f ({ Ast.Clause.body } as x) =
let body' = f body in
if body == body' then x else { x with body = body' }
let subst_global { subst = s } f =
try F.Map.find f s
with Not_found -> f
let apply_subst_clauses s ty_s cl =
smart_map (smart_map_clause (smart_map_scoped_term (subst_global s) ~tyf:(subst_global ty_s))) cl
let smart_map_sequent f ~tyf ({ Ast.Chr. eigen; context; conclusion } as orig) =
let eigen' = smart_map_scoped_term f ~tyf eigen in
let context' = smart_map_scoped_term f ~tyf context in
let conclusion' = smart_map_scoped_term f ~tyf conclusion in
if eigen' == eigen && context' == context && conclusion' == conclusion then orig
else { Ast.Chr.eigen = eigen'; context = context'; conclusion = conclusion' }
let smart_map_chr f ~tyf ({ Ast.Chr.to_match; to_remove; guard; new_goal; attributes; loc } as orig) =
let to_match' = smart_map (smart_map_sequent f ~tyf) to_match in
let to_remove' = smart_map (smart_map_sequent f ~tyf) to_remove in
let guard' = Util.option_map (smart_map_scoped_term f ~tyf) guard in
let new_goal' = Util.option_map (smart_map_sequent f ~tyf) new_goal in
if to_match' == to_match && to_remove' == to_remove && guard' == guard && new_goal' == new_goal then orig
else { Ast.Chr.to_match = to_match'; to_remove = to_remove'; guard = guard'; new_goal = new_goal'; attributes; loc }
let smart_map_chrs f ~tyf ({ Ast.Structured.clique; ctx_filter; rules; loc } as orig) =
let clique' = smart_map f clique in
let ctx_filter' = smart_map f ctx_filter in
let rules' = smart_map (smart_map_chr f ~tyf) rules in
if clique' == clique && ctx_filter' == ctx_filter && rules' == rules then orig
else { Ast.Structured.clique = clique'; ctx_filter = ctx_filter'; rules = rules'; loc }
let apply_subst_chrs s sty = smart_map_chrs (subst_global s) ~tyf:(subst_global sty)
let apply_subst_types pred_subst ty_subst l =
let pred_f = subst_global pred_subst and ty_f = subst_global ty_subst in
F.Map.fold (fun k v m ->
F.Map.add (pred_f k) (ScopeTypeExpressionUniqueList.smart_map (ScopedTypeExpression.smart_map ~name:pred_f ty_f) v) m)
l F.Map.empty
let apply_subst_kinds s l =
F.Map.fold (fun k v m -> F.Map.add (subst_global s k) v m) l F.Map.empty
let apply_subst_type_abbrevs s l =
List.map (fun (k, v) -> subst_global s k, ScopedTypeExpression.smart_map ~name:(subst_global s) (subst_global s) v) l
let merge_type_assignments = TypingEnv.merge_envs
let union_resilient ~errs f m1 m2 =
Errors.protect_fMap_fold ~errs (fun k v2 acc ->
match F.Map.find_opt k acc with
| None -> F.Map.add k v2 acc
| Some v1 ->
match f k v1 v2 with
| Some v -> F.Map.add k v acc
| None -> F.Map.remove k acc) m2 m1
let merge_checked_type_abbrevs ~errs (m1 : TypeAssignment.type_abbrevs) (m2 : TypeAssignment.type_abbrevs) =
let open TypeAssignment in
union_resilient ~errs (fun k ({ skema = sk; loc = otherloc} as x) { skema = ty; loc; } ->
if TypeAssignment.compare_skema sk ty <> 0 then
error ~loc
("Duplicate type abbreviation for " ^ F.show k ^
". Previous declaration: " ^ Loc.show otherloc)
else
Some x) m1 m2
let merge_types env t1 t2 =
F.Map.union (fun _ l1 l2 -> Some (ScopeTypeExpressionUniqueList.merge env l1 l2)) t1 t2
let merge_kinds ~errs (t1 : Arity.t F.Map.t) t2 =
union_resilient ~errs (fun f (k,loc1 as kdecl) (k',loc2) ->
if k == k' then Some kdecl
else error ~loc:loc2 ("Duplicate kind declaration for " ^ F.show f ^ ". Previously declared in " ^ Loc.show loc1);
) t1 t2
let merge_type_abbrevs m1 m2 = m1 @ m2
let merge_toplevel_macros ~errs env otlm toplevel_macros =
union_resilient ~errs (fun k (m1,l1) (m2,l2) ->
if ScopedTerm.equal env ~types:false m1 m2 then Some (m1,l1) else
error ~loc:l2 (Format.asprintf "@[<v>Macro %a declared twice.@;@[<hov 2>%a @[%a@]@]@;@[<hov 2>%a @[%a@]@]@]" F.pp k Loc.pp l1 ScopedTerm.pretty m1 Loc.pp l2 ScopedTerm.pretty m2)
) otlm toplevel_macros
let compile_block ~errs ~namespace_preds ~namespace_tys =
let merge_kinds = merge_kinds ~errs in
let rec compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst = function
| [] -> kinds, types, type_abbrevs, clauses, chr
| Scoped.Shorten(shorthands, { kinds = k; types = t; type_abbrevs = ta; body; pred_symbols = _; ty_symbols = _ }) :: rest ->
let inpsubst = push_subst_shorthands shorthands pred_subst in
let intysubst = push_subst_shorthands shorthands ty_subst in
let kinds = merge_kinds (apply_subst_kinds intysubst k) kinds in
let types = merge_types TypingEnv.empty (apply_subst_types inpsubst intysubst t) types in
let type_abbrevs = merge_type_abbrevs type_abbrevs (apply_subst_type_abbrevs intysubst ta) in
let kinds, types, type_abbrevs, clauses, chr =
compile_block kinds types type_abbrevs clauses chr inpsubst intysubst body in
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst rest
| Scoped.Namespace (, { kinds = k; types = t; type_abbrevs = ta; body; pred_symbols = ps; ty_symbols = ts }) :: rest ->
let prefix = pred_subst.old_prefix @ [extra] in
let new_pred_subst = push_subst extra (F.Set.union ps (namespace_preds prefix)) pred_subst in
let new_ty_subst = push_subst extra (F.Set.union ts (namespace_tys prefix)) ty_subst in
let kinds = merge_kinds (apply_subst_kinds new_ty_subst k) kinds in
let types = merge_types TypingEnv.empty (apply_subst_types new_pred_subst new_ty_subst t) types in
let type_abbrevs = merge_type_abbrevs type_abbrevs (apply_subst_type_abbrevs new_ty_subst ta) in
let type_abbrevs =
List.filter (fun (ta, tad) ->
match F.Map.find_opt ta kinds with
| None -> true
| Some (_,oloc) ->
report_error errs ~loc:tad.ScopedTypeExpression.loc ("Illegal type abbreviation for " ^ F.show ta ^ ". A type with the same name already exists in " ^ Loc.show oloc);
false)
type_abbrevs in
let kinds, types, type_abbrevs, clauses, chr =
compile_block kinds types type_abbrevs clauses chr new_pred_subst new_ty_subst body in
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst rest
| Scoped.Clauses cl :: rest ->
let cl = apply_subst_clauses pred_subst ty_subst cl in
let clauses = cl :: clauses in
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst rest
| Scoped.Constraints (ch, { kinds = k; types = t; type_abbrevs = ta; body }) :: rest ->
let kinds = merge_kinds (apply_subst_kinds ty_subst k) kinds in
let types = merge_types TypingEnv.empty (apply_subst_types pred_subst ty_subst t) types in
let type_abbrevs = merge_type_abbrevs type_abbrevs (apply_subst_type_abbrevs ty_subst ta) in
let chr = apply_subst_chrs pred_subst ty_subst ch :: chr in
let kinds, types, type_abbrevs, clauses, chr =
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst body in
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst rest
| Scoped.Block { kinds=k; types = t; type_abbrevs = ta; body; ty_symbols = _ } :: rest ->
let kinds = merge_kinds (apply_subst_kinds ty_subst k) kinds in
let types = merge_types TypingEnv.empty (apply_subst_types pred_subst ty_subst t) types in
let type_abbrevs = merge_type_abbrevs type_abbrevs (apply_subst_type_abbrevs ty_subst ta) in
let kinds, types, type_abbrevs, clauses, chr =
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst body in
compile_block kinds types type_abbrevs clauses chr pred_subst ty_subst rest
in compile_block
let run ~errs ~base state { Scoped.pbody; toplevel_macros; macro_uses = _ } =
let { Scoped.kinds; types; type_abbrevs; ty_symbols; pred_symbols; body } = pbody in
let namespaces = Namespaces.of_symbols ~preds:pred_symbols ~tys:ty_symbols in
let all_namespaces = Namespaces.union base.Assembled.namespaces namespaces in
let kinds, types, type_abbrevs, clauses_rev, chr_rev =
compile_block ~errs ~namespace_preds:(Namespaces.preds all_namespaces) ~namespace_tys:(Namespaces.tys all_namespaces)
kinds types type_abbrevs [] [] empty_subst empty_subst body in
let signature = { Flat.kinds; types; type_abbrevs; toplevel_macros; namespaces } in
{ Flat.clauses = List.(flatten (rev clauses_rev)); chr = List.rev chr_rev; builtins = None; signature }
end
module Check : sig
val check : errs:Errors.t -> flags:flags -> State.t -> base:Assembled.program -> unchecked_compilation_unit -> checked_compilation_unit
end = struct
let ErrorFun { error = error_typechecker } = error_fun ~component:"Typechecker"
let ErrorFun { error = error_builtins } = error_fun ~component:"Builtins"
let ErrorFun { error = error_chr } = error_fun ~component:"CHR"
let check_signature ~errs ~flags (base_signature : Assembled.signature) (signature : Flat.unchecked_signature) : Assembled.signature * Assembled.signature * float * TypingEnv.t =
let { Assembled.kinds = ok; types = ot; type_abbrevs = ota; toplevel_macros = otlm; ty_names = ots; namespaces = ons } = base_signature in
let { Flat.kinds; types; type_abbrevs; toplevel_macros; namespaces } = signature in
let all_kinds = Flatten.merge_kinds ~errs ok kinds in
let check_k_begin = Unix.gettimeofday () in
let all_type_abbrevs, type_abbrevs, all_ty_names, ty_names =
Errors.protect_fold_left ~errs (fun (all_type_abbrevs,type_abbrevs, all_ty_names, ty_names) (name, scoped_ty) ->
let loc = scoped_ty.ScopedTypeExpression.loc in
let _, _, { TypingEnv.ty } = Type_checker.check_type ~type_abbrevs:all_type_abbrevs ~kinds:all_kinds scoped_ty in
if F.Map.mem name all_type_abbrevs then begin
let TypeAssignment.{ skema = sk; loc = otherloc; } = F.Map.find name all_type_abbrevs in
if TypeAssignment.compare_skema sk ty <> 0 then
error_typechecker ~loc
("Duplicate type abbreviation for " ^ F.show name ^
". Previous declaration: " ^ Loc.show otherloc)
end;
if F.Map.mem name ots && not (Loc.equal (F.Map.find name ots) loc) then begin
error_typechecker ~loc ("Illegal type abbreviation for " ^ F.show name ^ ". A type with the same name already exists in " ^ Loc.show (F.Map.find name ots))
end;
let ta = TypeAssignment.{ skema = ty; loc; } in
F.Map.add name ta all_type_abbrevs,
F.Map.add name ta type_abbrevs,
F.Map.add name loc all_ty_names,
F.Map.add name loc ty_names)
(ota,F.Map.empty,ots,F.Map.empty) type_abbrevs in
let check_k_end = Unix.gettimeofday () in
let check_t_begin = Unix.gettimeofday () in
let merge k a b =
match a, b with
| _, Some (_,loc) -> Some loc
| Some _, _ -> a
| _ -> assert false in
let ty_names = F.Map.merge merge ty_names kinds in
let all_ty_names = F.Map.merge merge all_ty_names kinds in
let declarations = Type_checker.check_types ~errs ~stubs:flags.builtin_stubs ~type_abbrevs:all_type_abbrevs ~kinds:all_kinds types in
let all_types, types =
Errors.protect_fold_left ~errs (fun (all_types, types) d ->
Flatten.merge_type_assignments all_types d, TypingEnv.merge_envs types d)
(ot, TypingEnv.empty) declarations in
let toplevel_macros, all_toplevel_macros =
Errors.protect_fMap_fold ~errs (fun k m (tm, atm) ->
Type_checker.check_macro ~kinds:all_kinds ~type_abbrevs:all_type_abbrevs ~types:all_types k m;
F.Map.add k m tm, Flatten.merge_toplevel_macros ~errs all_types atm (F.Map.singleton k m))
toplevel_macros (F.Map.empty, otlm) in
let check_t_end = Unix.gettimeofday () in
{ Assembled.kinds; types; type_abbrevs; toplevel_macros; ty_names; namespaces },
{ Assembled.kinds = all_kinds; types = all_types; type_abbrevs = all_type_abbrevs; toplevel_macros = all_toplevel_macros; ty_names = all_ty_names;
namespaces = Namespaces.union ons namespaces },
(if flags.time_typechecking then check_t_end -. check_t_begin +. check_k_end -. check_k_begin else 0.0),
types
let is_global ~types { ScopedTerm.scope = symb' } symb =
match symb' with
| Scope.Global { resolved_to = x } ->
begin match SymbolResolver.resolved_to types x with
| Some symb' -> TypingEnv.same_symbol types symb symb'
| _ -> false
end
| _ -> false
let rec has_cut ~types = function
| { ScopedTerm.it = App(b,[]) } -> is_global ~types b Global_symbols.cut
| { ScopedTerm.it = App(_,args) } -> List.exists (has_cut ~types) args
| { ScopedTerm.it = Cast(x,_) } -> has_cut ~types x
| _ -> false
let check_clause ~errs ~flags ~det_check_time ~type_check_time ~unknown ~type_abbrevs ~kinds ~types ~as_written
({ Ast.Clause.body; needs_spilling; attributes = ({ Ast.Structured.typecheck; occur_check; autospill } as atts) } as clause) =
if not typecheck then unknown, Some { clause with needs_spilling = false; attributes = { atts with occur_check } }
else
match
Errors.protect errs ~default:None (fun () ->
Some (time_this type_check_time (fun () ->
Type_checker.check_rule ~errs ~unknown ~type_abbrevs ~kinds ~types ~auto_spill:autospill body ~exp:(Val (Prop Relation)))))
with
| None -> unknown, None
| Some (t, unknown, occur_check_pred) ->
let spilled =
if needs_spilling || autospill then begin
as_written := (clause.loc, t) :: !as_written;
Errors.protect errs ~default:None (fun () -> Some (Spilling.main_clause ~types ~type_abbrevs t))
end else Some t in
match spilled with
| None -> unknown, None
| Some t ->
let clause = { clause with body = t; needs_spilling = false; attributes = { atts with occur_check = occur_check && occur_check_pred } } in
if not flags.skip_det_checking then
Errors.protect errs ~default:() (fun () ->
time_this det_check_time (fun () -> Determinacy_checker.check_clause ~errs ~types ~unknown ~type_abbrevs clause.body));
unknown, Some clause
let check_chr_rule ~errs ~flags ~det_check_time ~type_check_time ~unknown ~type_abbrevs ~kinds ~types r =
match
Errors.protect errs ~default:None (fun () ->
Some (time_this type_check_time (fun () -> Type_checker.check_chr_rule ~unknown ~type_abbrevs ~kinds ~types r)))
with
| None -> unknown, None
| Some (r, unknown) ->
match
Errors.protect errs ~default:None (fun () ->
let guard = Option.map (Spilling.main_goal ~type_abbrevs ~types) r.guard in
let new_goal = Option.map (fun ({ Ast.Chr.conclusion } as x) -> { x with conclusion = Spilling.main_goal ~types ~type_abbrevs conclusion }) r.new_goal in
Some (guard, new_goal))
with
| None -> unknown, None
| Some (guard, new_goal) ->
if not flags.skip_det_checking then
Errors.protect errs ~default:() (fun () ->
time_this det_check_time (fun () ->
Option.iter (fun { Ast.Chr.conclusion } ->
Determinacy_checker.check_chr_guard_and_newgoal ~errs ~type_abbrevs ~types ~unknown ~guard ~newgoal:conclusion)
new_goal));
Errors.protect errs ~default:() (fun () ->
if Option.fold ~none:false ~some:(fun x -> has_cut ~types x.Ast.Chr.conclusion) r.new_goal then
error_chr ~loc:r.loc "CHR new goals cannot contain cut");
unknown, Some { r with guard; new_goal }
let check ~errs ~flags st ~base u : checked_compilation_unit =
let signature, precomputed_signature, check_sig, new_types = check_signature ~errs ~flags base.Assembled.signature u.code.Flat.signature in
let { version; code = { Flat.clauses; chr; builtins } } = u in
let { Assembled.kinds; types; type_abbrevs; toplevel_macros } = precomputed_signature in
let u_types = signature.types in
let type_check_time = ref 0.0 in
let det_check_time = ref 0.0 in
let builtins = builtins |> Option.map (fun file_name ->
let builtins, _ = declared_builtins ~file_name in
StrMap.fold (fun _ (BuiltInPredicate.(Pred(name,_,_) | ContextualPred(name,_,_,_))) acc ->
Errors.protect errs ~default:acc (fun () ->
let symb =
match TypingEnv.resolve_name (F.from_string name) new_types with
| Single s -> s
| Overloaded (s1::s2::_) ->
error_builtins ~loc:(Symbol.get_loc s2)
(Format.asprintf "Multiple signatures for builtin %s\nOther signature: %a" name Symbol.pp s1);
| Overloaded _ -> assert false
| exception Not_found ->
error_builtins (Format.asprintf "No signature declared for builtin %s" name) in
let { TypingEnv.indexing; availability } = TypingEnv.resolve_symbol symb new_types in
begin match availability with
| Ast.Structured.OCaml _ -> ()
| _ -> anomaly ~loc:(Symbol.get_loc symb) (Format.asprintf "Builtin predicate with no signature %s" name)
end;
(symb, name) :: acc)
) builtins [],
file_name) in
let types, u_types =
Option.fold ~some:(fun (bl,_) ->
List.fold_left (fun (t,ut) (s,_) ->
TypingEnv.set_as_implemented_in_ocaml t s, TypingEnv.set_as_implemented_in_ocaml ut s)
(types, u_types) bl)
~none:(types, u_types)
builtins in
let is_builtins_file = Option.is_some builtins in
if not flags.builtin_stubs then
TypingEnv.all_symbols u_types |> List.iter (fun (s, { TypingEnv.availability }) ->
match availability with
| Ast.Structured.OCaml (Builtin _ as p) ->
let name = Symbol.get_func s in
let is_global = D.Symbol.RawMap.mem (Symbol.make p name) D.Global_symbols.table.s2ct in
if not (is_global && is_builtins_file) && not (TypingEnv.resolve_symbol s types).implemented_in_ocaml then
Errors.protect errs ~default:() (fun () ->
error_builtins ~loc:(Symbol.get_loc s)
(Format.asprintf "%a is declared builtin but no MLCode implements it" F.pp name))
| _ -> ());
TypingEnv.iter_names (fun k -> function
| TypeAssignment.Single _ -> ()
| Overloaded l ->
Errors.protect errs ~default:() (fun () ->
let l = List.filter (fun x -> TypingEnv.(resolve_symbol x u_types).availability <> Elpi) l in
let l = List.filter (fun x ->
match Symbol.get_provenance x with
| Core | File _ -> false
| Builtin _ -> true) l in
if TypingEnv.undup u_types l |> List.length <> List.length l then
error_builtins ("Overloaded builtin symbol " ^ F.show k ^ " must be assigned different variants.\nDid you give each one its variant, symb ... = \"variant\"?"))
) u_types;
let as_written = ref [] in
let unknown, clauses = List.fold_left (fun (unknown,clauses) clause ->
match check_clause ~errs ~flags ~det_check_time ~type_check_time ~unknown ~type_abbrevs ~kinds ~types ~as_written clause with
| unknown, Some clause -> unknown, clause :: clauses
| unknown, None -> unknown, clauses) (F.Map.empty,[]) clauses in
let clauses = List.rev clauses in
let unknown, chr = List.fold_left (fun (unknown,chr_blocks) { Ast.Structured.clique; ctx_filter; rules; loc } ->
match
Errors.protect errs ~default:None (fun () ->
Some (List.map (Type_checker.check_pred_name ~types ~loc) clique,
List.map (Type_checker.check_pred_name ~types ~loc) ctx_filter))
with
| None -> unknown, chr_blocks
| Some (clique, ctx_filter) ->
let unknown, rules =
List.fold_left (fun (unknown, rules) r ->
match check_chr_rule ~errs ~flags ~det_check_time ~type_check_time ~unknown ~type_abbrevs ~kinds ~types r with
| unknown, Some r -> unknown, r :: rules
| unknown, None -> unknown, rules) (unknown, []) rules in
(unknown, { Ast.Structured.clique; ctx_filter; rules = List.rev rules; loc } :: chr_blocks)
) (unknown, []) chr in
let chr = List.rev chr in
TypingEnv.iter_symbols (fun k { TypingEnv.indexing; ty } ->
match SymbolMap.get_global_symbol base.Assembled.symbols k with
| Some c ->
Errors.protect errs ~default:() (fun () ->
if Builtins.is_declared base.Assembled.builtins c then
error_builtins ~loc:(Symbol.get_loc k)
(Format.asprintf "Ascribing a type to an already registered builtin %s" (Symbol.get_str k)))
| _ -> ()) new_types;
let more_types = time_this type_check_time (fun () -> Type_checker.check_undeclared ~errs:(Some errs) ~unknown ~type_abbrevs) in
let u_types = Flatten.merge_type_assignments u_types more_types in
let u_types =
let head_symbol (t : ScopedTerm.t) =
let hd = match t.it with ScopedTerm.Impl (R2L, _, hd, _) -> hd | _ -> t in
match hd.it with
| ScopedTerm.App ({ scope = Scope.Global { resolved_to }; _ }, _) -> SymbolResolver.resolved_to types resolved_to
| _ -> None in
let bodies = List.fold_left (fun bodies { Ast.Clause.body } ->
match head_symbol body with
| Some s when String.equal (Symbol.get_loc s).source_name body.loc.source_name ->
let loc = match Symbol.RawMap.find_opt s bodies with
| Some l -> Loc.extend_to l body.loc
| None -> body.loc in
Symbol.RawMap.add s loc bodies
| _ -> bodies) Symbol.RawMap.empty clauses in
Symbol.RawMap.fold (fun s loc t -> TypingEnv.set_body t s loc) bodies u_types in
let signature = { signature with types = u_types } in
let checked_code = { CheckedFlat.signature; clauses; chr; builtins; as_written = !as_written } in
{ version; checked_code; base_hash = hash_base base;
type_checking_time = if flags.time_typechecking then !type_check_time +. check_sig else 0.0;
det_checking_time = if flags.time_typechecking then !det_check_time else 0.0;
file_name = u.file_name;
digest = u.digest;
deps = u.deps;
}
end
let todopp name _fmt _ = compiler_error ("pp not implemented for field: "^name)
let get_argmap, set_argmap, _update_argmap =
let argmap =
State.declare
~name:"elpi:argmap" ~pp:(todopp "elpi:argmap")
~descriptor:D.elpi_state_descriptor
~clause_compilation_is_over:(fun _ -> F.Map.empty)
~compilation_is_over:(fun _ -> None)
~execution_is_over:(fun _ -> None)
~init:(fun () -> F.Map.empty)
() in
State.(get argmap, set argmap, update_return argmap)
module Assemble : sig
val extend : errs:Errors.t -> flags -> State.t -> Assembled.program -> checked_compilation_unit -> State.t * Assembled.program
val extend_signature : errs:Errors.t -> State.t -> Assembled.program -> checked_compilation_unit_signature -> State.t * Assembled.program
val compile_query : State.t -> Assembled.program -> bool * ScopedTerm.t -> SymbolMap.table * int F.Map.t * D.term
val compile_query_term :
State.t -> Assembled.program ->
?ctx:constant Scope.Map.t ->
?amap:constant F.Map.t ->
depth:int -> ScopedTerm.t -> constant F.Map.t * D.term
end = struct
let ErrorFun { error } = error_fun ~component:"Assemble"
let protect = Errors.protect
let update_indexing state symbols ({ idx } as index) (preds : (Symbol.t * pred_info) list) old_idx =
let check_if_some_clauses_already_in2 ~loc predicate c =
if Ptmap.mem c idx then
error ~loc @@ "Some rules for " ^ predicate ^
" are already in the program, changing the indexing a posteriori is not allowed."
in
let add_indexing_for name loc c (index:pred_info) map =
try
let old_tindex =
try C.Map.find c map
with Not_found -> C.Map.find c old_idx in
if not @@ same_indexing old_tindex index then
error ("multiple and inconsistent indexing attributes for " ^ name)
else map
with Not_found ->
check_if_some_clauses_already_in2 ~loc name c;
C.Map.add c index map
in
let map =
preds |> List.fold_left (fun acc (symb,(indexing:pred_info)) ->
match SymbolMap.get_global_symbol symbols symb with
| None -> acc
| Some c -> add_indexing_for (Symbol.get_str symb) (Symbol.get_loc symb) c indexing acc)
C.Map.empty
in
R.CompileTime.update_indexing map index, C.Map.union (fun _ a b -> assert (a=b); Some a) map old_idx
let lookup_global types symb state s =
match SymbolMap.get_global_symbol !symb s with
| None ->
let s, rc = SymbolMap.allocate_global_symbol state !symb s in
symb := s;
rc
| Some c ->
c, SymbolMap.get_canonical state !symb c;;
let allocate_global_symbol types symb state ~loc s c =
lookup_global types symb state @@
match SymbolResolver.resolved_to types s with
| Some s -> s
| None ->
match TypingEnv.resolve_name c types with
| TypeAssignment.Single s -> s
| TypeAssignment.Overloaded _ ->
error ~loc ("untyped and non allocated symbol " ^ F.show c)
| exception Not_found ->
error ~loc ("untyped and non allocated symbol " ^ F.show c)
let rec try_add_tail_cut ~types ({ ScopedTerm.it; loc } as orig) =
let open ScopedTerm in
let open Global_symbols in
let mkG x loc = const_of_symb ~types x ~loc in
let isG s1 = function Scope.Global { resolved_to = s } -> SymbolResolver.is_resolved_to types s s1 | _ -> false in
let conj ({ ScopedTerm.it; loc } as orig) =
let mk it = { it; loc; ty = TypeAssignment.(mkProp Function) } in
App(mkG and_ loc,[orig; mk @@ App(mkG cut loc,[])]) in
let rec append_list { ScopedTerm.it; loc } =
let mk it = { it; loc; ty = TypeAssignment.(mkProp Function) } in
let mkl it = { it; loc; ty = TypeAssignment.(mkList @@ Prop Function) } in
match it with
| App({ scope = s },[]) when isG nil s ->
App(mkG cons loc,[mk @@ App(mkG cut loc,[]);mkl @@ App(mkG nil loc,[])])
| App({ scope = s } as hd,[x;xs]) when isG cons s -> App(hd,[x;mk @@ append_list xs])
| _ -> raise (Failure "not a list") in
let append_list_or_conj h =
try append_list h
with Failure _ -> conj h in
let mk it = { it; loc; ty = TypeAssignment.(mkProp Function) } in
match it with
| Impl(R2L,lb,hd,hyp) -> Some (mk @@ Impl(R2L,lb,hd,mk @@ append_list_or_conj hyp))
| App({ scope = Scope.Global { resolved_to = s } },[]) when SymbolResolver.is_resolved_to types s nil -> Some orig
| App({ scope = Scope.Global { resolved_to = s } } as hd,[x;xs]) when SymbolResolver.is_resolved_to types s cons ->
begin match try_add_tail_cut ~types x, try_add_tail_cut ~types xs with
| Some x, Some xs -> Some (mk @@ App(hd,[x;xs]))
| _ -> None
end
| App({ scope = Scope.Global { resolved_to = s } } as hd,xs) when SymbolResolver.is_resolved_to types s and_ ->
let xs = List.map (try_add_tail_cut ~types) xs in
if List.for_all Option.is_some xs then
Some (mk @@ App(hd,List.map Option.get xs))
else None
| App({ scope = Scope.Global { resolved_to = s } } as hd,[{ it = Lam(v,ty,t) } as lam]) when SymbolResolver.is_resolved_to types s pi ->
begin match try_add_tail_cut ~types t with
| Some x -> Some (mk @@ App(hd,[{lam with it = Lam(v,ty,x)}]))
| _ -> None
end
| App _-> Some (mk @@ Impl(R2L,loc,orig,mk @@ App(const_of_symb ~types cut ~loc,[])))
| _ -> None
let to_dbl ?(ctx=Scope.Map.empty) ~types ~builtins state symb ?(depth=0) ?(amap = F.Map.empty) t =
let symb = ref symb in
let amap = ref amap in
let allocate_arg c =
try F.Map.find c !amap
with Not_found ->
let n = F.Map.cardinal !amap in
amap := F.Map.add c n !amap;
n
in
let allocate_fresh_arg () =
let n = F.Map.cardinal !amap in
let c = F.from_string (Printf.sprintf "%%Underscore%d" n) in
allocate_arg c
in
let lookup_bound loc (_,ctx) (c,l as x) =
try Scope.Map.find x ctx
with Not_found -> anomaly ~loc ("Unbound variable " ^ F.show c ^ if l <> elpi_language then " (language: "^l^")" else "" ^ " in context " ^ Scope.Map.(show Format.pp_print_int) ctx)
in
let allocate_bound_symbol loc ctx f =
let c = lookup_bound loc ctx f in
let s, rc = SymbolMap.allocate_bound_symbol state !symb c in
symb := s;
rc
in
let allocate_global_symbol = allocate_global_symbol types symb state in
let push_bound (n,ctx) c = (n+1,Scope.Map.add c n ctx) in
let push_unnamed_bound (n,ctx) = (n+1,ctx) in
let push ctx : ScopedTerm.binder option -> 'a = function
| None -> push_unnamed_bound ctx
| Some { scope = l; name = x } -> push_bound ctx (x,l) in
let open ScopedTerm in
let rec todbl (ctx : int * _ Scope.Map.t) t =
match t.it with
| Impl(b,_,t1,t2) ->
let t1, (b : builtin_predicate) =
match b with
| L2R -> t1, Impl
| R2L -> t1, RImpl
| L2RBang ->
match try_add_tail_cut ~types t1 with
| Some t1 -> t1, Impl
| None -> t1, ImplBang in
D.mkBuiltin b [todbl ctx t1;todbl ctx t2]
| CData c -> D.mkCData (CData.hcons c)
| Spill(t,_) ->
error ~loc:t.loc (Format.asprintf "todbl: term contains spill: %a" ScopedTerm.pretty t)
| Cast(t,_) -> todbl ctx t
| App({ scope = Global _; name = c },[]) when F.(equal c nilf) -> D.mkNil
| App({ scope = Global _; name = c },[x;y]) when F.(equal c consf) ->
let x = todbl ctx x in
let y = todbl ctx y in
D.mkCons x y
| App({ scope = Global { resolved_to }; name = c },[]) ->
let c, t = allocate_global_symbol ~loc:t.loc resolved_to c in
if is_builtin_predicate c then D.mkBuiltin (builtin_predicate_of_const c) []
else if Builtins.is_declared builtins c then D.mkBuiltin (Host c) []
else t
| App({ scope = Global { resolved_to }; name = c },x::xs) ->
let c,_ = allocate_global_symbol ~loc:t.loc resolved_to c in
let x = todbl ctx x in
let xs = List.map (todbl ctx) xs in
if is_builtin_predicate c then D.mkBuiltin (builtin_predicate_of_const c) (x::xs)
else if Builtins.is_declared builtins c then D.mkBuiltin (Host c) (x::xs)
else D.mkApp c x xs
| App({ scope = Bound l; name = c },[]) -> allocate_bound_symbol t.loc ctx (c,l)
| Lam(c,_,t) -> D.mkLam @@ todbl (push ctx c) t
| App({ scope = Bound l; name = c },x::xs) ->
let c = lookup_bound t.loc ctx (c,l) in
let x = todbl ctx x in
let xs = List.map (todbl ctx) xs in
D.mkApp c x xs
| UVar({ name = c },xs) ->
let xs = List.map (todbl ctx) xs in
R.mkAppArg (allocate_arg c) 0 xs
| Discard { heapify = false } -> D.mkDiscard
| Discard { heapify = true } ->
let xs =
Scope.Map.bindings (snd ctx) |>
List.map (fun (k,_) -> allocate_bound_symbol t.loc ctx k) in
R.mkAppArg (allocate_fresh_arg ()) 0 xs
in
let t = todbl (depth,ctx) t in
(!symb, !amap), t
let check_mut_excl state symbols ~loc pred_info cl cl_st (oc: overlap_clause option) p amap : pred_info C.Map.t =
let pp_global_predicate fmt p =
let f = SymbolMap.global_name state symbols p in
Format.fprintf fmt "predicate %a" F.pp f in
let preds_w_eigen_var_no_cut = ref C.Map.empty in
let add_pred_w_eigen_var_no_cut pred loc =
preds_w_eigen_var_no_cut := C.Map.add pred loc !preds_w_eigen_var_no_cut
in
let fresh_locs = ref [] in
let get_fresh_loc =
let n = ref 0 in
fun loc ->
incr n;
let fresh = Loc.extend !n loc in
fresh_locs := (fresh, loc) :: !fresh_locs;
fresh in
let shown loc =
match List.find_opt (fun (fresh, _) -> Loc.equal fresh loc) !fresh_locs with
| Some (_, loc) -> loc
| None -> loc in
let error ?loc msg = error ?loc:(Option.map shown loc) msg in
let runtime_tick =
let tick = ref 0 in
fun () -> decr tick; !tick
in
let get_opt x = Constants.Map.find_opt x pred_info in
let can_overlap x = match get_opt x with
| Some { overlap = Allowed } -> true
| Some { overlap = Forbidden _ } -> false
| _ -> true
in
let get_info x = match get_opt x with
| Some {mode; overlap} ->
let indexed_args =
match overlap with
| Forbidden d -> Discrimination_tree.user_upper_bound_depth d
| Allowed -> []
in
mode, indexed_args
| None -> [], [] in
let get_overlapping (_, pred_info) c query =
match pred_info with
| { overlap = Allowed } -> []
| { overlap = Forbidden dt } ->
R.CompileTime.get_clauses ~depth:0 query dt |> Bl.to_list
in
let rec to_heap ~depth t =
match t with
| Builtin (x, xs) -> Builtin (x, List.map (to_heap ~depth) xs)
| App (h,x,xs) -> App (h, (to_heap ~depth) x, List.map (to_heap ~depth) xs)
| Const x -> t
| Lam t -> Lam ((to_heap ~depth) t)
| (Nil | CData _ | Discard | AppUVar _ | UVar _) -> t
| Arg _ -> UVar (R.CompileTime.fresh_uvar ~depth,0)
| AppArg (_, args) -> AppUVar (R.CompileTime.fresh_uvar ~depth, List.map (to_heap ~depth) args)
| Cons (a, b) -> Cons ((to_heap ~depth) a, (to_heap ~depth) b)
in
let pretty_term ~depth =
let pp_ctx = ({ uv_names = ref (IntMap.empty,0); table = SymbolMap.compile symbols }) in
R.Pp.uppterm ~pp_ctx depth [] ~argsdepth:0 [||] in
let error_overlapping ~loc ~is_local pred overlaps (cl_st,depth : term * int) =
let local = if is_local then "local " else "" in
let to_str fmt x =
match x.overlap_loc with
| None -> Format.fprintf fmt "- anonymous rule"
| Some loc2 when Loc.equal loc loc2 -> Format.fprintf fmt "- @[<v 0>itself at %a@,did you accumulate %s twice?@]" Loc.pp (shown loc2) (Filename.basename loc2.Loc.source_name)
| Some loc2 -> Format.fprintf fmt "- rule at %a" Loc.pp (shown loc2)
in
error ~loc (Format.asprintf "@[<v 0>Mutual exclusion violated for rules of %a.@,@[Offending rule is:@ @[<hov 2>%a@]@]@,This %srule overlaps with:@ %a@]@ @[This may break the determinacy of the predicate. To solve the problem you may want to add a cut in the body of the rule that appears first.@]@ @]"
pp_global_predicate pred
(pretty_term ~depth) cl_st
local
(pplist to_str " ") overlaps)
in
let error_overlapping_eigen_variables ~loc pred (cl_st,depth : term * int) =
error ~loc (Format.asprintf "@[<v 0>Mutual exclusion violated for rules of %a.@,This rule (displayed below) does not respects the principles of mutual exclution@]@ @[Principles: there is a cut in the body of the local rule and/or all indexed input arguments are eigenvariables@] @[To solve the problem you may want to add a cut in the body of the rule that appears first.@]@ @[Offending rule:@ @[<hov 2>%a@]@] @]" pp_global_predicate pred
(pretty_term ~depth) cl_st)
in
let is_eigen_variable ~min_depth ~depth = function
| Const b -> min_depth <= b && b < depth
| _ -> false
in
let rec is_unif_var = function
| AppUVar _ | UVar (_, _) | Discard | Arg (_, _)|AppArg (_, _) -> true
| App (h,x,xs) when h == Global_symbols.asc -> is_unif_var x && List.for_all is_unif_var xs
| Nil|Const _|Lam _|App (_, _, _)|Cons (_, _)|Builtin (_, _)|CData _ -> false
in
let hd_query ~loc ~depth ~min_depth p args =
let mode, indexed_args = get_info p in
let rig_occ = ref true in
let has_input = ref false in
let is_catchall = ref true in
let update_bools m t =
has_input := !has_input || m;
rig_occ := !rig_occ && (is_eigen_variable ~min_depth ~depth t);
is_catchall := !is_catchall && is_unif_var t
in
let remove_as = function
| App(c,a,_) when c == Global_symbols.asc -> a
| x -> x in
let rec mkpats indexed_args args mode =
match indexed_args, args, mode with
| _, [], [] -> []
| i::is, a::args, (Mode.Fo Input | Ho(Input,_)) :: mode when i > 0 ->
update_bools true a;
remove_as a :: mkpats is args mode
| (([] as is) | (_::is)), _::args, _ :: mode -> mkDiscard :: mkpats is args mode
| (([] as is) | (_::is)), _::args, [] -> mkDiscard :: mkpats is args mode
| _ -> assert false
in
(not !has_input || !rig_occ), (not !has_input || !is_catchall), R.mkAppL p @@ mkpats indexed_args args mode
in
let check_overlaps ~is_local ~loc ~min_depth ~depth (cl:clause) h (cl_overlap:overlap_clause option) p args (index : int * pred_info) =
match cl_overlap with
| None -> ()
| Some cl_overlap ->
let rec filter_overlaps (arg_nb:int) : overlap_clause list -> 'a list = function
| [] -> []
| x::xs when x.timestamp = cl.timestamp ->
if x.has_cut then [] else xs
| x::xs ->
if not x.has_cut && arg_nb = x.arg_nb then (x::filter_overlaps arg_nb xs)
else filter_overlaps arg_nb xs
in
let all_input_eigen_vars, all_input_catchall, hd = hd_query ~loc ~min_depth ~depth p args in
if is_local && not cl_overlap.has_cut && not all_input_eigen_vars then (
error_overlapping_eigen_variables ~loc p h);
if not is_local && all_input_catchall then
(match get_opt p with
| None | Some {has_local_without_cut = None} -> ()
| Some {has_local_without_cut = (Some _) as loc1} ->
error_overlapping ~is_local ~loc p [{ overlap_loc = loc1; timestamp =[]; has_cut = false; arg_nb = 0 }] h);
if is_local && not cl_overlap.has_cut && all_input_eigen_vars then
add_pred_w_eigen_var_no_cut p (shown loc);
if not is_local || (is_local && not cl_overlap.has_cut) then
let all_overlapping = get_overlapping index p hd in
let overlapping = filter_overlaps cl_overlap.arg_nb all_overlapping in
if overlapping <> [] then error_overlapping ~loc ~is_local p overlapping h
in
let rec check_local ~min_depth ~depth ~loc ~lcs index amap (t : term) : unit =
let t = to_heap ~depth t in
let rec aux ~min_depth ~depth (index: pred_info C.Map.t) t =
match t with
| Builtin (Cut, []) -> ()
| Builtin (Pi, [Lam b]) -> aux ~min_depth ~depth:(depth+1) index b
| Builtin (Sigma, [Lam b]) ->
let uvar = UVar(R.CompileTime.fresh_uvar ~depth,0) in
let b = Runtime.subst ~depth [uvar] b in
aux ~min_depth ~depth:(depth+1) index b
| Builtin ((Impl| ImplBang), [Nil; l])
| Builtin ((Impl| ImplBang), [Builtin(And,[]); l]) -> aux ~min_depth ~depth index l
| Builtin ((Impl| ImplBang as ik), [Cons(h,hl); l]) ->
aux ~min_depth ~depth index (Builtin (ik, [h; Builtin(ik,[hl; l])]))
| Builtin ((Impl| ImplBang as ik), [Builtin(And,h::hl); l]) ->
aux ~min_depth ~depth index (Builtin (ik, [h; Builtin(ik,[Builtin(And,hl); l])]))
| Builtin ((Impl | ImplBang as ik), [h; l]) ->
begin try
let fresh_loc = get_fresh_loc loc in
let (p,cl), _, morelcs =
try R.CompileTime.clausify1 ~tail_cut:(ik = ImplBang) ~loc:fresh_loc ~modes:(fun x -> fst (get_info x)) ~nargs:(F.Map.cardinal amap) ~depth h
with
| D.CannotDeclareClauseForBuiltin(loc,c) ->
error ?loc ("Declaring a rule for built predicate:" ^ show_builtin_predicate (fun ?table x -> F.show @@ SymbolMap.global_name state symbols x) c)
| D.CompileTimeError(loc,msg) -> error ?loc msg
in
let cl_overlap, index =
try R.Indexing.add1clause_overlap_runtime ~depth ~time:(runtime_tick ()) index p cl
with D.CompileTimeError(loc,msg) -> error ?loc msg in
check_clause ~min_depth ~is_local:true ~depth ~loc:fresh_loc ~lcs:morelcs index cl h cl_overlap p amap;
aux ~min_depth ~depth index l
with
| ElpiError _ as e -> raise e
| Flex_head -> aux ~min_depth ~depth index l end
| Builtin (RImpl, [l; h]) -> aux ~min_depth ~depth index (Builtin (Impl, [h; l]))
| Builtin (And, l) ->
List.iter (aux ~min_depth ~depth index) l
| _ -> ()
in
aux ~min_depth ~depth index t
and check_clause ~min_depth ~is_local ~depth ~loc ~lcs index cl h cl_overlap p amap =
if not @@ can_overlap p then check_overlaps ~is_local ~loc ~min_depth ~depth cl (h,depth) cl_overlap p cl.args (0, C.Map.find p index);
List.iter (check_local ~min_depth:depth ~loc ~depth ~lcs index amap) cl.hyps
in
check_clause ~min_depth:0 ~loc ~is_local:false ~lcs:0 ~depth:0 pred_info cl cl_st oc p amap;
let pred_info = C.Map.fold (fun k v -> C.Map.add k {(C.Map.find k pred_info) with has_local_without_cut = Some v}) !preds_w_eigen_var_no_cut pred_info in
pred_info
let spill_todbl ?(ctx=Scope.Map.empty) ~builtins ~needs_spilling ~type_abbrevs ~types state symb ?(depth=0) ?(amap = F.Map.empty) t =
let t = if needs_spilling then Spilling.main_goal ~types ~type_abbrevs t else t in
to_dbl ~ctx ~builtins state symb ~types ~depth ~amap t
let extend1_clause ~errs ~time flags state ~builtins ~types ((clauses, symbols, index, pred_info) as acc) ({ Ast.Clause.body = body_st; loc; needs_spilling; attributes = { Ast.Structured.insertion = graft; id; ifexpr; occur_check } } : _ Ast.Clause.t) =
protect errs ~default:acc @@ fun () ->
assert (not needs_spilling);
if not @@ filter1_if flags (fun x -> x) ifexpr then
(clauses,symbols, index, pred_info)
else
let (symbols, amap), body = to_dbl ~builtins ~types state symbols body_st in
let modes x = (Constants.Map.find_opt x pred_info) |> Option.fold ~some:(fun (x : pred_info) -> x.mode) ~none:[] in
let (p,cl), _, morelcs =
try R.CompileTime.clausify1 ~tail_cut:false ~loc ~modes ~nargs:(F.Map.cardinal amap) ~depth:0 body
with
| D.CannotDeclareClauseForBuiltin(loc,_c) ->
error ?loc ("Declaring a rule for built in predicate")
| D.CompileTimeError(loc,msg) -> error ?loc msg
in
if morelcs <> 0 then error ~loc "sigma in a toplevel rule is not supported";
let cl =
if occur_check then cl
else { cl with oc = false } in
let p_info =
try C.Map.find p pred_info
with Not_found -> error ~loc ("No signature declaration for " ^ F.show (SymbolMap.global_name state symbols p) ^ ". Did you forget to accumulate a file?") in
let index, (overlap_clause, p_info) =
try R.CompileTime.add_to_index ~det_check:(if flags.skip_det_checking then None else Some time) ~depth:0 ~predicate:p ~graft cl id index p_info
with D.CompileTimeError(loc,msg) -> error ?loc msg in
let pred_info = C.Map.add p p_info pred_info in
let pred_info = ref pred_info in
if not flags.skip_det_checking then
time_this time (fun () ->
pred_info := protect errs ~default:!pred_info (fun () ->
check_mut_excl state symbols ~loc !pred_info cl body overlap_clause p amap));
(graft,id,p,cl) :: clauses, symbols, index, !pred_info
let check_rule_pattern_in_clique state symbols clique { D.CHR.pattern; rule_name; rule_loc } =
try
let outside =
List.find (fun x -> not (D.CHR.in_clique clique x)) pattern in
error ~loc:rule_loc ("CHR rule " ^ rule_name ^ ": matches " ^ (F.show @@ SymbolMap.global_name state symbols outside) ^
" which is not a constraint on which it is applied. Check the list of predicates after the \"constraint\" keyword.");
with Not_found -> ()
let extend1_chr flags state clique ~builtins ~types (symbols,chr) { Ast.Chr.to_match; to_remove; guard; new_goal; attributes; loc } =
if not @@ filter1_if flags (fun x -> x.Ast.Structured.cifexpr) attributes then
(symbols,chr)
else
let todbl state (symbols,amap) t = to_dbl ~types ~builtins state symbols ~amap t in
let sequent_todbl state st { Ast.Chr.eigen; context; conclusion } =
let st, eigen = todbl state st eigen in
let st, context = todbl state st context in
let st, conclusion = todbl state st conclusion in
st, { CHR.eigen; context; conclusion } in
let st = symbols, F.Map.empty in
let st, to_match = map_acc (sequent_todbl state) st to_match in
let st, to_remove = map_acc (sequent_todbl state) st to_remove in
let st, guard = option_mapacc (todbl state) st guard in
let st, new_goal = option_mapacc (sequent_todbl state) st new_goal in
let symbols, amap = st in
let key_of_sequent { CHR.conclusion } =
match conclusion with
| Const x -> x
| App(x,_,_) -> x
| _ -> error ~loc "CHR: rule without head symbol" in
let all_sequents = to_match @ to_remove in
let pattern = List.map key_of_sequent all_sequents in
let rule_name = attributes.Ast.Structured.cid in
let patsno = List.(length to_match + length to_remove) in
let nargs = F.Map.cardinal amap in
let rule = { CHR.to_match; nargs; to_remove; guard; new_goal; patsno; pattern; rule_name; rule_loc = loc } in
check_rule_pattern_in_clique state symbols clique rule;
symbols, CHR.add_rule clique rule chr
let extend1_chr_block ~errs flags state ~builtins ~types (symbols,chr) { Ast.Structured.clique; ctx_filter; rules; loc } =
let allocate_global_symbol state symbols f =
let symbols = ref symbols in
let resolved_to =
let r = SymbolResolver.make () in
SymbolResolver.resolve types r f;
r in
let (c,_) = allocate_global_symbol types symbols state ~loc resolved_to (Symbol.get_func f) in
!symbols, c in
let symbols, clique = map_acc (allocate_global_symbol state) symbols clique in
let symbols, ctx_filter = map_acc (allocate_global_symbol state) symbols ctx_filter in
let chr, clique = CHR.new_clique (SymbolMap.global_name state symbols) ctx_filter clique chr in
List.fold_left (fun acc r ->
protect errs ~default:acc (fun () ->
extend1_chr ~builtins ~types flags state clique acc r)) (symbols,chr) rules
let extend1_signature ~errs base_signature ({ signature } : checked_compilation_unit_signature) =
let { Assembled.kinds = ok; types = ot; type_abbrevs = ota; toplevel_macros = otlm; ty_names = ots; namespaces = ons } = base_signature in
let { Assembled.toplevel_macros; kinds; types; type_abbrevs; ty_names; namespaces } = signature in
let kinds = Flatten.merge_kinds ~errs ok kinds in
F.Map.iter (fun k TypeAssignment.{ loc; } -> if F.Map.mem k ots && not (Loc.equal loc (F.Map.find k ots)) then error ~loc ("Illegal type abbreviation for " ^ F.show k ^ ". A type with the same name already exists in " ^ Loc.show (F.Map.find k ots))) type_abbrevs;
let type_abbrevs = Flatten.merge_checked_type_abbrevs ~errs ota type_abbrevs in
let types = Flatten.merge_type_assignments ot types in
let toplevel_macros = Flatten.merge_toplevel_macros ~errs types otlm toplevel_macros in
let merge _ _ b = Some b in
let ty_names = F.Map.union merge ots ty_names in
let namespaces = Namespaces.union ons namespaces in
{ Assembled.kinds; types; type_abbrevs; toplevel_macros; ty_names; namespaces }
let new_symbols_of_types ~(base_sig:Assembled.signature) new_types =
let symbs = TypingEnv.all_symbols new_types in
symbs |> List.filter_map (fun (symb,m) -> if TypingEnv.mem_symbol base_sig.types symb then None else Some symb),
symbs |> List.filter_map (fun (symb, { TypingEnv.indexing } ) -> match indexing with Index m -> Some (symb, m) | _ -> None)
let allocate_new_symbols state ~symbols ~new_defined_symbols =
List.fold_left (fun symbols s -> SymbolMap.allocate_global_symbol state symbols s |> fst)
symbols new_defined_symbols
let extend1 ~errs flags (state, base) unit =
match
protect errs ~default:None (fun () ->
Some (extend1_signature ~errs base.Assembled.signature (signature_of_checked_compilation_unit unit)))
with
| None -> state, base
| Some signature ->
let { Assembled.hash; clauses = cl; symbols; prolog_program; indexing; signature = bsig; chr = ochr; builtins = ob; total_type_checking_time; total_det_checking_time } = base in
let { version; base_hash; checked_code = { CheckedFlat.clauses; chr; builtins; signature = { types = new_types } }; type_checking_time; det_checking_time } = unit in
let new_defined_symbols, new_indexable = new_symbols_of_types ~base_sig:bsig new_types in
let symbols = allocate_new_symbols state ~symbols ~new_defined_symbols in
let prolog_program, indexing = update_indexing state symbols prolog_program new_indexable indexing in
let symbols, builtins =
Option.fold ~some:(fun (builtins,file_name) ->
let bm, _ = declared_builtins ~file_name in
List.fold_left (fun (symbols,builtins) (symb, name) ->
let p = StrMap.find name bm in
let symbols, (c,_) = SymbolMap.allocate_global_symbol state symbols symb in
let builtins = Builtins.register builtins p c in
symbols, builtins) (symbols, ob) builtins)
~none:(symbols, ob) builtins
in
let symbols, chr =
List.fold_left (extend1_chr_block ~errs ~builtins ~types:signature.types flags state) (symbols,ochr) chr in
let mutexcl_time = ref 0.0 in
let clauses, symbols, prolog_program, indexing =
List.fold_left (extend1_clause ~errs ~time:mutexcl_time ~builtins ~types:signature.types flags state) (cl, symbols, prolog_program, indexing) clauses in
let mutexcl_time = if flags.time_typechecking then !mutexcl_time else 0.0 in
let total_type_checking_time = total_type_checking_time +. type_checking_time in
let total_det_checking_time = total_det_checking_time +. det_checking_time +. mutexcl_time in
let state =
Option.fold ~none:state ~some:(fun (_,file_name) ->
let _, decls = declared_builtins ~file_name in
List.fold_left (fun state -> function
| BuiltInPredicate.MLCalc ops ->
D.State.update CalcHooks.eval state (fun m ->
List.fold_left (fun m (c,{ CalcHooks.code }) -> Constants.Map.add c code m) m ops)
| _ -> state) state decls) unit.checked_code.CheckedFlat.builtins in
let base = { Assembled.builtins; hash; symbols; chr; clauses; prolog_program; signature; indexing; total_type_checking_time; total_det_checking_time } in
let hash = hash_base base in
state, { base with hash }
let extend ~errs flags state assembled u = extend1 ~errs flags (state, assembled) u
let extend_signature ~errs state assembled u =
match
protect errs ~default:None (fun () ->
Some (extend1_signature ~errs assembled.Assembled.signature u))
with
| None -> state, assembled
| Some signature ->
let base_sig = assembled.Assembled.signature in
let new_defined_symbols, new_indexable = new_symbols_of_types ~base_sig signature.types in
let symbols = allocate_new_symbols state ~symbols:assembled.symbols ~new_defined_symbols in
let prolog_program, indexing = update_indexing state symbols assembled.prolog_program new_indexable assembled.indexing in
let base = { assembled with symbols; prolog_program; indexing; signature } in
state, { base with hash = hash_base base }
let compile_query state { Assembled.symbols; builtins; signature = { types; type_abbrevs } } (needs_spilling,t) =
let (symbols, amap), t = spill_todbl ~builtins ~needs_spilling ~types ~type_abbrevs state symbols t in
symbols, amap, t
let compile_query_term state { Assembled.symbols; builtins; signature = { types; type_abbrevs } } ?ctx ?(amap = F.Map.empty) ~depth t =
let (symbols', amap), rt = spill_todbl ~builtins ?ctx ~needs_spilling:false state symbols ~types ~type_abbrevs ~depth ~amap t in
if SymbolMap.same_constants symbols' symbols then amap, rt
else error ~loc:t.ScopedTerm.loc "cannot allocate new symbols in the query"
end
let check_user_declarations ~errs (p : Ast.Program.t) =
let check ({ Ast.Type.attributes; loc; name } : _ Ast.Type.t) =
attributes |> List.iter (function
| Ast.External (Some "core") ->
Errors.protect errs ~default:() (fun () ->
compiler_error ~loc (F.show name ^ ": only builtin.elpi declares the symbols of the language (= \"core\")"))
| Ast.External (Some _) ->
Errors.protect errs ~default:() (fun () ->
compiler_error ~loc (F.show name ^ ": = \"variant\" is only for the text of an OCaml builtins declaration, where it picks one of its OCaml symbols (MLData, MLConstants)"))
| _ -> ()) in
let rec aux l = l |> List.iter (function
| Ast.Program.Type l -> List.iter check l
| Ast.Program.Pred t -> check t
| Ast.Program.Accumulated (_, l) ->
List.iter (fun { Ast.ast; file_name } -> if not (is_plugin_unit file_name) then aux ast) l
| _ -> ()) in
aux p.Ast.ast
let rec bind_plugin_units (p : Ast.Program.t) =
let ast = p.Ast.ast |> List.map (function
| Ast.Program.Accumulated (loc, l) ->
Ast.Program.Accumulated (loc, l |> List.map (fun (x : Ast.Program.t) ->
if is_plugin_unit x.file_name then bind_builtins ~file_name:x.file_name x
else bind_plugin_units x))
| d -> d) in
{ p with ast }
let scope ~errs ?(user_text=false) s ~toplevel_macros ~builtins p : scoped_program list =
if user_text then check_user_declarations ~errs p;
let p = bind_plugin_units p in
let pl = RecoverStructure.run ~errs s p in
pl |> List.map (fun { Ast.ast = p; digest; deps; file_name} ->
let p = Scope_Quotation_Macro.run ~errs ~toplevel_macros s p in
{
version = "4.1.1";
code = p;
builtins = if is_plugin_unit file_name then Some file_name else builtins;
file_name;
digest;
deps;
})
let ~errs ~(base : Assembled.program) s (p : scoped_program) : unchecked_compilation_unit =
assert ("4.1.1" = p.version);
let f = Flatten.run ~errs ~base:base.Assembled.signature s p.code in
{
version = "4.1.1";
code = { f with builtins = p.builtins };
file_name = p.file_name;
digest = p.digest;
deps = p.deps;
}
;;
let print_unit { print_units } x =
if print_units then
let b1 = Marshal.to_bytes x.code [] in
Printf.eprintf "UNIT %s:\n size: %5dk clauses: %5d builtins: %5d digest: 0x%s\n deps: %s\n\n%!"
x.file_name
(Bytes.length b1 / 1024) (List.length x.code.Flat.clauses)
(Option.fold ~none:0 ~some:(fun file_name -> List.length (declared_builtins ~file_name |> snd)) x.code.Flat.builtins)
(Digest.to_hex x.digest)
(if x.deps <> [] then "\n - " ^ String.concat "\n - "
(List.mapi (fun i (f,d) -> Printf.sprintf "%d: %s, digest: 0x%s" (i+1) f (Digest.to_hex d)) x.deps) else "none")
;;
let with_errors ~flags f =
let errs = Errors.make ~max_errors:flags.max_errors () in
let r = f errs in
r, Errors.list errs, Errors.warnings errs
let without_errors f =
match first_error f with
| Ok r, _ -> r
| Error { component; loc; message }, _ ->
let ErrorFun { error } = error_fun ~component in
error ?loc message
let scoped_units_of_builtins ~flags ~header:(s,u) builtins =
let parser = Option.get @@ D.State.get parser s in
let builtins_src = ast_of_builtins ~stubs:flags.builtin_stubs ~parser ~file_name:builtins in
without_errors (fun errs -> scope ~errs ~toplevel_macros:u.Assembled.signature.toplevel_macros s ~builtins:(Some builtins) builtins_src)
let scoped_of_builtins ~flags ~ builtins =
match scoped_units_of_builtins ~flags ~header builtins with
| [x] -> x
| _ -> builtins_error ~loc:(Util.Loc.initial builtins)
(Printf.sprintf "the text of the builtins %s accumulates files: it is not one unit" builtins)
let pp_error = Compiler_data.pp_error
let pp_error_message = Compiler_data.pp_error_message
let show_error = Compiler_data.show_error
let rec units (p : Ast.Program.t) =
let ast = p.Ast.ast |> List.map (function
| Ast.Program.Accumulated (loc, l) ->
Ast.Program.Accumulated (loc, l |> List.filter_map (fun (x : Ast.Program.t) ->
if StrSet.mem x.digest units then None else Some (drop_header_units units x)))
| d -> d) in
{ p with ast }
let scoped_of_ast ~flags ~header:(s,u) p =
let units = D.State.get header_units s in
let sp = StrSet.mem (scoped_program_digest sp) units in
let p = drop_header_units units p in
with_errors ~flags (fun errs ->
scope ~errs ~user_text:(not flags.builtin_stubs) ~toplevel_macros:u.Assembled.signature.toplevel_macros s ~builtins:None p
|> List.filter (fun sp -> not (in_header sp)))
let ~flags ~parser:p state_descriptor quotation_descriptor hoas_descriptor builtins : header =
let state = D.State.(init (merge_descriptors D.elpi_state_descriptor state_descriptor)) in
let state =
match hoas_descriptor.D.HoasHooks.extra_goals_postprocessing with
| Some x ->
D.State.set D.Conversion.extra_goals_postprocessing state x
| None -> state in
let { Compiler_data.QuotationHooks.default_quotation;
named_quotations;
singlequote_compilation;
backtick_compilation } = quotation_descriptor in
let state = D.State.set CustomFunctorCompilation.backtick state backtick_compilation in
let state = D.State.set CustomFunctorCompilation.singlequote state singlequote_compilation in
let state = D.State.set Quotation.default_quotation state default_quotation in
let state = D.State.set Quotation.named_quotations state named_quotations in
let state = D.State.set parser state (Some p) in
let state = D.State.set D.while_compiling state true in
let base = Assembled.empty () in
let seen = ref StrSet.empty in
builtins |> List.fold_left (fun builtins ->
scoped_units_of_builtins ~flags ~header builtins |> List.fold_left (fun (state,base as ) scoped ->
let digest = scoped_program_digest scoped in
if StrSet.mem digest !seen then header else begin
seen := StrSet.add digest !seen;
let u = without_errors (fun errs -> unit_or_header_of_scoped ~errs ~base state scoped) in
print_unit flags u;
let u = without_errors (fun errs -> Check.check ~errs ~flags state ~base u) in
let h = without_errors (fun errs -> Assemble.extend ~errs flags state base u) in
h end) header)
(state,base)
|> fun (state, base) -> D.State.set header_units state !seen, base
let empty_base ~header:b = b
let unit_of_scoped ~flags ~header:(s, u) p : unchecked_compilation_unit * error list * warning list =
with_errors ~flags (fun errs ->
let u = unit_or_header_of_scoped ~errs ~base:u s p in
print_unit flags u;
u)
let check_unit ~flags ~base:(st,base) u : checked_compilation_unit * error list * warning list =
with_errors ~flags (fun errs -> Check.check ~errs ~flags st ~base u)
let append_unit ~flags ~base:(s,p) unit : program * error list * warning list =
with_errors ~flags (fun errs -> Assemble.extend ~errs flags s p unit)
let append_unit_signature ~flags ~base:(s,p) unit : program * error list * warning list =
with_errors ~flags (fun errs -> Assemble.extend_signature ~errs s p unit)
let compile_unit ~flags ~ ~base:(st,base) scoped : checked_compilation_unit * error list * warning list =
let (s, _) = header in
with_errors ~flags (fun errs ->
let u = unit_or_header_of_scoped ~errs ~base s scoped in
print_unit flags u;
Check.check ~errs ~flags st ~base u)
let program_of_ast ~flags ~header:( : State.t * Assembled.program) p : program * error list * warning list =
let units = D.State.get header_units (fst header) in
let p = drop_header_units units p in
with_errors ~flags (fun errs ->
let pl = scope ~errs ~user_text:(not flags.builtin_stubs) ~toplevel_macros:(snd header).Assembled.signature.toplevel_macros (fst header) ~builtins:None p in
let , _ =
pl |> List.fold_left (fun ((, seen) as acc) (p : scoped_program) ->
if StrSet.mem p.digest seen then acc
else
Errors.protect errs ~default:acc (fun () ->
let (st, base) = header in
let u = unit_or_header_of_scoped ~errs ~base st p in
print_unit flags u;
let u = Check.check ~errs ~flags st ~base u in
Assemble.extend ~errs flags st base u, StrSet.add p.digest seen))
(header, units) in
header)
let total_type_checking_time { WithMain.total_type_checking_time = x } = x
let total_det_checking_time { WithMain.total_det_checking_time = x } = x
let pp_uvar_body fmt ub = R.Pp.uppterm 0 [] ~argsdepth:0 [||] fmt (D.mkUVar ub 0)
let pp_uvar_body_raw fmt ub = R.Pp.ppterm 0 [] ~argsdepth:0 [||] fmt (D.mkUVar ub 0)
let uvk = D.State.declare ~descriptor:D.elpi_state_descriptor ~name:"elpi:uvk" ~pp:(Util.StrMap.pp pp_uvar_body)
~clause_compilation_is_over:(fun x -> Util.StrMap.empty)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun _ -> None)
~init:(fun () -> Util.StrMap.empty)
()
let compile_builtins b =
let builtins = Hashtbl.create 17 in
let () = Builtins.fold (fun c p () -> Hashtbl.add builtins c p) b () in
builtins
let query_of_ast (compiler_state, assembled_program) t state_update =
first_error @@ fun errs ->
let compiler_state = State.begin_goal_compilation compiler_state in
let { Assembled.signature = { kinds; types; type_abbrevs; toplevel_macros; }; chr; prolog_program; total_type_checking_time } = assembled_program in
let total_type_checking_time = assembled_program.Assembled.total_type_checking_time in
let total_det_checking_time = assembled_program.Assembled.total_det_checking_time in
let needs_spilling = ref false in
let t = Scope_Quotation_Macro.scope_loc_term ~state:(set_mtm compiler_state { empty_mtm with macros = toplevel_macros; needs_spilling }) t in
let t, unknown = Type_checker.check_query ~unknown:F.Map.empty ~type_abbrevs ~kinds ~types t ~exp:TypeAssignment.(Val (Prop Relation)) in
let _ : TypingEnv.t = Type_checker.check_undeclared ~errs:(Some errs) ~unknown ~type_abbrevs in
let symbols, amap, query = Assemble.compile_query compiler_state assembled_program (!needs_spilling,t) in
let query_env = Array.make (F.Map.cardinal amap) D.dummy in
let initial_goal = R.move ~argsdepth:0 ~from:0 ~to_:0 query_env query in
let assignments = F.Map.fold (fun k i m -> StrMap.add (F.show k) query_env.(i) m) amap StrMap.empty in
let assignments = StrMap.fold (fun k i m -> StrMap.add k (UVar(i,0)) m) (State.get uvk compiler_state) assignments in
let builtins = assembled_program.Assembled.builtins in
{
WithMain.prolog_program;
chr;
symbols;
initial_goal;
assignments;
compiler_state = compiler_state |> state_update;
total_type_checking_time;
total_det_checking_time;
builtins;
runtime_types = Type_checker.compile_for_runtime types;
}
let compile_term_to_raw_term ?(check=true) state (_, assembled_program) ?ctx ~depth t =
if not @@ State.get Data.while_compiling state then
anomaly "compile_term_to_raw_term called at run time";
let { Assembled.signature = { kinds; types; type_abbrevs }; chr; prolog_program; total_type_checking_time } = assembled_program in
let t = if check && Option.fold ~none:true ~some:Scope.Map.is_empty ctx then begin
let t, unknown = Type_checker.check_query ~unknown:F.Map.empty ~type_abbrevs ~kinds ~types t ~exp:(Type_checker.unknown_type_assignment "Ty") in
let _ : TypingEnv.t= Type_checker.check_undeclared ~errs:None ~unknown ~type_abbrevs in
t
end else t in
let amap = get_argmap state in
let amap, t = Assemble.compile_query_term ?ctx ~amap state assembled_program ~depth t in
set_argmap state amap,t
let runtime_hack_term_to_raw_term state (_, assembled_program) ?ctx ~depth t =
if State.get Data.while_compiling state then
anomaly "runtime_hack_term_to_raw_term called at compile time";
let amap, t = Assemble.compile_query_term ?ctx state assembled_program ~depth t in
if F.Map.is_empty amap then t
else
let query_env = Array.make (F.Map.cardinal amap) D.dummy in
R.move ~argsdepth:depth ~from:depth ~to_:depth query_env t
let query_of_scoped_term (compiler_state, assembled_program) f =
first_error @@ fun errs ->
let compiler_state = State.begin_goal_compilation compiler_state in
let { Assembled.signature = { kinds; types; type_abbrevs }; chr; prolog_program; total_type_checking_time } = assembled_program in
let total_type_checking_time = assembled_program.Assembled.total_type_checking_time in
let total_det_checking_time = assembled_program.Assembled.total_det_checking_time in
let compiler_state,t = f compiler_state in
let t, unknown = Type_checker.check_query ~unknown:F.Map.empty ~type_abbrevs ~kinds ~types t ~exp:TypeAssignment.(Val (Prop Relation)) in
let _ : TypingEnv.t = Type_checker.check_undeclared ~errs:(Some errs) ~unknown ~type_abbrevs in
let symbols, amap, query = Assemble.compile_query compiler_state assembled_program (false,t) in
let query_env = Array.make (F.Map.cardinal amap) D.dummy in
let initial_goal = R.move ~argsdepth:0 ~from:0 ~to_:0 query_env query in
let assignments = F.Map.fold (fun k i m -> StrMap.add (F.show k) query_env.(i) m) amap StrMap.empty in
let assignments = StrMap.fold (fun k i m -> StrMap.add k (UVar(i,0)) m) (State.get uvk compiler_state) assignments in
let builtins = assembled_program.Assembled.builtins in
{
WithMain.prolog_program;
chr;
symbols;
initial_goal;
assignments;
compiler_state;
total_type_checking_time;
total_det_checking_time;
builtins;
runtime_types = Type_checker.compile_for_runtime types;
}
let query_of_raw_term (compiler_state, assembled_program) f =
first_error @@ fun _ ->
let compiler_state = State.begin_goal_compilation compiler_state in
let { Assembled.signature = { kinds; types; type_abbrevs }; chr; prolog_program; total_type_checking_time } = assembled_program in
let total_type_checking_time = assembled_program.Assembled.total_type_checking_time in
let total_det_checking_time = assembled_program.Assembled.total_det_checking_time in
let compiler_state, query, gls = f compiler_state in
let compiler_state, gls = Data.State.get Data.Conversion.extra_goals_postprocessing compiler_state gls compiler_state in
let gls = List.map Data.Conversion.term_of_extra_goal gls in
let query =
match gls @ [query] with
| [] -> assert false
| [g] -> g
| x :: xs -> mkBuiltin And (x :: xs) in
let amap = get_argmap compiler_state in
let query_env = Array.make (F.Map.cardinal amap) D.dummy in
let initial_goal = R.move ~argsdepth:0 ~from:0 ~to_:0 query_env query in
let assignments = F.Map.fold (fun k i m -> StrMap.add (F.show k) query_env.(i) m) amap StrMap.empty in
let assignments = StrMap.fold (fun k i m -> StrMap.add k (UVar(i,0)) m) (State.get uvk compiler_state) assignments in
let builtins = assembled_program.Assembled.builtins in
{
WithMain.prolog_program;
chr;
symbols = assembled_program.Assembled.symbols;
initial_goal;
assignments;
compiler_state;
total_type_checking_time;
total_det_checking_time;
builtins;
runtime_types = Type_checker.compile_for_runtime types;
}
let symtab : ((constant * D.term) Symbol.RawMap.t * Type_checker.runtime_types) D.State.component = D.State.declare
~descriptor:D.elpi_state_descriptor
~name:"elpi:symbol_table"
~pp:(fun fmt _ -> Format.fprintf fmt "<symbol_table>")
~clause_compilation_is_over:(fun x -> x)
~compilation_is_over:(fun x -> Some x)
~execution_is_over:(fun _ -> None)
~init:(fun () -> Symbol.RawMap.empty, Type_checker.empty_runtime_types)
()
let global_name_to_constant state s =
let symbols2c,str2symbol = State.get symtab state in
match Type_checker.runtime_resolve str2symbol (F.from_string s) with
| s ->
(match Symbol.RawMap.find_opt s symbols2c with
| Some (c, _) -> c
| None ->
match Symbol.RawMap.find_opt s Global_symbols.table.s2ct with
| Some (c, _) -> c
| None -> compiler_error (Format.asprintf "cannot resolve symbol %s at run time: the program does not declare it" (Symbol.get_str s)))
| exception Not_found -> compiler_error (Format.asprintf "cannot resolve symbol %s at run time: the program does not declare it, or overloads it" s)
let lookup_global_name name state =
global_name_to_constant state name
module Compiler : sig
val run : query -> executable
end = struct
let run
{
WithMain.prolog_program;
chr;
symbols;
initial_goal;
assignments;
builtins;
runtime_types;
compiler_state = state;
}
=
let symbol_table = SymbolMap.compile symbols in
let state = State.set symtab state (SymbolMap.compile_s2c symbols,runtime_types) in
{
D.compiled_program = { index = close_index prolog_program; src = [] };
chr;
initial_depth = 0;
initial_goal;
initial_runtime_state = State.end_compilation state;
assignments;
symbol_table;
builtins = compile_builtins builtins;
}
end
let optimize_query = Compiler.run
let removals l =
List.filter_map (function
| (Some (Ast.Structured.Remove x),_,_,_) -> Some x
| (Some (Ast.Structured.Replace x),_,_,_) -> Some x
| _ -> None) l
let handle_clause_graftin (clauses: (Ast.Structured.insertion option * string option * constant * clause) list) : (string option * constant * clause) list =
let clauses = clauses |> List.sort (fun (_,_,_,c1) (_,_,_,c2) -> R.lex_insertion c1.timestamp c2.timestamp) in
let removals = removals clauses in
let clauses = clauses |> List.filter (fun (_,id,_,_) -> id = None || not(List.exists (fun x -> id = Some x) removals)) in
let clauses = clauses |> List.filter (fun (c,_,_,_) -> match c with Some (Ast.Structured.Remove _) -> false | _ -> true) in
List.map (fun (_,a,b,c) -> a,b,c) clauses
let pp_program (pp : pp_ctx:pp_ctx -> depth:int -> _) fmt (compiler_state, { Assembled.clauses; signature; symbols }) =
let clauses = handle_clause_graftin clauses in
let pp_ctx = {
uv_names = ref (IntMap.empty, 0);
table = SymbolMap.compile symbols;
} in
Format.fprintf fmt "@[<v>";
F.Map.iter (fun name (ty,_) ->
let rec a2k = function
| 0 -> "type"
| n -> "type -> " ^ a2k (n-1) in
Format.fprintf fmt "@[<h>kind %s %s.@]@," (F.show name) (a2k ty)) signature.kinds;
TypingEnv.iter_names (fun name sl ->
let f s = TypeAssignment.fresh (TypingEnv.resolve_symbol s signature.types).ty |> fst in
let tys =
match sl with
| TypeAssignment.Single t -> [f t]
| TypeAssignment.Overloaded l -> List.map f l in
let name =
match Elpi_parser.Parser_config.precedence_of (F.show name) with
| (Some _,_) -> "("^F.show name^")"
| _ -> F.show name in
List.iter (fun ty ->
Format.fprintf fmt "@[<h>type %s %a.@]@," name TypeAssignment.pretty_mut_once ty) tys;
) signature.types;
F.Map.iter (fun name TypeAssignment.{ skema = ty; } ->
Format.fprintf fmt "@[<h>typeabbrv %a (%a).@]@," F.pp name TypeAssignment.pretty_mut_once (fst @@ TypeAssignment.fresh ty)
) signature.type_abbrevs;
List.iter (fun (name,predicate,{ depth; args; hyps; loc; timestamp }) ->
Format.fprintf fmt "@[<h>%% %a [%a] %a@]@;"
Format.(pp_print_option Loc.pp) loc
Format.(pp_print_list ~pp_sep:(fun fmt () -> pp_print_string fmt "; ") pp_print_int) timestamp
Format.(pp_print_option pp_print_string) name;
Fmt.fprintf fmt "@[<hov 1>%a :- %a.@]@;"
(pp ~depth ~pp_ctx) (if args = [] then D.Const predicate else D.mkApp predicate (List.hd args) (List.tl args))
(pplist (pp ~depth ~pp_ctx) ", ") hyps)
clauses;
Format.fprintf fmt "@]"
;;
let pp_goal pp fmt { WithMain.compiler_state; initial_goal; symbols } =
let pp_ctx = {
uv_names = ref (IntMap.empty, 0);
table = SymbolMap.compile symbols;
} in
Format.fprintf fmt "@[<v>";
Format.fprintf fmt "%a.@;" (pp ~pp_ctx ~depth:0) initial_goal;
Format.fprintf fmt "@]"
;;
let elpi ~language:_ state loc s =
let module P = (val option_get ~err:"No parser" (State.get parser state)) in
let ast = P.goal ~loc ~text:s in
let term = Scope_Quotation_Macro.scope_loc_term ~state ast in
{ ScopedTerm.SimpleTerm.it = Opaque (ScopedTerm.in_scoped_term term); loc = term.loc }
exception RelocationError of string
let relocate_closed_term ~from:symbol_table ~to_:(_,{ Assembled.symbols; signature }) (t : term) : term =
let relocate c =
if Util.Constants.Map.mem c D.Global_symbols.table.c2s then c else
let s = Util.Constants.Map.find c symbol_table.c2s in
let f = s |> Symbol.get_func in
let get_variant s =
match Symbol.get_provenance s with
| Builtin { variant } -> Some variant
| _ -> None in
let c =
match TypingEnv.resolve_name f signature.types with
| (Single s) ->
SymbolMap.get_global_symbol symbols s
| (Overloaded l) ->
begin match List.filter (fun x -> Option.equal String.equal (get_variant s) (get_variant x)) l with
| [] -> None
| [x] -> SymbolMap.get_global_symbol symbols x
| x1::x2::_ -> anomaly ("Cannot relocate overloaded symbol " ^ F.show f ^"\nDeclarations:\n - " ^ Loc.show (Symbol.get_loc x1) ^ "\n - " ^ Loc.show (Symbol.get_loc x2))
end
| exception Not_found -> None in
match c with
| Some x -> x
| None -> raise (RelocationError (Format.asprintf "Relocation: unknown global %a: %a" F.pp f SymbolMap.pp_table symbols))
in
let rec rel = function
| Const c when c < 0 -> Const (relocate c)
| Const _ as x -> x
| App(c,x,xs) when c < 0 -> App(relocate c,rel x,List.map rel xs)
| App(c,x,xs) -> App(c,rel x, List.map rel xs)
| Cons(x,y) -> Cons(rel x, rel y)
| Lam t -> Lam(rel t)
| CData _ as x -> x
| Builtin(c,l) -> Builtin(map_builtin_predicate relocate c,List.map rel l)
| (Nil | Discard) as x -> x
| Arg _ | AppArg _ | UVar _ | AppUVar _ -> assert false
in
rel t
let relocate_closed_term ~from ~to_ t =
try Result.Ok(relocate_closed_term ~from ~to_ t)
with RelocationError s -> Result.Error s
module IntervalTree = struct
type 'a items = (Ast.Loc.t * 'a) list
[@@deriving show]
type 'a node =
| Leaf
| Node of { left : 'a node; loc : Ast.Loc.t; data : 'a; index : int; max_stop : int; right : 'a node }
module SM = Map.Make (String)
type 'a t = { files : 'a node SM.t; items : 'a items }
let max_stop = function Leaf -> min_int | Node { max_stop } -> max_stop
let rec build a lo hi =
if lo >= hi then Leaf
else
let mid = (lo + hi) / 2 in
let index, ((loc : Ast.Loc.t), data) = a.(mid) in
let left = build a lo mid and right = build a (mid + 1) hi in
Node { left; loc; data; index; right;
max_stop = max loc.source_stop (max (max_stop left) (max_stop right)) }
let of_list items =
let by_file = Hashtbl.create 7 in
List.iteri (fun i (((loc : Ast.Loc.t), _) as x) ->
Hashtbl.replace by_file loc.source_name
((i, x) :: Option.value ~default:[] (Hashtbl.find_opt by_file loc.source_name)))
items;
let files = Hashtbl.fold (fun name l files ->
let a = Array.of_list l in
Array.stable_sort (fun (i, ((l1 : Ast.Loc.t), _)) (j, ((l2 : Ast.Loc.t), _)) ->
match Int.compare l1.source_start l2.source_start with 0 -> Int.compare i j | c -> c) a;
SM.add name (build a 0 (Array.length a)) files) by_file SM.empty in
{ files; items }
let pp f fmt t = pp_items f fmt t.items
let smaller ({ Ast.Loc.source_start = b1; source_stop = e1 },_) ({ Ast.Loc.source_start = b2; source_stop = e2 },_) =
let d1 = e1 - b1 in
let d2 = e2 - b2 in
d1 - d2
let find ({ Ast.Loc.source_name; source_start; source_stop } : Ast.Loc.t) t =
match SM.find_opt source_name t.files with
| None -> []
| Some tree ->
let acc = ref [] in
let rec go = function
| Leaf -> ()
| Node { left; loc; data; index; max_stop; right } ->
if max_stop >= source_start then begin
go left;
if loc.source_start <= source_stop then begin
if loc.source_stop >= source_start then acc := (index, (loc, data)) :: !acc;
go right
end
end in
go tree;
List.sort (fun (i, _) (j, _) -> Int.compare i j) !acc |> List.map snd |> List.sort smaller
let fold_file source_name f t acc =
match SM.find_opt source_name t.files with
| None -> acc
| Some tree ->
let rec go acc = function
| Leaf -> acc
| Node { left; loc; data; right } -> go (f loc data (go acc left)) right in
go acc tree
end
type type_ = Compiler_data.TypeAssignment.ty
let pp_type_ = Compiler_data.TypeAssignment.pretty_mut_once
let show_type_expression =
let open ScopedTypeExpression in
let rec show ?(paren = false) (x : e) =
let par b t = if b then "(" ^ t ^ ")" else t in
match x.it with
| Const (_, c) -> F.show c
| App (_, c, y, ys) -> par paren (String.concat " " (F.show c :: List.map (show ~paren:true) (y :: ys)))
| Prop Ast.Structured.Function -> "func"
| Prop Ast.Structured.Relation -> "pred"
| Any -> "any"
| Arrow _ ->
let rec args acc (x : e) =
match x.it with
| Arrow (m, v, a, b) -> args ((m, v, a) :: acc) b
| Prop f -> Some (f, List.rev acc)
| _ -> None in
match args [] x with
| Some (f, l) ->
let kw = match f with Ast.Structured.Function -> "func" | Ast.Structured.Relation -> "pred" in
let arg (_, v, a) = show ~paren:true a ^ (if v = Ast.Structured.Variadic then ".." else "") in
let rec split_inputs = function
| (Mode.Input, _, _) as x :: rest -> let i, o = split_inputs rest in x :: i, o
| rest -> [], rest in
let ins, outs = split_inputs l in
if List.for_all (fun (m, _, _) -> m = Mode.Output) outs then
let ins_s = String.concat ", " (List.map arg ins) and outs_s = String.concat ", " (List.map arg outs) in
"(" ^ kw ^ (if ins = [] && outs = [] then "" else " ")
^ ins_s ^ (if outs = [] then "" else if ins = [] then "-> " ^ outs_s else " -> " ^ outs_s) ^ ")"
else
let mode = function Mode.Input -> "i:" | Mode.Output -> "o:" in
"(" ^ kw ^ " " ^ String.concat ", " (List.map (fun ((m, _, _) as x) -> mode m ^ arg x) l) ^ ")"
| None ->
(match x.it with
| Arrow (_, _, a, b) -> par paren (show ~paren:true a ^ " -> " ^ show b)
| _ -> assert false) in
show ?paren:None
type type_item =
| Ty_var of F.t
| Ty_const of { name : F.t; arity : int; defined : Loc.t option; abbreviation : bool }
| Ty_whole of ScopedTypeExpression.e
let walk_type_expressions (sp : scoped_program) =
let open ScopedTypeExpression in
let kinds = ref F.Map.empty and abbrevs = ref F.Map.empty in
let rec collect pb =
F.Map.iter (fun c (_, loc) -> kinds := F.Map.add c loc !kinds) pb.Scoped.kinds;
List.iter (fun (c, (t : ScopedTypeExpression.t)) -> abbrevs := F.Map.add c t.loc !abbrevs) pb.Scoped.type_abbrevs;
List.iter (function
| Scoped.Namespace (_, pb) | Scoped.Shorten (_, pb) | Scoped.Constraints (_, pb) | Scoped.Block pb -> collect pb
| Scoped.Clauses _ -> ()) pb.Scoped.body in
collect sp.code.Scoped.pbody;
let clip (loc : Loc.t) (first : e) =
if loc.Loc.source_start < first.loc.Loc.line_starts_at && first.loc.Loc.line_starts_at <= first.loc.Loc.source_start
then { loc with Loc.source_start = first.loc.Loc.line_starts_at; line = first.loc.Loc.line;
line_starts_at = first.loc.Loc.line_starts_at }
else loc in
let const name arity =
match F.Map.find_opt name !abbrevs with
| Some d -> Ty_const { name; arity; defined = Some d; abbreviation = true }
| None -> Ty_const { name; arity; defined = F.Map.find_opt name !kinds; abbreviation = false } in
let rec e f ?(in_arrow = false) (x : e) =
match x.it with
| Const (Scope.Bound _, c) -> f x.loc (Ty_var c)
| Const (Scope.Global _, c) -> f x.loc (const c 0)
| App (_, c, y, ys) ->
f x.loc (const c (1 + List.length ys));
List.iter (e f) (y :: ys)
| Arrow (_, _, a, b) ->
if not in_arrow then f (clip x.loc a) (Ty_whole x);
e f a; e f ~in_arrow:true b
| Prop _ | Any -> if not in_arrow then f x.loc (Ty_whole x) in
let rec v f = function Lam (_, x) -> v f x | Ty x -> e f x in
let rec decls f pb =
F.Map.iter (fun _ l -> List.iter (fun (t : ScopedTypeExpression.t) -> v f t.value) l) pb.Scoped.types;
List.iter (fun (_, (t : ScopedTypeExpression.t)) -> v f t.value) pb.Scoped.type_abbrevs;
List.iter (function
| Scoped.Namespace (_, pb) | Scoped.Shorten (_, pb) | Scoped.Constraints (_, pb) | Scoped.Block pb -> decls f pb
| Scoped.Clauses _ -> ()) pb.Scoped.body in
(fun f -> e f ?in_arrow:None), (fun f -> decls f sp.code.Scoped.pbody)
type origin = User | Builtin | Core | Undeclared
type cls = Predicate | Function | Data
type kind =
| Term
| Constant of cls * origin
| Bound
| Binder
| Unification_variable
| Discard
| Literal of [ `Int | `Float | `String | `Other ]
| Keyword
| Type_constructor
| Type_abbreviation
| Type_variable
| Type_keyword
| Macro
type description =
| Type of type_
| Text of string
type info = {
kind : kind;
description : description option;
defined : Ast.Loc.t option;
doc : Ast.Loc.t option;
body : Ast.Loc.t option;
declaration : bool;
occurrences : Ast.Loc.t list;
}
let pp_cls fmt = function
| Predicate -> Format.fprintf fmt "Predicate" | Function -> Format.fprintf fmt "Function" | Data -> Format.fprintf fmt "Data"
let pp_origin fmt = function
| User -> Format.fprintf fmt "User" | Builtin -> Format.fprintf fmt "Builtin"
| Core -> Format.fprintf fmt "Core" | Undeclared -> Format.fprintf fmt "Undeclared"
let pp_kind fmt = function
| Term -> Format.fprintf fmt "Term"
| Constant (c, o) -> Format.fprintf fmt "Constant(%a,%a)" pp_cls c pp_origin o
| Bound -> Format.fprintf fmt "Bound" | Binder -> Format.fprintf fmt "Binder"
| Unification_variable -> Format.fprintf fmt "Unification_variable" | Discard -> Format.fprintf fmt "Discard"
| Literal _ -> Format.fprintf fmt "Literal" | Keyword -> Format.fprintf fmt "Keyword"
| Type_constructor -> Format.fprintf fmt "Type_constructor" | Type_abbreviation -> Format.fprintf fmt "Type_abbreviation"
| Type_variable -> Format.fprintf fmt "Type_variable" | Type_keyword -> Format.fprintf fmt "Type_keyword"
| Macro -> Format.fprintf fmt "Macro"
let pp_description fmt = function
| Type t -> Format.fprintf fmt "Type(%a)" pp_type_ t
| Text s -> Format.fprintf fmt "Text(%s)" s
let pp_info fmt { kind; description; defined; doc; body; declaration; occurrences } =
Format.fprintf fmt "@[<hov 2>{ kind = %a;@ description = %a;@ defined = %a;@ doc = %a;@ body = %a;@ declaration = %b;@ occurrences = %d }@]"
pp_kind kind (pp_option pp_description) description
(pp_option Ast.Loc.pp) defined (pp_option Ast.Loc.pp) doc (pp_option Ast.Loc.pp) body declaration (List.length occurrences)
let keywords = F.Set.of_list F.[andf; orf; implf; rimplf; cutf; pif; sigmaf]
type item = {
iloc : Loc.t; ikind : kind; iname : string option; idescription : description option;
idefined : Loc.t option; idoc : Loc.t option; ibody : Loc.t option; ideclaration : bool;
}
let item ?name ?type_ ?text ?defined ?doc ?body ?(declaration = false) iloc ikind =
let idescription = match type_, text with
| Some t, _ -> Some (Type t)
| None, Some s -> Some (Text s)
| None, None -> None in
{ iloc; ikind; iname = name; idescription; idefined = defined; idoc = doc; ibody = body; ideclaration = declaration }
let type_expression_items (sp : scoped_program) =
let walk_one, walk_all = walk_type_expressions sp in
let kind n = String.concat " -> " (List.init (n + 1) (fun _ -> "type")) in
let item f loc = function
| Ty_var c -> f (item loc Type_variable ~name:(F.show c) ~text:(F.show c ^ " : type (a type variable)"))
| Ty_const { name; arity; defined; abbreviation } ->
f (item loc (if abbreviation then Type_abbreviation else Type_constructor) ~name:(F.show name)
?defined ~text:(F.show name ^ " : " ^ kind arity))
| Ty_whole ({ ScopedTypeExpression.it = Arrow _ } as x) ->
f (item loc Type_keyword ~name:"->" ~text:(show_type_expression x))
| Ty_whole x -> f (item loc Type_keyword ~name:"" ~text:(show_type_expression x)) in
(fun f -> walk_one (item f)), (fun f -> walk_all (item f))
let term_items ?(rule = false) ?(macro_args = fun _ -> None) ~types ~metadata ~head ~type_items f (t : ScopedTerm.t) =
let open ScopedTerm in
let rec heads_of_atom (t : ScopedTerm.t) =
match t.it with
| App (c, args) when F.equal c.name F.andf -> List.concat_map heads_of_atom args
| App (c, _) -> [ c.loc ]
| _ -> [] in
let heads =
if not rule then []
else match t.it with
| Impl (R2L, _, hd, _) -> heads_of_atom hd
| _ -> heads_of_atom t in
let is_head (l : Loc.t) = List.exists (fun (h : Loc.t) -> h.source_start = l.source_start && h.source_stop = l.source_stop) heads in
let emit ?declaration ?name ?type_ ?defined ?doc ?body loc kind = f (item ?declaration ?name ?type_ ?defined ?doc ?body loc kind) in
let ty_of ty = TypeAssignment.deref_opt ty in
let term (t : ScopedTerm.t) = Option.iter (fun type_ -> emit t.loc Term ~type_) (ty_of t.ty) in
let rec cls_of = function
| TypeAssignment.Prop Ast.Structured.Relation -> Predicate
| TypeAssignment.Prop Ast.Structured.Function -> Function
| TypeAssignment.Arr (_, _, _, r) -> cls_of r
| TypeAssignment.UVar r when MutableOnce.is_set r -> cls_of (TypeAssignment.deref r)
| _ -> Data in
let range (qloc : Loc.t) (b : binder) = { qloc with Loc.source_stop = b.loc.Loc.source_stop } in
let global (c : const) resolved_to =
let name = F.show c.name and type_ = ty_of c.ty in
let sym = SymbolResolver.resolved_to types resolved_to in
let defined = Option.map Symbol.get_loc sym in
let meta = Option.bind sym metadata in
let doc = Option.bind meta (fun { TypingEnv.doc } -> doc) in
let body = Option.bind meta (fun { TypingEnv.body } -> body) in
if F.Set.mem c.name keywords then emit c.loc Keyword ~name ?type_ ?defined
else
let origin =
match sym with
| None -> Undeclared
| Some s -> (match Symbol.get_provenance s with File _ -> User | Builtin _ -> Builtin | Core -> Core) in
let cls = match type_ with Some ty -> cls_of ty | None -> Data in
emit c.loc (Constant (cls, origin)) ~name ?type_ ?defined ?doc ?body ~declaration:(is_head c.loc) in
let rec aux env (t : ScopedTerm.t) =
match macro_args t.loc with
| Some args -> term t; List.iter (aux env) args
| None ->
match t.it with
| Impl (_, hdloc, l, r) ->
term t;
emit hdloc Keyword ~defined:(Symbol.get_loc Global_symbols.impl);
aux env l; aux env r
| Discard _ -> emit t.loc Discard ?type_:(ty_of t.ty)
| UVar (uv, args) ->
if args <> [] then term t;
emit uv.loc Unification_variable ~name:(F.show uv.name) ?type_:(ty_of uv.ty) ~defined:head;
List.iter (aux env) args
| App (c, args) ->
if args <> [] then term t;
let synthetic =
(F.equal c.name F.consf && (match args with a :: _ -> c.loc.Loc.source_start = a.loc.Loc.source_start | [] -> false))
|| (F.equal c.name F.nilf && c.loc.Loc.source_stop = c.loc.Loc.source_start) in
(match c.scope with
| Scope.Global _ when synthetic -> ()
| Scope.Global { resolved_to } -> global c resolved_to
| Scope.Bound lang ->
emit c.loc Bound ~name:(F.show c.name) ?type_:(ty_of c.ty) ?defined:(Scope.Map.find_opt (c.name, lang) env));
(match c.scope, args with
| Scope.Global _, [ { it = Lam (Some b, ty, body) } as l ] when F.equal c.name F.pif || F.equal c.name F.sigmaf ->
term l;
lam env (Some (range c.loc b)) b ty body
| _ -> List.iter (aux env) args)
| CData c ->
let l = match CData.name c with "int" -> `Int | "float" -> `Float | "string" -> `String | _ -> `Other in
emit t.loc (Literal l) ?type_:(ty_of t.ty)
| Spill (s, _) -> term t; aux env s
| Cast (c, ty) -> term t; aux env c; type_items f ty
| Lam (Some b, ty, body) -> term t; lam env None b ty body
| Lam (None, ty, body) -> term t; Option.iter (type_items f) ty; aux env body
and lam env quantifier (b : binder) ty body =
let defined = match quantifier with Some r -> r | None -> b.loc in
emit b.loc Binder ~name:(F.show b.name) ?type_:(ty_of b.ty) ~defined ~declaration:true;
Option.iter (type_items f) ty;
aux (Scope.Map.add (b.name, b.scope) defined env) body in
aux Scope.Map.empty t
let rule_head (t : ScopedTerm.t) =
match t.ScopedTerm.it with
| ScopedTerm.Impl (R2L, _, hd, _) -> hd.ScopedTerm.loc
| _ -> t.ScopedTerm.loc
module Occurrence = struct
type t = bool * string option * Loc.t option
let equal (v1, n1, d1) (v2, n2, d2) =
Stdlib.Bool.equal v1 v2 && Option.equal String.equal n1 n2 && Option.equal Loc.equal d1 d2
let hash (v, n, d) =
Hashtbl.hash (v, n, Option.map (fun (l : Loc.t) -> (l.Loc.source_name, l.Loc.source_start, l.Loc.source_stop)) d)
end
module OccurrenceTbl = Hashtbl.Make(Occurrence)
let is_variable { ikind; idefined } =
match ikind with Bound | Binder | Unification_variable -> Option.is_some idefined | _ -> false
let is_constant { ikind } = match ikind with Constant _ -> true | _ -> false
let hover ?base (sp : scoped_program) (u : checked_compilation_unit) =
let types = u.checked_code.CheckedFlat.signature.Assembled.types in
let metadata s =
match TypingEnv.resolve_symbol_opt s types with
| Some m -> Some m
| None -> Option.bind base (fun ((_, p) : program) -> TypingEnv.resolve_symbol_opt s p.Assembled.signature.types) in
let type_items, declaration_items = type_expression_items sp in
let items = ref [] in
let add i = items := i :: !items in
let key (l : Loc.t) = l.Loc.source_name, l.Loc.source_start, l.Loc.source_stop in
let expansions = Hashtbl.create 17 in
List.iter (fun { Scoped.name_loc; expansion_loc; macro; macro_loc } ->
Hashtbl.replace expansions (key expansion_loc) ();
add (item name_loc Macro ~name:(F.show macro) ~defined:macro_loc))
sp.code.Scoped.macro_uses;
let in_text i = match i.ikind with Term -> true | _ -> not (Hashtbl.mem expansions (key i.iloc)) in
let args_of_use = Hashtbl.create 17 in
List.iter (fun { Scoped.expansion_loc; args; _ } -> Hashtbl.replace args_of_use (key expansion_loc) args) sp.code.Scoped.macro_uses;
let macro_args l = Hashtbl.find_opt args_of_use (key l) in
let term ?rule ~head t = term_items ?rule ~macro_args ~types ~metadata ~head ~type_items (fun i -> if in_text i then add i) t in
let as_written = Hashtbl.create 7 in
List.iter (fun (l, t) -> Hashtbl.replace as_written (key l) t) u.checked_code.CheckedFlat.as_written;
List.iter (fun { Ast.Clause.body; loc } ->
let body = Option.value ~default:body (Hashtbl.find_opt as_written (key loc)) in
term ~rule:true ~head:(rule_head body) body) u.checked_code.CheckedFlat.clauses;
List.iter (fun { Ast.Structured.rules } ->
List.iter (fun { Ast.Chr.to_match; to_remove; guard; new_goal; loc } ->
let sequents = to_match @ to_remove @ Option.to_list new_goal in
let head = match sequents with { Ast.Chr.conclusion } :: _ -> conclusion.ScopedTerm.loc | [] -> loc in
List.iter (fun { Ast.Chr.eigen; context; conclusion } ->
term ~head eigen; term ~head context; term ~head conclusion) sequents;
Option.iter (term ~head) guard) rules) u.checked_code.CheckedFlat.chr;
F.Map.iter (fun _ ((t : ScopedTerm.t), _) -> term ~head:t.loc t) u.checked_code.CheckedFlat.signature.Assembled.toplevel_macros;
declaration_items add;
let symbol i = if is_variable i || is_constant i then Some (is_variable i, i.iname, i.idefined) else None in
let groups = OccurrenceTbl.create 97 in
List.iter (fun i ->
match symbol i, i.ikind with
| None, _ | Some _, Binder -> ()
| Some k, _ -> OccurrenceTbl.replace groups k (i.iloc :: Option.value ~default:[] (OccurrenceTbl.find_opt groups k)))
!items;
let by_position (a : Loc.t) (b : Loc.t) =
match String.compare a.source_name b.source_name with
| 0 -> (match Int.compare a.source_start b.source_start with 0 -> Int.compare a.source_stop b.source_stop | c -> c)
| c -> c in
let sorted = OccurrenceTbl.create 97 in
let occurrences k =
match OccurrenceTbl.find_opt sorted k with
| Some l -> l
| None ->
let l = List.sort_uniq by_position (Option.value ~default:[] (OccurrenceTbl.find_opt groups k)) in
OccurrenceTbl.replace sorted k l; l in
List.rev_map (fun i ->
i.iloc, { kind = i.ikind; description = i.idescription; defined = i.idefined; doc = i.idoc; body = i.ibody;
declaration = i.ideclaration; occurrences = (match symbol i with Some k -> occurrences k | None -> []) })
!items
|> IntervalTree.of_list
let smart_map_cdata_in_scoped_term (f : CData.t -> CData.t) t =
let open ScopedTerm in
let rec aux it =
match it with
| CData c ->
let c' = f c in
if c == c' then it else CData c'
| Impl(b,lb,t1,t2) ->
let t1' = aux_loc t1 in
let t2' = aux_loc t2 in
if t1 == t1' && t2 == t2' then it
else Impl(b,lb,t1',t2')
| Spill(t,n) ->
let t' = aux_loc t in
if t' == t then it else Spill(t',n)
| App(c,xs) ->
let xs' = smart_map aux_loc xs in
if xs == xs' then it else App(c,xs')
| Lam(n,ty,b) ->
let b' = aux_loc b in
if b == b' then it else Lam(n,ty,b')
| UVar(c,l) ->
let l' = smart_map aux_loc l in
if l == l' then it else UVar(c,l')
| Cast(t,ty) ->
let t' = aux_loc t in
if t' == t then it else Cast(t',ty)
| Discard _ -> it
and aux_loc ({ it; loc; ty } as orig) =
let it' = aux it in
if it == it' then orig
else { it = it'; loc; ty }
in
aux_loc t
let smart_map_cdata_in_clause f ({ Ast.Clause.body } as x) =
let body' = smart_map_cdata_in_scoped_term f body in
if body == body' then x else { x with body = body' }
let smart_map_cdata_in_sequent f ({ Ast.Chr.eigen; context; conclusion } as orig) =
let eigen' = smart_map_cdata_in_scoped_term f eigen in
let context' = smart_map_cdata_in_scoped_term f context in
let conclusion' = smart_map_cdata_in_scoped_term f conclusion in
if eigen' == eigen && context' == context && conclusion' == conclusion then orig
else { Ast.Chr.eigen = eigen'; context = context'; conclusion = conclusion' }
let smart_map_cdata_in_chr f ({ Ast.Chr.to_match; to_remove; guard; new_goal; attributes; loc } as orig) =
let to_match' = smart_map (smart_map_cdata_in_sequent f) to_match in
let to_remove' = smart_map (smart_map_cdata_in_sequent f) to_remove in
let guard' = option_smart_map (smart_map_cdata_in_scoped_term f) guard in
let new_goal' = option_smart_map (smart_map_cdata_in_sequent f) new_goal in
if to_match' == to_match && to_remove' == to_remove && guard' == guard && new_goal' == new_goal then orig
else { Ast.Chr.to_match = to_match'; to_remove = to_remove'; guard = guard'; new_goal = new_goal'; attributes; loc }
let smart_map_cdata_in_block_constraint f ({ Ast.Structured.rules; _ } as orig) =
let rules' = smart_map (smart_map_cdata_in_chr f) rules in
if rules' == rules then orig
else { orig with Ast.Structured.rules = rules' }
let map_compilation_unit (f : CData.t -> CData.t) (u : checked_compilation_unit) : checked_compilation_unit =
let { checked_code = { CheckedFlat.clauses; chr; builtins; signature; as_written }; _ } = u in
let clauses' = smart_map (smart_map_cdata_in_clause f) clauses in
let chr' = smart_map (smart_map_cdata_in_block_constraint f) chr in
if clauses == clauses' && chr == chr' then u
else { u with checked_code = { CheckedFlat.clauses = clauses'; chr = chr'; builtins; signature; as_written } }