Source file ctype.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
open Misc
open Asttypes
open Types
open Btype
open Errortrace
open Mode
open Local_store
let debug_ikind_crossing_mismatch =
Sys.getenv_opt "OXCAML_IKIND_CROSSING_MISMATCH" <> None
exception Unify_trace of unification trace
exception Equality_trace of comparison trace
exception Moregen_trace of comparison trace
exception Unify of unification_error
exception Equality of equality_error
exception Moregen of moregen_error
exception Subtype of Subtype.error
exception Escape of type_expr escape
type _ trace_exn =
| Unify : unification trace_exn
| Moregen : comparison trace_exn
| Equality : comparison trace_exn
let raise_trace_for
(type variant)
(tr_exn : variant trace_exn)
(tr : variant trace) : 'a =
match tr_exn with
| Unify -> raise (Unify_trace tr)
| Equality -> raise (Equality_trace tr)
| Moregen -> raise (Moregen_trace tr)
let raise_unexplained_for tr_exn =
raise_trace_for tr_exn []
let raise_for tr_exn e =
raise_trace_for tr_exn [e]
exception Public_method_to_private_method
let escape kind = {kind; context = None}
let escape_exn kind = Escape (escape kind)
let scope_escape_exn ty = escape_exn (Equation ty)
let raise_escape_exn kind = raise (escape_exn kind)
let raise_scope_escape_exn ty = raise (scope_escape_exn ty)
exception Tags of label * label
let () =
let open Format_doc in
Location.register_error_of_exn
(function
| Tags (l, l') ->
let pp_tag ppf s = fprintf ppf "`%s" s in
let inline_tag = Misc.Style.as_inline_code pp_tag in
Some
Location.
(errorf ~loc:(in_file !input_name)
"In this program,@ variant constructors@ %a and %a@ \
have the same hash value.@ Change one of them."
inline_tag l inline_tag l'
)
| _ -> None
)
exception Cannot_expand
exception Cannot_apply
exception Cannot_subst
exception Cannot_unify_universal_variables
exception Incompatible
let current_level = s_ref 0
let nongen_level = s_ref 0
let global_level = s_ref 0
let saved_level = s_ref []
type levels =
{ current_level: int;
nongen_level: int;
global_level: int;
saved_level: (int * int) list;
}
let save_levels () =
{ current_level = !current_level;
nongen_level = !nongen_level;
global_level = !global_level;
saved_level = !saved_level }
let set_levels l =
current_level := l.current_level;
nongen_level := l.nongen_level;
global_level := l.global_level;
saved_level := l.saved_level
let get_current_level () = !current_level
let init_def level = current_level := level; nongen_level := level
let begin_def () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
incr current_level; nongen_level := !current_level
let begin_class_def () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
incr current_level
let raise_nongen_level () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
nongen_level := !current_level
let end_def () =
let (cl, nl) = List.hd !saved_level in
saved_level := List.tl !saved_level;
current_level := cl; nongen_level := nl
let create_scope () =
init_def (!current_level + 1);
!current_level
let wrap_end_def f = Misc.try_finally f ~always:end_def
let mark_toplevel_in_quotations env =
let scope = !current_level in
let _ = create_scope () in
Env.mark_toplevel_in_quotations ~scope env
let with_local_level ?post f =
begin_def ();
let result = wrap_end_def f in
Option.iter (fun g -> g result) post;
result
let with_local_level_if cond f ~post =
if cond then with_local_level f ~post else f ()
let with_local_level_iter f ~post =
begin_def ();
let result, l = wrap_end_def f in
List.iter post l;
result
let with_local_level_iter_if cond f ~post =
if cond then with_local_level_iter f ~post else fst (f ())
let with_local_level_if_principal f ~post =
with_local_level_if !Clflags.principal f ~post
let with_local_level_iter_if_principal f ~post =
with_local_level_iter_if !Clflags.principal f ~post
let with_level ~level f =
begin_def (); init_def level;
let result = wrap_end_def f in
result
let with_level_if cond ~level f =
if cond then with_level ~level f else f ()
let with_local_level_for_class ?post f =
begin_class_def ();
let result = wrap_end_def f in
Option.iter (fun g -> g result) post;
result
let with_raised_nongen_level f =
raise_nongen_level ();
wrap_end_def f
let reset_global_level () =
global_level := !current_level
let increase_global_level () =
let gl = !global_level in
global_level := !current_level;
gl
let restore_global_level gl =
global_level := gl
let trace_gadt_instances = ref false
let check_trace_gadt_instances env =
not !trace_gadt_instances && Env.has_local_constraints env &&
(trace_gadt_instances := true; cleanup_abbrev (); true)
let reset_trace_gadt_instances b =
if b then trace_gadt_instances := false
let wrap_trace_gadt_instances env f x =
let b = check_trace_gadt_instances env in
let y = f x in
reset_trace_gadt_instances b;
y
let simple_abbrevs = ref Mnil
let proper_abbrevs tl abbrev =
if tl <> [] || !trace_gadt_instances || !Clflags.principal
then abbrev
else simple_abbrevs
let newty desc = newty2 ~level:!current_level desc
let new_scoped_ty scope desc = newty3 ~level:!current_level ~scope desc
let newvar ?name jkind =
newty2 ~level:!current_level (Tvar { name; jkind })
let new_rep_var ?name ~why () =
let jkind, sort = Jkind.of_new_sort_var ~why ~level:!current_level in
newvar ?name jkind, sort
let newvar2 ?name level jkind = newty2 ~level (Tvar { name; jkind })
let new_global_var ?name jkind =
newty2 ~level:!global_level (Tvar { name; jkind })
let newstub ~scope jkind =
newty3 ~level:!current_level ~scope (Tvar { name = None; jkind })
let newobj fields = newty (Tobject (fields, ref None))
let newconstr path tyl = newty (Tconstr (path, tyl, ref Mnil))
let newmono ty = newty (Tpoly(ty, []))
let none = newty (Ttuple [])
let rec update_variable_stage stage_offset ty name jkind =
if stage_offset = 0 then ()
else if stage_offset < 0 then begin
let v = newvar2 ?name (get_level ty) jkind in
link_type ty (new_quote_ty v);
update_variable_stage (stage_offset + 1) v name jkind
end else begin
let v = newvar2 ?name (get_level ty) jkind in
link_type ty (new_splice_ty v);
update_variable_stage (stage_offset - 1) v name jkind
end
module Pattern_env : sig
type t = private
{ mutable env : Env.t;
equations_scope : int;
allow_recursive_equations : bool;
mutable env_alloc_mode : Mode.Alloc.r option; }
val make: ?env_alloc_mode:Mode.Alloc.r -> Env.t -> equations_scope:int
-> allow_recursive_equations:bool -> t
val copy: ?equations_scope:int -> t -> t
val set_env: t -> Env.t -> unit
val set_env_alloc_mode : t -> Mode.Alloc.r option -> unit
end = struct
type t =
{ mutable env : Env.t;
equations_scope : int;
allow_recursive_equations : bool;
mutable env_alloc_mode : Mode.Alloc.r option; }
let make ?env_alloc_mode env ~equations_scope ~allow_recursive_equations =
{ env;
equations_scope;
allow_recursive_equations;
env_alloc_mode; }
let copy ?equations_scope penv =
let equations_scope =
match equations_scope with None -> penv.equations_scope | Some s -> s in
{ penv with equations_scope }
let set_env penv env = penv.env <- env
let set_env_alloc_mode penv m = penv.env_alloc_mode <- m
end
type equations_generation =
| Forbidden
| Allowed of { equated_types : TypePairs.t; pattern_stage : Env.stage }
type unification_environment =
| Expression of
{ env : Env.t;
in_subst : bool; }
| Pattern of
{ penv : Pattern_env.t;
equations_generation : equations_generation;
assume_injective : bool;
unify_eq_set : TypePairs.t }
let get_env = function
| Expression {env} -> env
| Pattern {penv} -> penv.env
let set_env uenv env =
match uenv with
| Expression _ -> invalid_arg "Ctype.set_env"
| Pattern {penv} -> Pattern_env.set_env penv env
let in_pattern_mode = function
| Expression _ -> false
| Pattern _ -> true
let get_equations_scope = function
| Expression _ -> invalid_arg "Ctype.get_equations_scope"
| Pattern r -> r.penv.equations_scope
let order_type_pair t1 t2 =
if get_id t1 <= get_id t2 then (t1, t2) else (t2, t1)
let add_type_equality uenv t1 t2 =
match uenv with
| Expression _ -> invalid_arg "Ctype.add_type_equality"
| Pattern r -> TypePairs.add r.unify_eq_set (order_type_pair t1 t2)
let unify_eq uenv t1 t2 =
eq_type t1 t2 ||
match uenv with
| Expression _ -> false
| Pattern r -> TypePairs.mem r.unify_eq_set (order_type_pair t1 t2)
let in_subst_mode = function
| Expression {in_subst} -> in_subst
| Pattern _ -> false
let can_generate_equations = function
| Expression _ | Pattern { equations_generation = Forbidden } -> false
| Pattern { penv; equations_generation = Allowed { pattern_stage } } ->
Env.stage penv.env >= pattern_stage
let record_equation uenv t1 t2 =
match uenv with
| Expression _ | Pattern { equations_generation = Forbidden } ->
invalid_arg "Ctype.record_equation"
| Pattern { equations_generation = Allowed { equated_types } } ->
TypePairs.add equated_types (t1, t2)
let can_assume_injective = function
| Expression _ -> false
| Pattern { assume_injective } -> assume_injective
let in_counterexample uenv =
match uenv with
| Expression _ -> false
| Pattern { penv } -> penv.allow_recursive_equations
let allow_recursive_equations uenv =
!Clflags.recursive_types || in_counterexample uenv
let without_assume_injective uenv f =
match uenv with
| Expression _ as uenv -> f uenv
| Pattern r -> f (Pattern { r with assume_injective = false })
let without_generating_equations uenv f =
match uenv with
| Expression _ as uenv -> f uenv
| Pattern r -> f (Pattern { r with equations_generation = Forbidden })
let decr_stage env =
if Int.equal 0 (Env.stage env :> int) then
fatal_errorf "Ctype.decr_stage: Stage decreased below the meta stage";
Env.enter_splice ~loc:Location.none env
let incr_stage env =
Env.enter_quotation env
let iter_type_expr_with_stages f env ty =
match get_desc ty with
| Tquote ty ->
f (incr_stage env) ty
| Tsplice ty ->
f (decr_stage env) ty
| Tquote_eval ty ->
f (incr_stage env) ty
| _ ->
iter_type_expr (f env) ty
let contains_toplevel_splice stage ty =
let visited = ref TypeSet.empty in
let rec loop acc ty =
if TypeSet.mem ty !visited then false else begin
visited := TypeSet.add ty !visited;
let offset =
match get_desc ty with
| Tquote _ -> +1
| Tsplice _ -> -1
| Tquote_eval _ -> +1
| _ -> 0
in
fold_type_expr
(fun x y -> x || loop (acc + offset) y)
(acc < 0) ty
end
in
loop stage ty
let unify_with_incr_stage uenv f =
match uenv with
| Expression e ->
f (Expression { e with env = incr_stage e.env })
| Pattern p ->
Pattern_env.set_env p.penv (incr_stage p.penv.env);
try
let x = f (Pattern p) in
Pattern_env.set_env p.penv (decr_stage p.penv.env);
x
with exn ->
Pattern_env.set_env p.penv (decr_stage p.penv.env);
raise exn
let unify_with_decr_stage uenv f =
match uenv with
| Expression e ->
f (Expression { e with env = decr_stage e.env })
| Pattern p ->
Pattern_env.set_env p.penv (decr_stage p.penv.env);
try
let x = f (Pattern p) in
Pattern_env.set_env p.penv (incr_stage p.penv.env);
x
with exn ->
Pattern_env.set_env p.penv (incr_stage p.penv.env);
raise exn
type jkind_unification_mode =
| Perform_checks
| Delay_checks of (type_expr * jkind_r) list ref
let lmode = ref Perform_checks
let delay_jkind_checks_in f =
let r = ref [] in
Misc.protect_refs [Misc.R (lmode, Delay_checks r)] f;
!r
let rec in_current_module = function
| Path.Pident _ -> true
| Path.Pdot _ | Path.Papply _ -> false
| Path.Pextra_ty (p, _) -> in_current_module p
let in_pervasives p =
in_current_module p &&
try ignore (Env.find_type p (Lazy.force Env.initial)); true
with Not_found -> false
let is_datatype decl=
match decl.type_kind with
| Type_record _ | Type_record_unboxed_product _ | Type_variant _
| Type_open -> true
| Type_abstract _ -> false
let object_fields ty =
match get_desc ty with
Tobject (fields, _) -> fields
| _ -> assert false
let flatten_fields ty =
let rec flatten l ty =
match get_desc ty with
Tfield(s, k, ty1, ty2) ->
flatten ((s, k, ty1)::l) ty2
| _ ->
(l, ty)
in
let (l, r) = flatten [] ty in
(List.sort (fun (n, _, _) (n', _, _) -> compare n n') l, r)
let build_fields level =
List.fold_right
(fun (s, k, ty1) ty2 -> newty2 ~level (Tfield(s, k, ty1, ty2)))
let associate_fields fields1 fields2 =
let rec associate p s s' =
function
(l, []) ->
(List.rev p, (List.rev s) @ l, List.rev s')
| ([], l') ->
(List.rev p, List.rev s, (List.rev s') @ l')
| ((n, k, t)::r, (n', k', t')::r') when n = n' ->
associate ((n, k, t, k', t')::p) s s' (r, r')
| ((n, k, t)::r, ((n', _k', _t')::_ as l')) when n < n' ->
associate p ((n, k, t)::s) s' (r, l')
| (((_n, _k, _t)::_ as l), (n', k', t')::r') ->
associate p s ((n', k', t')::s') (l, r')
in
associate [] [] [] (fields1, fields2)
let rec object_row ty =
match get_desc ty with
Tobject (t, _) -> object_row t
| Tfield(_, _, _, t) -> object_row t
| _ -> ty
let opened_object ty =
match get_desc (object_row ty) with
| Tvar _ | Tunivar _ | Tconstr _ -> true
| _ -> false
let concrete_object ty =
match get_desc (object_row ty) with
| Tvar _ -> false
| _ -> true
let rec fields_row_variable ty =
match get_desc ty with
| Tfield (_, _, _, ty) -> fields_row_variable ty
| Tvar _ -> ty
| _ -> assert false
let set_object_name id params ty =
match get_desc ty with
| Tobject (fi, nm) ->
let rv = fields_row_variable fi in
set_name nm (Some (Path.Pident id, rv::params))
| Tconstr (_, _, _) -> ()
| _ -> fatal_error "Ctype.set_object_name"
let remove_object_name ty =
match get_desc ty with
Tobject (_, nm) -> set_name nm None
| Tconstr (_, _, _) -> ()
| _ -> fatal_error "Ctype.remove_object_name"
let sort_row_fields = List.sort (fun (p,_) (q,_) -> compare p q)
let rec merge_rf r1 r2 pairs fi1 fi2 =
match fi1, fi2 with
(l1,f1 as p1)::fi1', (l2,f2 as p2)::fi2' ->
if l1 = l2 then merge_rf r1 r2 ((l1,f1,f2)::pairs) fi1' fi2' else
if l1 < l2 then merge_rf (p1::r1) r2 pairs fi1' fi2 else
merge_rf r1 (p2::r2) pairs fi1 fi2'
| [], _ -> (List.rev r1, List.rev_append r2 fi2, pairs)
| _, [] -> (List.rev_append r1 fi1, List.rev r2, pairs)
let merge_row_fields fi1 fi2 =
match fi1, fi2 with
[], _ | _, [] -> (fi1, fi2, [])
| [p1], _ when not (List.mem_assoc (fst p1) fi2) -> (fi1, fi2, [])
| _, [p2] when not (List.mem_assoc (fst p2) fi1) -> (fi1, fi2, [])
| _ -> merge_rf [] [] [] (sort_row_fields fi1) (sort_row_fields fi2)
let rec filter_row_fields erase = function
[] -> []
| (_l,f as p)::fi ->
let fi = filter_row_fields erase fi in
match row_field_repr f with
Rabsent -> fi
| Reither(_,_,false) when erase ->
link_row_field_ext ~inside:f rf_absent; fi
| _ -> p :: fi
let remove_mode_and_jkind_variables ty =
let visited = ref TypeSet.empty in
let rec go ty =
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tvar { jkind } -> Jkind.default_to_scannable jkind
| Tunivar { jkind } -> Jkind.default_to_scannable jkind
| Tarrow ((_,marg,mret),targ,tret,_) ->
let _ = Alloc.zap_to_legacy marg in
let _ = Alloc.zap_to_legacy mret in
go targ; go tret
| _ -> iter_type_expr go ty
end
in go ty
type variable_kind = Row_variable | Type_variable
exception Non_closed of type_expr * variable_kind
let[@inline] free_vars ~zero ~add_one ?env mark tys =
let rec fv ~kind acc ty =
if not (try_mark_node mark ty) then acc
else match get_desc ty, env with
| Tvar { jkind; _ }, _ ->
add_one ty (Some jkind) kind acc
| Tconstr (path, tl, _), Some env ->
let acc =
match Env.find_type_expansion path env with
| exception Not_found -> acc
| (_, body, _) ->
if get_level body = generic_level then acc
else add_one ty None kind acc
in
List.fold_left (fv ~kind:Type_variable) acc tl
| Tobject (ty, _), _ ->
fv ~kind:Row_variable acc ty
| Tfield (_, _, ty1, ty2), _ ->
let acc = fv ~kind:Type_variable acc ty1 in
fv ~kind:Row_variable acc ty2
| Tvariant row, _ ->
let acc = fold_row (fv ~kind:Type_variable) acc row in
if static_row row then acc
else fv ~kind:Row_variable acc (row_more row)
| _ ->
fold_type_expr (fv ~kind) acc ty
in
List.fold_left (fv ~kind:Type_variable) zero tys
let free_variables ?env ty =
let add_one ty _jkind _kind acc = ty :: acc in
with_type_mark (fun mark -> free_vars ~zero:[] ~add_one ?env mark [ty])
let free_non_row_variables_of_list tyl =
let add_one ty _jkind kind acc =
match kind with
| Type_variable -> ty :: acc
| Row_variable -> acc
in
with_type_mark (fun mark -> free_vars ~zero:[] ~add_one mark tyl)
let free_variable_set_of_list env tys =
let add_one ty jkind _kind acc =
match jkind with
| None -> acc
| Some _jkind -> TypeSet.add ty acc
in
with_type_mark (fun mark ->
free_vars ~zero:TypeSet.empty ~add_one ~env mark tys)
let exists_free_variable f ty =
let exception Exists in
let add_one ty jkind _kind _acc =
match jkind with
| Some jkind when f ty jkind -> raise Exists
| Some _ -> ()
| None -> assert false
in
with_type_mark (fun mark ->
try free_vars ~zero:() ~add_one mark [ty]; false
with Exists -> true)
let closed_type ?env mark ty =
let add_one ty _jkind kind _acc = raise (Non_closed (ty, kind)) in
free_vars ~zero:() ~add_one ?env mark [ty]
let closed_type_expr ?env ty =
with_type_mark (fun mark ->
try closed_type ?env mark ty; true
with Non_closed _ -> false)
let close_type mark ty =
remove_mode_and_jkind_variables ty;
closed_type mark ty
let closed_parameterized_type params ty =
with_type_mark begin fun mark ->
List.iter (mark_type mark) params;
try close_type mark ty; true with Non_closed _ -> false
end
let closed_type_decl decl =
with_type_mark begin fun mark -> try
List.iter (mark_type mark) decl.type_params;
List.iter remove_mode_and_jkind_variables decl.type_params;
begin match decl.type_kind with
Type_abstract _ ->
()
| Type_variant (v, _rep, _) ->
List.iter
(fun {cd_args; cd_res; _} ->
match cd_res with
| Some res_ty ->
begin match cd_args with
| Cstr_tuple l -> List.iter (fun ca ->
remove_mode_and_jkind_variables ca.ca_type) l
| Cstr_record l -> List.iter (fun l ->
remove_mode_and_jkind_variables l.ld_type) l
end;
remove_mode_and_jkind_variables res_ty
| None -> List.iter (close_type mark) (tys_of_constr_args cd_args)
)
v
| Type_record(r, _rep, _) ->
List.iter (fun l -> close_type mark l.ld_type) r
| Type_record_unboxed_product(r, _rep, _) ->
List.iter (fun l -> close_type mark l.ld_type) r
| Type_open -> ()
end;
begin match decl.type_manifest with
None -> ()
| Some ty -> close_type mark ty
end;
None
with Non_closed (ty, _) ->
Some ty
end
let closed_extension_constructor ext =
with_type_mark begin fun mark -> try
List.iter (mark_type mark) ext.ext_type_params;
begin match ext.ext_ret_type with
| Some res_ty ->
iter_type_expr_cstr_args remove_mode_and_jkind_variables ext.ext_args;
remove_mode_and_jkind_variables res_ty
| None ->
iter_type_expr_cstr_args (close_type mark) ext.ext_args
end;
None
with Non_closed (ty, _) ->
Some ty
end
type closed_class_failure = {
free_variable: type_expr * variable_kind;
meth: string;
meth_ty: type_expr;
}
exception CCFailure of closed_class_failure
let closed_class params sign =
with_type_mark begin fun mark ->
List.iter (mark_type mark) params;
ignore (try_mark_node mark sign.csig_self_row);
try
Meths.iter
(fun lab (priv, _, ty) ->
if priv = Mpublic then begin
try close_type mark ty with Non_closed (ty0, variable_kind) ->
raise (CCFailure {
free_variable = (ty0, variable_kind);
meth = lab;
meth_ty = ty;
})
end)
sign.csig_meths;
None
with CCFailure reason ->
Some reason
end
let duplicate_type ty =
Subst.type_expr Subst.identity ty
let duplicate_class_type ty =
Subst.class_type Subst.identity ty
let rec lower_all ty =
if get_level ty > !current_level then begin
set_level ty !current_level;
iter_type_expr lower_all ty
end
let rec generalize stage_offset ty =
let level = get_level ty in
if (level > !current_level) && (level <> generic_level) then begin
set_level ty generic_level;
begin match get_desc ty with
| Tquote ty' ->
generalize (stage_offset + 1) ty'
| Tquote_eval ty' ->
generalize (stage_offset + 1) ty'
| Tsplice ty' ->
generalize (stage_offset - 1) ty'
| Tvar name ->
update_variable_stage stage_offset ty name.name name.jkind;
Jkind.generalize ~current_level:!current_level name.jkind
| Tobject _ | Tvariant _ when stage_offset <> 0 && is_Tvar (proxy ty) ->
lower_all ty
| Tconstr (_, _, abbrev) ->
iter_abbrev (generalize stage_offset) !abbrev;
iter_type_expr (generalize stage_offset) ty
| _ ->
iter_type_expr (generalize stage_offset) ty
end;
end
let generalize ty =
simple_abbrevs := Mnil;
generalize 0 ty
let rec generalize_structure ty =
let level = get_level ty in
if level <> generic_level then begin
if is_Tvar ty && level > !current_level then
set_level ty !current_level
else if level > !current_level then begin
begin match get_desc ty with
Tconstr (_, _, abbrev) ->
abbrev := Mnil
| _ -> ()
end;
set_level ty generic_level;
iter_type_expr generalize_structure ty
end
end
let generalize_structure ty =
simple_abbrevs := Mnil;
generalize_structure ty
let rec generalize_spine ty =
let level = get_level ty in
if level < !current_level || level = generic_level then () else
match get_desc ty with
Tarrow (_, ty1, ty2, _) ->
set_level ty generic_level;
generalize_spine ty1;
generalize_spine ty2;
| Tpoly (ty', _) ->
set_level ty generic_level;
generalize_spine ty'
| Ttuple tyl ->
set_level ty generic_level;
List.iter (fun (_,t) -> generalize_spine t) tyl
| Tunboxed_tuple tyl ->
set_level ty generic_level;
List.iter (fun (_,t) -> generalize_spine t) tyl
| Tpackage (_, fl) ->
set_level ty generic_level;
List.iter (fun (_n, ty) -> generalize_spine ty) fl
| Tconstr (_, tyl, memo) ->
set_level ty generic_level;
memo := Mnil;
List.iter generalize_spine tyl
| _ -> ()
let forward_try_expand_safe =
ref (fun _env _ty -> assert false)
let rec normalize_package_path env p =
let t =
try (Env.find_modtype_lazy p env).mtd_type
with Not_found -> None
in
match t with
| Some (Mty_ident p) -> normalize_package_path env p
| Some (Mty_signature _ | Mty_functor _ | Mty_alias _ | Mty_strengthen _ | Mty_for_hole) | None ->
match p with
Path.Pdot (p1, s) ->
let p1' = Env.normalize_module_path None env p1 in
if Path.same p1 p1' then p else
normalize_package_path env (Path.Pdot (p1', s))
| _ -> p
let rec check_scope_escape mark env level ty =
let orig_level = get_level ty in
if try_mark_node mark ty then begin
if level < get_scope ty then
raise_scope_escape_exn ty;
begin match get_desc ty with
| Tconstr (p, _, _) when level < Path.scope p ->
begin match !forward_try_expand_safe env ty with
| ty' ->
check_scope_escape mark env level ty'
| exception Cannot_expand ->
raise_escape_exn (Constructor p)
end
| Tpackage (p, fl) when level < Path.scope p ->
let p' = normalize_package_path env p in
if Path.same p p' then raise_escape_exn (Module_type p);
check_scope_escape mark env level
(newty2 ~level:orig_level (Tpackage (p', fl)))
| _ ->
iter_type_expr_with_stages
(fun env -> check_scope_escape mark env level) env ty
end;
end
let check_scope_escape env level ty =
with_type_mark begin fun mark -> try
check_scope_escape mark env level ty
with Escape e ->
raise (Escape { e with context = Some ty })
end
let rec update_scope scope ty =
if get_scope ty < scope then begin
if get_level ty < scope then raise_scope_escape_exn ty;
set_scope ty scope;
if !Clflags.principal then iter_type_expr (update_scope scope) ty
end
let update_scope_for tr_exn scope ty =
try
update_scope scope ty
with Escape e -> raise_for tr_exn (Escape e)
let rec update_level env level expand ty =
if get_level ty > level then begin
if level < get_scope ty then raise_scope_escape_exn ty;
match get_desc ty with
Tconstr(p, _tl, _abbrev) when level < Path.scope p ->
begin try
let ty' = !forward_try_expand_safe env ty in
link_type ty ty';
update_level env level expand ty'
with Cannot_expand ->
raise_escape_exn (Constructor p)
end
| Tconstr(p, (_ :: _ as tl), _) ->
let variance =
try (Env.find_type p env).type_variance
with Not_found -> List.map (fun _ -> Variance.unknown) tl in
let needs_expand =
expand ||
List.exists2
(fun var ty -> var = Variance.null && get_level ty > level)
variance tl
in
begin try
if not needs_expand then raise Cannot_expand;
let ty' = !forward_try_expand_safe env ty in
link_type ty ty';
update_level env level expand ty'
with Cannot_expand ->
set_level ty level;
iter_type_expr (update_level env level expand) ty
end
| Tpackage (p, fl) when level < Path.scope p ->
let p' = normalize_package_path env p in
if Path.same p p' then raise_escape_exn (Module_type p);
set_type_desc ty (Tpackage (p', fl));
update_level env level expand ty
| Tobject (_, ({contents=Some(p, _tl)} as nm))
when level < Path.scope p ->
set_name nm None;
update_level env level expand ty
| Tvariant row ->
begin match row_name row with
| Some (p, _tl) when level < Path.scope p ->
set_type_desc ty (Tvariant (set_row_name row None))
| _ -> ()
end;
set_level ty level;
iter_type_expr (update_level env level expand) ty
| Tfield(lab, _, ty1, _)
when lab = dummy_method && level < get_scope ty1 ->
raise_escape_exn Self
| _ ->
set_level ty level;
iter_type_expr_with_stages
(fun env -> update_level env level expand) env ty
end
let update_level env level ty =
if get_level ty > level then begin
let snap = snapshot () in
try
update_level env level false ty
with Escape _ ->
backtrack snap;
update_level env level true ty
end
let update_level_for tr_exn env level ty =
try
update_level env level ty
with Escape e -> raise_for tr_exn (Escape e)
let rec lower_contravariant env var_level visited contra ty =
let must_visit =
get_level ty > var_level &&
match Hashtbl.find visited (get_id ty) with
| done_contra -> contra && not done_contra
| exception Not_found -> true
in
if must_visit then begin
Hashtbl.add visited (get_id ty) contra;
let lower_rec = lower_contravariant env var_level visited in
match get_desc ty with
Tvar _ -> if contra then set_level ty var_level
| Tconstr (_, [], _) -> ()
| Tconstr (path, tyl, _abbrev) ->
let variance, maybe_expand =
try
let typ = Env.find_type path env in
typ.type_variance,
type_kind_is_abstract typ
with Not_found ->
List.map (fun _ -> Variance.unknown) tyl,
false
in
if List.for_all ((=) Variance.null) variance then () else
let not_expanded () =
List.iter2
(fun v t ->
if v = Variance.null then () else
if Variance.(mem May_weak v)
then lower_rec true t
else lower_rec contra t)
variance tyl in
if maybe_expand then
match !forward_try_expand_safe env ty with
| ty -> lower_rec contra ty
| exception Cannot_expand -> not_expanded ()
else not_expanded ()
| Tpackage (_, fl) ->
List.iter (fun (_n, ty) -> lower_rec true ty) fl
| Tarrow (_, t1, t2, _) ->
lower_rec true t1;
lower_rec contra t2
| _ ->
iter_type_expr_with_stages
(fun env -> lower_contravariant env var_level visited contra) env ty
end
let lower_variables_only env level ty =
simple_abbrevs := Mnil;
lower_contravariant env level (Hashtbl.create 7) true ty
let lower_contravariant env ty =
simple_abbrevs := Mnil;
lower_contravariant env !nongen_level (Hashtbl.create 7) false ty
let rec generalize_class_type' gen =
function
Cty_constr (_, params, cty) ->
List.iter gen params;
generalize_class_type' gen cty
| Cty_signature csig ->
gen csig.csig_self;
gen csig.csig_self_row;
Vars.iter (fun _ (_, _, ty) -> gen ty) csig.csig_vars;
Meths.iter (fun _ (_, _, ty) -> gen ty) csig.csig_meths
| Cty_arrow (_, ty, cty) ->
gen ty;
generalize_class_type' gen cty
let generalize_class_type cty =
generalize_class_type' generalize cty
let generalize_class_type_structure cty =
generalize_class_type' generalize_structure cty
let correct_levels ty =
duplicate_type ty
let limited_generalize ty0 ty =
let graph = TypeHash.create 17 in
let roots = ref [] in
let rec inverse pty ty =
match TypeHash.find_opt graph ty with
| Some parents -> parents := pty @ !parents
| None ->
let level = get_level ty in
if level > !current_level then begin
TypeHash.add graph ty (ref pty);
if (level = generic_level) || eq_type ty ty0 then
roots := ty :: !roots;
iter_type_expr (inverse [ty]) ty
end
in
let rec generalize_parents ~is_root ty =
if is_root || get_level ty <> generic_level then begin
set_level ty generic_level;
List.iter (generalize_parents ~is_root:false) !(TypeHash.find graph ty);
match get_desc ty with
Tvariant row ->
let more = row_more row in
let lv = get_level more in
if (TypeHash.mem graph more || lv > !current_level)
&& lv <> generic_level then set_level more generic_level
| _ -> ()
end
in
inverse [] ty;
List.iter (generalize_parents ~is_root:true) !roots;
TypeHash.iter
(fun ty _ ->
if get_level ty <> generic_level then
set_level ty !current_level)
graph
let limited_generalize_class_type rv cty =
generalize_class_type' (limited_generalize rv) cty
type inv_type_expr =
{ inv_type : type_expr;
mutable inv_parents : inv_type_expr list }
let rec inv_type hash pty ty =
try
let inv = TypeHash.find hash ty in
inv.inv_parents <- pty @ inv.inv_parents
with Not_found ->
let inv = { inv_type = ty; inv_parents = pty } in
TypeHash.add hash ty inv;
iter_type_expr (inv_type hash [inv]) ty
let compute_univars ty =
let inverted = TypeHash.create 17 in
inv_type inverted [] ty;
let node_univars = TypeHash.create 17 in
let rec add_univar univ inv =
match get_desc inv.inv_type with
Tpoly (_ty, tl) when List.memq (get_id univ) (List.map get_id tl) -> ()
| _ ->
try
let univs = TypeHash.find node_univars inv.inv_type in
if not (TypeSet.mem univ !univs) then begin
univs := TypeSet.add univ !univs;
List.iter (add_univar univ) inv.inv_parents
end
with Not_found ->
TypeHash.add node_univars inv.inv_type (ref(TypeSet.singleton univ));
List.iter (add_univar univ) inv.inv_parents
in
TypeHash.iter (fun ty inv -> if is_Tunivar ty then add_univar ty inv)
inverted;
fun ty ->
try !(TypeHash.find node_univars ty) with Not_found -> TypeSet.empty
let fully_generic ty =
with_type_mark begin fun mark ->
let rec aux ty =
if try_mark_node mark ty then
if get_level ty = generic_level then iter_type_expr aux ty
else raise Exit
in
try aux ty; true with Exit -> false
end
let rec find_repr p1 =
function
Mnil ->
None
| Mcons (Public, p2, ty, _, _) when Path.same p1 p2 ->
Some ty
| Mcons (_, _, _, _, rem) ->
find_repr p1 rem
| Mlink {contents = rem} ->
find_repr p1 rem
let abbreviations = ref (ref Mnil)
let rec copy ?partial ?keep_names copy_scope ty =
let copy = copy ?partial ?keep_names copy_scope in
match get_desc ty with
Tsubst (ty, _) -> ty
| desc ->
let level = get_level ty in
if level <> generic_level && partial = None then ty else
let forget =
if level = generic_level then generic_level else
match partial with
None -> assert false
| Some (free_univars, keep) ->
if not (is_Tpoly ty) && TypeSet.is_empty (free_univars ty) then
if keep then level else !current_level
else generic_level
in
if forget <> generic_level then
newty2 ~level:forget
(Tvar { name = None; jkind = Jkind.Builtin.any ~why:Dummy_jkind })
else
let t = newstub ~scope:(get_scope ty) (Jkind.Builtin.any ~why:Dummy_jkind) in
For_copy.redirect_desc copy_scope ty (Tsubst (t, None));
let desc' =
match desc with
| Tconstr (p, tl, _) ->
let abbrevs = proper_abbrevs tl !abbreviations in
begin match find_repr p !abbrevs with
Some ty when not (eq_type ty t) ->
Tlink ty
| _ ->
Tconstr (p, List.map copy tl,
ref (match !(!abbreviations) with
Mcons _ -> Mlink !abbreviations
| abbrev -> abbrev))
end
| Tvariant row ->
let more = row_more row in
let mored = get_desc more in
begin match mored with
Tsubst (_, Some ty2) ->
For_copy.redirect_desc copy_scope ty (Tsubst (ty2, None));
Tlink ty2
| _ ->
let keep = get_level more <> generic_level && partial = None in
let more' =
match mored with
Tsubst (ty, None) -> ty
| Tconstr _ | Tquote _ | Tsplice _ | Tnil | Tof_kind _ ->
copy more
| Tvar _ | Tunivar _ ->
if keep then more else newty mored
| _ -> assert false
in
let row =
match get_desc more' with
Tconstr (x,_,_) when not (is_fixed row) ->
let Row {fields; more; closed; name} = row_repr row in
create_row ~fields ~more ~closed ~name
~fixed:(Some (Reified x))
| _ -> row
in
let more', row =
match partial with
Some (free_univars, false) ->
let not_reither (_, f) =
match row_field_repr f with
Reither _ -> false
| _ -> true
in
let fields = row_fields row in
if row_closed row && not (is_fixed row)
&& TypeSet.is_empty (free_univars ty)
&& not (List.for_all not_reither fields) then
let more' = newvar (Jkind.Builtin.value ~why:Row_variable) in
(more',
create_row ~fields:(List.filter not_reither fields)
~more:more' ~closed:false ~fixed:None ~name:None)
else (more', row)
| _ -> (more', row)
in
For_copy.redirect_desc copy_scope more
(Tsubst(more', Some t));
Tvariant (copy_row copy true row keep more')
end
| Tvar { name; jkind } ->
let name = if keep_names = Some true then name else None in
Tvar { name; jkind = Jkind.instance jkind }
| Tunivar { name; jkind } ->
Tunivar { name; jkind = Jkind.instance jkind }
| Tobject (ty1, _) when partial <> None ->
Tobject (copy ty1, ref None)
| _ -> copy_type_desc ?keep_names copy desc
in
Transient_expr.set_stub_desc t desc';
t
let instance ?partial sch =
let partial =
match partial with
None -> None
| Some keep -> Some (compute_univars sch, keep)
in
For_copy.with_scope (fun copy_scope ->
copy ?partial copy_scope sch)
let generic_instance sch =
let old = !current_level in
current_level := generic_level;
let ty = instance sch in
current_level := old;
ty
let instance_list schl =
For_copy.with_scope (fun copy_scope ->
List.map (fun t -> copy copy_scope t) schl)
let get_new_abstract_name env s =
let name index =
if index = 0 && s <> "" && s.[String.length s - 1] <> '$' then s else
Printf.sprintf "%s%d" s index
in
let check index =
match Env.find_type_by_name (Longident.Lident (name index)) env with
| _ -> false
| exception Not_found -> true
in
let index = Misc.find_first_mono check in
name index
let new_local_type ?(loc = Location.none) ?manifest_and_scope origin jkind =
let manifest, expansion_scope =
match manifest_and_scope with
None -> None, Btype.lowest_level
| Some (ty, scope) -> Some ty, scope
in
{
type_params = [];
type_arity = 0;
type_kind = Type_abstract origin;
type_jkind = Jkind.disallow_right jkind;
type_ikind = Types.ikinds_todo "new_local_type";
type_private = Public;
type_manifest = manifest;
type_variance = [];
type_separability = [];
type_is_newtype = true;
type_expansion_scope = expansion_scope;
type_loc = loc;
type_attributes = [];
type_unboxed_default = false;
type_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
type_unboxed_version = None;
}
let new_local_jkind ?(loc = Location.none) ?manifest () =
{
jkind_manifest = manifest;
jkind_attributes = [];
jkind_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
jkind_loc = loc;
}
let existential_name name_counter ty =
let name =
match get_desc ty with
| Tvar { name = Some name } -> name
| _ ->
let name = Misc.letter_of_int !name_counter in
incr name_counter;
name
in
"$" ^ name
type existential_treatment =
| Keep_existentials_flexible
| Make_existentials_abstract of Pattern_env.t
let instance_constructor existential_treatment cstr =
For_copy.with_scope (fun copy_scope ->
let name_counter = ref 0 in
let declared_jkind_of existential =
match get_desc existential with
| Tvar { jkind } -> jkind
| Tvariant _ -> Jkind.Builtin.value ~why:Row_variable
| _ -> Misc.fatal_error "Ctype.instance_constructor"
in
let copy_existential =
match existential_treatment with
| Keep_existentials_flexible ->
fun existential ->
(copy copy_scope existential, declared_jkind_of existential)
| Make_existentials_abstract penv ->
fun existential ->
let jkind = declared_jkind_of existential in
let decl = new_local_type (Existential cstr.cstr_name) jkind in
let name = existential_name name_counter existential in
let env = penv.env in
let fresh_constr_scope = penv.equations_scope in
let (id, new_env) =
Env.enter_type (get_new_abstract_name env name) decl env
~scope:fresh_constr_scope in
Pattern_env.set_env penv new_env;
let to_unify = newty (Tconstr (Path.Pident id,[],ref Mnil)) in
let tv = copy copy_scope existential in
assert (is_Tvar tv);
link_type tv to_unify;
(tv, jkind)
in
let ty_ex = List.map copy_existential cstr.cstr_existentials in
let ty_res = copy copy_scope cstr.cstr_res in
let ty_args =
List.map (fun ca -> {ca with ca_type = copy copy_scope ca.ca_type}) cstr.cstr_args
in
(ty_args, ty_res, ty_ex)
)
let instance_parameterized_type ?keep_names sch_args sch =
For_copy.with_scope (fun copy_scope ->
let ty_args = List.map (fun t -> copy ?keep_names copy_scope t) sch_args in
let ty = copy copy_scope sch in
(ty_args, ty)
)
let instance_parameterized_kind args jkind =
For_copy.with_scope (fun copy_scope ->
let ty_args = List.map (fun t -> copy copy_scope t) args in
let jkind = Jkind.map_type_expr (copy copy_scope) jkind in
(ty_args, jkind)
)
let map_unsafe_mode_crossing f umc =
{ umc with unsafe_with_bounds = Jkind.With_bounds.map_type_expr f umc.unsafe_with_bounds }
let map_kind f = function
| (Type_abstract _ | Type_open) as k -> k
| Type_variant (cl, rep, mc) ->
Type_variant (
List.map
(fun c ->
{c with
cd_args = map_type_expr_cstr_args f c.cd_args;
cd_res = Option.map f c.cd_res
})
cl, rep, Option.map (map_unsafe_mode_crossing f) mc)
| Type_record (fl, rr, mc) ->
Type_record (
List.map
(fun l ->
{l with ld_type = f l.ld_type}
) fl, rr, Option.map (map_unsafe_mode_crossing f) mc)
| Type_record_unboxed_product (fl, rr, mc) ->
Type_record_unboxed_product (
List.map
(fun l ->
{l with ld_type = f l.ld_type}
) fl, rr, Option.map (map_unsafe_mode_crossing f) mc)
let instance_declaration decl =
For_copy.with_scope (fun copy_scope ->
let copy = copy ~keep_names:true copy_scope in
let rec instance decl =
{
decl with
type_params = List.map copy decl.type_params;
type_manifest = Option.map copy decl.type_manifest;
type_kind = map_kind copy decl.type_kind;
type_jkind = Jkind.map_type_expr copy decl.type_jkind;
type_unboxed_version = Option.map instance decl.type_unboxed_version;
}
in
instance decl
)
let generic_instance_declaration decl =
let old = !current_level in
current_level := generic_level;
let decl = instance_declaration decl in
current_level := old;
decl
let instance_class params cty =
let rec copy_class_type copy_scope = function
| Cty_constr (path, tyl, cty) ->
let tyl' = List.map (copy copy_scope) tyl in
let cty' = copy_class_type copy_scope cty in
Cty_constr (path, tyl', cty')
| Cty_signature sign ->
Cty_signature
{csig_self = copy copy_scope sign.csig_self;
csig_self_row = copy copy_scope sign.csig_self_row;
csig_vars =
Vars.map
(function (m, v, ty) -> (m, v, copy copy_scope ty))
sign.csig_vars;
csig_meths =
Meths.map
(function (p, v, ty) -> (p, v, copy copy_scope ty))
sign.csig_meths}
| Cty_arrow (l, ty, cty) ->
Cty_arrow (l, copy copy_scope ty, copy_class_type copy_scope cty)
in
For_copy.with_scope (fun copy_scope ->
let params' = List.map (copy copy_scope) params in
let cty' = copy_class_type copy_scope cty in
(params', cty')
)
let copy_sep ~copy_scope ~fixed ~partial ~bound_univars
~(visited : type_expr TypeHash.t) sch =
let free = compute_univars sch in
let delayed_copies = ref [] in
let add_delayed_copy t ty =
delayed_copies :=
(fun () -> Transient_expr.set_stub_desc t (Tlink (copy copy_scope ty))) ::
!delayed_copies
in
let rec copy_rec ~bound_univars ~may_share (ty : type_expr) =
let bound_univars =
match get_desc ty with
| Tpoly (_, tl) -> List.fold_right TypeSet.add tl bound_univars
| _ -> bound_univars
in
let copy_rec = copy_rec ~bound_univars in
let univars = TypeSet.inter (free ty) bound_univars in
if is_Tvar ty || may_share && TypeSet.is_empty univars then
if partial || get_level ty <> generic_level then ty else
let t = newstub ~scope:(get_scope ty) (Jkind.Builtin.any ~why:Dummy_jkind) in
add_delayed_copy t ty;
t
else try
TypeHash.find visited ty
with Not_found -> begin
let t = newstub ~scope:(get_scope ty) (Jkind.Builtin.any ~why:Dummy_jkind) in
TypeHash.add visited ty t;
let desc' =
match get_desc ty with
| Tvariant row ->
let more = row_more row in
let keep =
is_Tvar more && get_level more <> generic_level
in
if keep then
(add_delayed_copy t ty;
Tvar { name = None;
jkind = Jkind.for_non_float ~why:Polymorphic_variant })
else
let more' = copy_rec ~may_share:false more in
let fixed' = fixed && (is_Tvar more || is_Tunivar more) in
let row =
copy_row (copy_rec ~may_share:true) fixed' row keep more' in
Tvariant row
| Tfield (p, k, ty1, ty2) ->
Tfield (p, field_kind_internal_repr k,
copy_rec ~may_share:true ty1,
copy_rec ~may_share:false ty2)
| desc -> copy_type_desc (copy_rec ~may_share:true) desc
in
Transient_expr.set_stub_desc t desc';
t
end
in
let ty = copy_rec ~bound_univars ~may_share:true sch in
List.iter (fun force -> force ()) !delayed_copies;
ty
let instance_poly' copy_scope
~keep_names ~fixed ~partial ~copy_var univars sch =
let copy_var =
Option.value copy_var
~default:
(fun ty ->
match get_desc ty with
Tunivar { name; jkind } ->
if keep_names then newty (Tvar { name; jkind }) else newvar jkind
| _ -> assert false)
in
let vars = List.map copy_var univars in
let visited = TypeHash.create 17 in
List.iter2 (TypeHash.add visited) univars vars;
let bound_univars = List.fold_right TypeSet.add univars TypeSet.empty in
let ty = copy_sep ~copy_scope ~fixed ~partial ~bound_univars ~visited sch in
vars, ty
let instance_poly_fixed ?(keep_names=false) univars sch =
For_copy.with_scope (fun copy_scope ->
instance_poly' copy_scope
~keep_names ~fixed:true ~partial:false ~copy_var:None univars sch
)
let instance_poly ?(keep_names=false) univars sch =
For_copy.with_scope (fun copy_scope ->
snd (instance_poly' copy_scope
~keep_names ~fixed:false ~partial:false ~copy_var:None univars sch)
)
(** The body of a [Tpoly] will likely have references to the [Tunivar]s bound in
it. When asking for the jkind of a [Tpoly], we don't want to let those
vars escape the scope. To resolve this, we substitute all occurrences of
them with a [Tof_kind]. *)
let instance_poly_for_jkind univars sch =
if List.is_empty univars then sch else
let copy_var ty =
match get_desc ty with
| Tunivar { name = _; jkind } ->
newgenty (Tof_kind jkind)
| _ -> Misc.fatal_error "Ctype.instance_poly_for_jkind: expected Tunivar"
in
For_copy.with_scope (fun copy_scope ->
let _, ty =
instance_poly' copy_scope ~keep_names:false ~fixed:false ~partial:false
~copy_var:(Some copy_var) univars sch
in
ty
)
let () = Ikind.instance_poly_for_jkind' := instance_poly_for_jkind
let instance_label ~fixed lbl =
For_copy.with_scope (fun copy_scope ->
let vars, ty_arg =
match get_desc lbl.lbl_arg with
Tpoly (ty, tl) ->
instance_poly' copy_scope
~keep_names:false ~copy_var:None ~fixed ~partial:false tl ty
| _ ->
[], copy copy_scope lbl.lbl_arg
in
let ty_res = copy copy_scope lbl.lbl_res in
(vars, ty_arg, ty_res)
)
let prim_mode' mvars = function
| Primitive.Prim_global, _ ->
Locality.allow_right Locality.global, None
| Primitive.Prim_local, _ ->
Locality.allow_right Locality.local, None
| Primitive.Prim_poly, _ ->
match mvars with
| Some (mvar_l, (mvar_f, mvar_y)) -> mvar_l, Some (mvar_f, mvar_y)
| None -> assert false
let prim_mode mvar prim =
let mvar = Option.map
(fun mvar_l -> mvar_l, (Forkable.newvar (), Yielding.newvar ())) mvar
in
fst (prim_mode' mvar prim)
(** Returns a new mode variable whose locality is the given locality and
whose yieldingness is the given yieldingness, while all other axes are
from the given [m]. This function is too specific to be put in [mode.ml] *)
let with_locality_and_forkable_yielding (locality, fy) m =
let forkable = Option.map fst fy in
let yielding = Option.map snd fy in
let m' = Alloc.newvar () in
Locality.equate_exn (Alloc.proj_comonadic Areality m') locality;
let forkable =
Option.value ~default:(Alloc.proj_comonadic Forkable m) forkable
in
let yielding =
Option.value ~default:(Alloc.proj_comonadic Yielding m) yielding
in
Forkable.equate_exn (Alloc.proj_comonadic Forkable m') forkable;
Yielding.equate_exn (Alloc.proj_comonadic Yielding m') yielding;
let c =
{ Alloc.Comonadic.Const.max with
areality = Locality.Const.min;
forkable = Forkable.Const.min;
yielding = Yielding.Const.min}
in
Alloc.submode_exn (Alloc.meet_const c m') m;
Alloc.submode_exn (Alloc.meet_const c m) m';
m'
let curry_mode alloc arg : Alloc.Const.t =
let acc =
Alloc.Comonadic.Const.join
(Alloc.Const.close_over arg)
(Alloc.Const.partial_apply alloc)
in
Alloc.Const.merge {comonadic = acc; monadic = Alloc.Monadic.Const.legacy}
let rec instance_prim_locals locals mvar_l mvar_y macc (loc, yld) ty =
match locals, get_desc ty with
| l :: locals, Tarrow ((lbl,marg,mret),arg,ret,commu) ->
let marg = with_locality_and_forkable_yielding
(prim_mode' (Some (mvar_l, mvar_y)) l) marg
in
let macc =
Alloc.join [
Alloc.disallow_right mret;
Alloc.close_over marg;
Alloc.partial_apply macc
]
in
let mret =
match locals with
| [] -> with_locality_and_forkable_yielding (loc, yld) mret
| _ :: _ ->
let mret', _ = Alloc.newvar_above macc in
mret'
in
let ret = instance_prim_locals locals mvar_l mvar_y macc (loc, yld) ret in
newty2 ~level:(get_level ty) (Tarrow ((lbl,marg,mret),arg,ret, commu))
| _ :: _, _ -> assert false
| [], _ ->
ty
let instance_prim_layout env (desc : Primitive.description) ty =
if not desc.prim_is_layout_poly
then ty, None
else
let new_sort = ref None in
let get_jkind jkind sa =
let sort = match !new_sort with
| Some sort -> sort
| None ->
let sort = Jkind.Sort.(of_var (new_var ~level:!current_level)) in
new_sort := Some sort;
sort
in
let jkind = Jkind.set_layout jkind (Jkind.Layout.Sort (sort, sa)) in
Jkind.History.update_reason
jkind (Concrete_creation Layout_poly_in_external)
in
For_copy.with_scope (fun copy_scope ->
let rec inner mark ty =
let level = get_level ty in
if level = generic_level && try_mark_node mark ty then begin
begin match get_desc ty with
| Tvar ({ jkind; _ } as r) -> (
match Jkind.extract_layout env jkind with
| Ok (Any sa) ->
For_copy.redirect_desc copy_scope ty
(Tvar {r with jkind = get_jkind jkind sa})
| _ -> ())
| Tunivar ({ jkind; _ } as r) -> (
match Jkind.extract_layout env jkind with
| Ok (Any sa) ->
For_copy.redirect_desc copy_scope ty
(Tunivar {r with jkind = get_jkind jkind sa})
| _ -> ())
| _ -> ()
end;
iter_type_expr (inner mark) ty
end
in
with_type_mark (fun mark -> inner mark ty);
match !new_sort with
| Some sort ->
generic_instance ty, Some sort
| None -> ty, None)
let instance_prim_mode (desc : Primitive.description) ty =
let is_poly = function Primitive.Prim_poly, _ -> true | _ -> false in
if is_poly desc.prim_native_repr_res ||
List.exists is_poly desc.prim_native_repr_args then
let mode_l = Locality.newvar () in
let mode_fy = Forkable.newvar (), Yielding.newvar () in
let finalret =
prim_mode' (Some (mode_l, mode_fy)) desc.prim_native_repr_res
in
instance_prim_locals desc.prim_native_repr_args
mode_l mode_fy (Alloc.disallow_right Alloc.legacy) finalret ty,
Some mode_l, Some mode_fy
else
ty, None, None
let instance_prim env (desc : Primitive.description) ty =
let ty, sort = instance_prim_layout env desc ty in
let ty, mode_l, mode_y = instance_prim_mode desc ty in
ty, mode_l, mode_y, sort
let unify_var' =
ref (fun _env _ty1 _ty2 -> assert false)
let subst env level priv abbrev oty params args body =
if List.length params <> List.length args then raise Cannot_subst;
let old_level = !current_level in
current_level := level;
let body0 = newvar (Jkind.Builtin.any ~why:Dummy_jkind) in
let undo_abbrev =
match oty with
| None -> fun () -> ()
| Some ty ->
match get_desc ty with
Tconstr (path, tl, _) ->
let abbrev = proper_abbrevs tl abbrev in
memorize_abbrev abbrev priv path ty body0;
fun () -> forget_abbrev abbrev path
| _ -> assert false
in
abbreviations := abbrev;
let (params', body') = instance_parameterized_type params body in
abbreviations := ref Mnil;
let uenv = Expression {env; in_subst = true} in
try
!unify_var' uenv body0 body';
List.iter2 (!unify_var' uenv) params' args;
current_level := old_level;
body'
with Unify _ ->
current_level := old_level;
undo_abbrev ();
raise Cannot_subst
let jkind_subst env level params args jkind =
if List.length params <> List.length args then raise Cannot_subst;
let old_level = !current_level in
current_level := level;
let (params', jkind') = instance_parameterized_kind params jkind in
let uenv = Expression {env; in_subst = true} in
try
List.iter2 (!unify_var' uenv) params' args;
current_level := old_level;
jkind'
with Unify _ ->
current_level := old_level;
raise Cannot_subst
let apply ?(use_current_level = false) env params body args =
simple_abbrevs := Mnil;
let level = if use_current_level then !current_level else generic_level in
try
subst env level Public (ref Mnil) None params args body
with
Cannot_subst -> raise Cannot_apply
let previous_env = ref Env.empty
let check_abbrev_env env =
if not (Env.same_type_declarations env !previous_env) then begin
cleanup_abbrev ();
previous_env := env
end
let expand_abbrev_gen kind find_type_expansion env ty =
let path, args, abbrev = match get_desc ty with
| Tconstr (path,args,abbrev) -> path, args, abbrev
| _ -> assert false
in
check_abbrev_env env;
let level = get_level ty in
let scope = get_scope ty in
let lookup_abbrev = proper_abbrevs args abbrev in
let expansion =
match find_expans kind path !lookup_abbrev with
| None -> None
| Some ty' -> try
if level <> generic_level then update_level env level ty';
update_scope scope ty';
Some ty'
with Escape _ ->
forget_abbrev lookup_abbrev path;
None
in
begin match expansion with
| Some ty' -> ty'
| None ->
match find_type_expansion path env with
| exception Not_found ->
let path' = Env.normalize_type_path None env path in
if Path.same path path' then raise Cannot_expand
else newty2 ~level (Tconstr (path', args, abbrev))
| (params, body, lv) ->
let ty' =
try
subst env level kind abbrev (Some ty) params args body
with Cannot_subst -> raise_escape_exn Constraint
in
let scope = Int.max lv (get_scope ty) in
update_scope scope ty;
update_scope scope ty';
ty'
end
let expand_abbrev env ty =
expand_abbrev_gen Public Env.find_type_expansion env ty
let expand_head_once env ty =
try
expand_abbrev env ty
with Cannot_expand | Escape _ -> assert false
let safe_abbrev env ty =
let snap = Btype.snapshot () in
try ignore (expand_abbrev env ty); true with
Cannot_expand ->
Btype.backtrack snap;
false
| Escape _ ->
Btype.backtrack snap;
cleanup_abbrev ();
false
let rec try_expand_once_gen expand_abbrev env ty =
match get_desc ty with
Tconstr _ -> expand_abbrev env ty
| Tquote t ->
try_expand_once_gen expand_abbrev (incr_stage env) t |> new_quote_ty
| Tsplice t ->
try_expand_once_gen expand_abbrev (decr_stage env) t |> new_splice_ty
| Tquote_eval t ->
try_expand_once_gen expand_abbrev (incr_stage env) t |> new_quote_eval_ty
| _ -> raise Cannot_expand
let try_expand_once = try_expand_once_gen expand_abbrev
let try_expand_safe env ty =
let snap = Btype.snapshot () in
try try_expand_once env ty
with Escape _ ->
Btype.backtrack snap; cleanup_abbrev (); raise Cannot_expand
let rec try_reduce_once env t =
let path_must_be_toplevel env path =
if not (Env.path_is_toplevel_in_quotations env path) then
raise Cannot_expand
in
let try_reduce_poly env t = if is_Tpoly t then try_reduce_once env t else t in
match get_desc t with
| Tquote_eval t -> begin
match get_desc t with
| Tvar _ | Tunivar _ -> raise Cannot_expand
| Tarrow (a, t1, t2, c) ->
let t1' = new_quote_eval_ty t1 |> try_reduce_once env in
let t2' = new_quote_eval_ty t2 in
Tarrow (a, t1', t2', c)
| Ttuple tl ->
Ttuple (List.map (fun (l, t) -> (l, new_quote_eval_ty t)) tl)
| Tunboxed_tuple tl ->
Tunboxed_tuple (List.map (fun (l, t) -> (l, new_quote_eval_ty t)) tl)
| Tconstr (p, tl, a) ->
path_must_be_toplevel env p;
Tconstr (p, List.map new_quote_eval_ty tl, a)
| Tobject (t, ct) ->
Tobject (
try_reduce_once env (new_quote_eval_ty t),
ref (
Option.map
(fun (p, tl) ->
path_must_be_toplevel env p;
p, List.map new_quote_eval_ty tl)
!ct))
| Tfield (s, k, t_method, t_rest) ->
Tfield (
s, k,
try_reduce_poly env (new_quote_eval_ty t_method),
try_reduce_once env (new_quote_eval_ty t_rest))
| Tnil -> Tnil
| Tquote _ | Tsplice _ | Tquote_eval _ ->
Tquote_eval (try_reduce_once (incr_stage env) t)
| Tvariant row ->
let more = row_more row |> new_quote_eval_ty |> try_reduce_once env in
Tvariant (copy_row new_quote_eval_ty true row false more)
| Tpoly (t, tl) ->
let copy tv =
newty3 ~level:(get_level tv) ~scope:(get_scope tv) (get_desc tv)
|> new_splice_ty
in
let tl', t' =
For_copy.with_scope (fun copy_scope ->
instance_poly' copy_scope ~keep_names:true
~fixed:false ~partial:true ~copy_var:(Some copy) tl t)
in
let tl' =
List.map
(fun t -> match get_desc t with Tsplice uv -> uv | _ -> assert false)
tl'
in
Tpoly (new_quote_eval_ty t', tl')
| Trepr (t, sl) ->
Trepr (new_quote_eval_ty t, sl)
| Tpackage (p, fl) ->
path_must_be_toplevel env p;
Tpackage (p, List.map (fun (n, t) -> n, new_quote_eval_ty t) fl)
| Tof_kind _ -> raise Cannot_expand
| Tlink _ | Tsubst _ -> assert false
end |> newty2 ~level:(get_level t)
| Tsplice t -> begin
match get_desc t with
| Tquote t ->
t
| Tsplice _ -> try_reduce_once (decr_stage env) t |> new_splice_ty
| Tquote_eval _ -> try_reduce_once (decr_stage env) t |> new_splice_ty
| _ -> raise Cannot_expand
end
| Tquote t -> begin
match get_desc t with
| Tsplice t ->
t
| Tquote _ -> try_reduce_once (incr_stage env) t |> new_quote_ty
| Tquote_eval _ -> try_reduce_once (incr_stage env) t |> new_quote_ty
| _ -> raise Cannot_expand
end
| _ -> raise Cannot_expand
let rec try_reduce env ty =
let ty' = try_reduce_once env ty in
try try_reduce env ty'
with Cannot_expand -> ty'
let expand_eval_abbrev env ty =
match get_desc ty with
| Tconstr (path, [_], _) when Path.same path Predef.path_eval ->
try_expand_once env ty
| _ -> raise Cannot_expand
let try_expand_eval_once = try_expand_once_gen expand_eval_abbrev
let try_expand_head ?(fuel = 5000)
(try_once : Env.t -> type_expr -> type_expr) (env : Env.t) ty =
let rec loop try_once env ty ~fuel =
if fuel <= 0 then raise Cannot_expand;
let ty' = try_once env ty in
try loop try_once env ty' ~fuel:(fuel - 1)
with Cannot_expand ->
try try_reduce env ty'
with Cannot_expand -> ty'
in
try loop try_once env ty ~fuel
with Cannot_expand -> try_reduce env ty
let reduce_head ~expand_eval env ty =
let try_once =
if expand_eval
then try_expand_eval_once
else (fun _env _ty -> raise Cannot_expand)
in
try try_expand_head try_once env ty
with Cannot_expand -> ty
let expand_head_unif env ty =
try
try_expand_head try_expand_once env ty
with
| Cannot_expand -> ty
| Escape e -> raise_for Unify (Escape e)
let expand_head env ty =
try try_expand_head try_expand_safe env ty
with Cannot_expand -> ty
let _ = forward_try_expand_safe := try_expand_safe
let rec env ty =
match get_desc ty with
Tconstr (p, _, _) ->
begin match Env.find_type p env with
| exception Not_found -> May_have_typedecl
| decl ->
if not (type_kind_is_abstract decl) then Typedecl(p, p, decl)
else begin
match try_expand_safe env ty with
| exception Cannot_expand -> May_have_typedecl
| ty ->
match extract_concrete_typedecl env ty with
| Typedecl(_, p', decl) -> Typedecl(p, p', decl)
| Has_no_typedecl -> Has_no_typedecl
| May_have_typedecl -> May_have_typedecl
end
end
| Tpoly(ty, _) -> extract_concrete_typedecl env ty
| Trepr _ -> Has_no_typedecl
| Tquote ty -> extract_concrete_typedecl (incr_stage env) ty
| Tsplice ty -> extract_concrete_typedecl (decr_stage env) ty
| Tquote_eval ty -> extract_concrete_typedecl (incr_stage env) ty
| Tarrow _ | Ttuple _ | Tunboxed_tuple _ | Tobject _ | Tfield _ | Tnil
| Tvariant _ | Tpackage _ | Tof_kind _ -> Has_no_typedecl
| Tvar _ | Tunivar _ -> May_have_typedecl
| Tlink _ | Tsubst _ -> assert false
let expand_abbrev_opt env ty =
expand_abbrev_gen Private Env.find_type_expansion_opt env ty
let safe_abbrev_opt env ty =
let snap = Btype.snapshot () in
try ignore (expand_abbrev_opt env ty); true
with Cannot_expand | Escape _ ->
Btype.backtrack snap;
false
let try_expand_once_opt = try_expand_once_gen expand_abbrev_opt
let try_expand_safe_opt env ty =
let snap = Btype.snapshot () in
try try_expand_once_opt env ty
with Escape _ ->
Btype.backtrack snap; raise Cannot_expand
let expand_head_opt env ty =
try try_expand_head try_expand_safe_opt env ty with Cannot_expand -> ty
let is_principal ty =
not !Clflags.principal || get_level ty = generic_level
type unwrapped_type_expr =
{ ty : type_expr
; modality : Mode.Modality.Const.t
; or_null : (type_declaration * unwrapped_type_expr) option;
}
let mk_unwrapped_type_expr ty =
{ ty; modality = Mode.Modality.Const.id; or_null = None }
type unbox_result =
| Stepped of unwrapped_type_expr
| Stepped_record_unboxed_product of unwrapped_type_expr list
| Final_result
| Missing of Path.t
let unbox_once env ty =
match get_desc ty.ty with
| Tconstr (p, args, _) ->
begin match Env.find_type p env with
| exception Not_found -> Missing p
| decl ->
let apply ty2 ~ =
let , = List.split extra_substs in
apply env (extra_params @ decl.type_params) ty2 (extra_args @ args)
in
begin match find_unboxed_type decl with
| Some (ty2, modality) ->
let =
match Env.find_type_descrs p env with
| Type_variant ([ ({ cstr_generalized = true } as cstr) ], _, _) ->
let res_args =
match get_desc cstr.Types.cstr_res with
| Tconstr (_, res_args, _) -> res_args
| _ -> Misc.fatal_error "Ctype.unbox_once: cstr_res"
in
Btype.Jkind0.gadt_payload_subst
~projected_params:args
~res_args
~payload_tys:[ty2]
~get_free_vars:(free_variable_set_of_list env)
| Type_variant ([{ cstr_generalized = false }], _, _) -> []
| Type_variant (_not_one, _, _) ->
Misc.fatal_error "Ctype.unbox_once: not just one constructor"
| Type_abstract _ | Type_record _
| Type_record_unboxed_product _ | Type_open -> []
| exception Not_found ->
Misc.fatal_error "Ctype.unbox_once: expected to find [p] in [env]"
in
Stepped { ty = apply ty2 ~extra_substs; modality; or_null = None }
| None -> begin match decl.type_kind with
| Type_record_unboxed_product ([_], Record_unboxed_product, _) ->
Misc.fatal_error "Ctype.unbox_once"
| Type_record_unboxed_product
((_::_::_ as lbls), Record_unboxed_product, _) ->
Stepped_record_unboxed_product
(List.map (fun ld -> { ty = apply ld.ld_type ~extra_substs:[];
modality = ld.ld_modalities;
or_null = None }) lbls)
| Type_record_unboxed_product ([], _, _) ->
Misc.fatal_error "Ctype.unboxed_once: fieldless record"
| Type_variant (cstrs, Variant_with_null, _) ->
begin match Datarepr.find_variant_with_null_payload cstrs with
| Some
{ payload_arg = { ca_type; ca_modalities = modality; _ };
_ } ->
Stepped
{ ty = apply ca_type ~extra_substs:[];
modality;
or_null = Some (decl, ty) }
| None ->
Misc.fatal_error "Invalid constructor for Variant_with_null"
end
| Type_abstract _ | Type_record _ | Type_variant _ | Type_open ->
Final_result
end
end
end
| Tpoly (ty, univars) ->
Stepped
{ ty = instance_poly_for_jkind univars ty
; modality = Mode.Modality.Const.id
; or_null = None }
| _ -> Final_result
let contained_without_boxing env ty =
match get_desc ty with
| Tconstr _ ->
begin match unbox_once env (mk_unwrapped_type_expr ty) with
| Stepped { ty; modality = _; or_null = _ } -> [ty]
| Stepped_record_unboxed_product tys ->
List.map (fun { ty; _ } -> ty) tys
| Final_result | Missing _ -> []
end
| Tunboxed_tuple labeled_tys ->
List.map snd labeled_tys
| Tpoly (ty, _) -> [ty]
| Trepr (_, _) -> Misc.fatal_error "Ctype.contained_without_boxing: repr"
| Tvar _ | Tarrow _ | Ttuple _ | Tobject _ | Tfield _ | Tnil | Tlink _
| Tsubst _ | Tvariant _ | Tunivar _ | Tpackage _ | Tof_kind _
| Tquote _ | Tsplice _ | Tquote_eval _ -> []
let rec get_unboxed_type_representation ~modality ~or_null env ty_prev ty fuel =
if fuel < 0 then Error { ty; modality; or_null }
else
let ty = expand_head_opt env ty in
match unbox_once env { ty; modality; or_null } with
| Stepped { ty = ty2; modality = modality2; or_null = or_null2 } ->
let modality = Mode.Modality.Const.concat modality ~then_:modality2 in
begin match or_null, or_null2 with
| None, or_null | or_null, None ->
get_unboxed_type_representation ~modality ~or_null env ty ty2 (fuel - 1)
| Some _, Some _ ->
Ok { ty = ty_prev; modality; or_null }
end
| Stepped_record_unboxed_product _ | Final_result ->
Ok { ty; modality; or_null }
| Missing _ -> Ok { ty = ty_prev; modality; or_null }
let get_unboxed_type_representation env ty =
get_unboxed_type_representation ~modality:Mode.Modality.Const.id
~or_null:None env ty ty 100
let get_unboxed_type_approximation env ty =
match get_unboxed_type_representation env ty with
| Ok ty | Error ty -> ty
let type_equal' = ref (fun _ _ _ -> Misc.fatal_error "type_equal")
let type_jkind_purely_if_principal' =
ref (fun _ _ -> Misc.fatal_error "type_jkind_purely_if_principal")
let mk_is_abstract env p =
let decl =
try Env.find_type p env
with Not_found ->
Misc.fatal_errorf_doc "mk_is_abstract: type %a not found in environment"
Path.print p
in
match decl.type_kind with
| Type_abstract _ ->
begin match decl.type_manifest with
| None -> true
| Some _ -> false
end
| Type_variant _ | Type_record _ | Type_open | Type_record_unboxed_product _
-> false
let mk_jkind_context env jkind_of_type =
let lookup_type p =
match Env.find_type p env with
| decl -> Some decl
| exception Not_found -> None
in
{ Jkind.jkind_of_type;
is_abstract = mk_is_abstract env;
lookup_type;
}
let apply_layout_wrapping_l ~env
~unwrapped_ty:{ ty = _; or_null; modality = _ }
jkind : (_, unwrapped_type_expr) Result.t =
let get_layout jkind =
match Jkind.extract_layout env jkind with
| Ok l -> l
| Error _ -> Jkind_types.Layout.Any Jkind_types.Scannable_axes.max
in
match or_null with
| Some (_, prev) ->
begin match Jkind.apply_or_null_l jkind with
| Ok jkind -> Ok (get_layout jkind)
| Error () -> Error prev
end
| None ->
Ok (get_layout jkind)
let apply_jkind_wrapping_l ~env ~level
~unwrapped_ty:{ ty; or_null; modality } jkind =
begin
match or_null with
| Some (decl, _) ->
let instance_jkind =
jkind_subst env level decl.type_params [ty] decl.type_jkind
in
begin match
apply_layout_wrapping_l ~env
~unwrapped_ty:{ ty; modality; or_null } jkind
with
| Ok layout -> Ok (Jkind.set_layout instance_jkind layout)
| Error _ as e -> e
end
| None -> Ok jkind
end
|> Result.map (Jkind.apply_modality_l modality)
let apply_jkind_wrapping_r ~unwrapped_ty:{ ty = _; modality; or_null } jkind =
begin
if Option.is_some or_null then
match Jkind.apply_or_null_r jkind with
| Ok jkind -> jkind
| Error () ->
Misc.fatal_error "Ctype.apply_jkind_wrapping_r: nested or_nulls"
else
jkind
end
|> Jkind.apply_modality_r modality
let rec estimate_type_jkind ~expand_component ~ignore_mod_bounds env ty =
match get_desc ty with
| Tvar { jkind } -> Jkind.disallow_right jkind
| Tarrow _ -> Jkind.for_arrow
| Ttuple elts -> Jkind.for_boxed_tuple elts
| Tunboxed_tuple ltys ->
let rec compute_ty_modality_layout unwrapped_ty =
let jkind =
estimate_type_jkind ~expand_component ~ignore_mod_bounds env
unwrapped_ty.ty
in
match apply_layout_wrapping_l ~env ~unwrapped_ty jkind with
| Ok layout -> (unwrapped_ty.ty, unwrapped_ty.modality), layout
| Error prev_unwrapped_ty -> compute_ty_modality_layout prev_unwrapped_ty
in
let tys_modalities, layouts =
List.map
(fun (_lbl, ty) -> compute_ty_modality_layout (expand_component env ty))
ltys
|> List.split
in
Jkind.Builtin.product ~why:Unboxed_tuple tys_modalities layouts
| Tconstr (p, args, _) -> begin try
let type_decl = Env.find_type p env in
let jkind = type_decl.type_jkind in
if not ignore_mod_bounds
&& Jkind.has_with_bounds jkind
&& List.compare_length_with args 0 <> 0
then
let level = get_level ty in
jkind_subst env level type_decl.type_params args jkind
else
jkind
with
| Cannot_subst | Not_found -> Jkind.Builtin.any ~why:(Missing_cmi p)
end
| Tobject _ -> Jkind.for_object
| Tfield _ -> Jkind.Builtin.value ~why:Tfield
| Tquote ty ->
estimate_type_jkind ~expand_component ~ignore_mod_bounds (incr_stage env) ty
|> Jkind.map_type_expr new_quote_ty
| Tsplice ty ->
estimate_type_jkind ~expand_component ~ignore_mod_bounds (decr_stage env) ty
|> Jkind.map_type_expr new_splice_ty
| Tquote_eval ty ->
estimate_type_jkind ~expand_component ~ignore_mod_bounds (incr_stage env) ty
|> Jkind.map_type_expr new_quote_ty
| Tnil -> Jkind.Builtin.value ~why:Tnil
| Tlink _ | Tsubst _ -> assert false
| Tvariant row ->
Jkind.for_boxed_row row
| Tunivar { jkind } -> Jkind.disallow_right jkind
| Tpoly (ty, univars) ->
instance_poly_for_jkind univars ty
|> estimate_type_jkind ~expand_component ~ignore_mod_bounds env
| Trepr (ty, _sort_vars) ->
estimate_type_jkind ~expand_component ~ignore_mod_bounds env ty
| Tof_kind jkind ->
Jkind.mark_best jkind
| Tpackage _ -> Jkind.for_non_float ~why:First_class_module
let rec estimate_type_jkind_unwrapped
level ~expand_component env ~unwrapped_ty =
match
estimate_type_jkind ~expand_component ~ignore_mod_bounds:false env
unwrapped_ty.ty
|> apply_jkind_wrapping_l ~env ~level ~unwrapped_ty
with
| Ok jkind -> jkind
| Error prev_unwrapped_ty ->
estimate_type_jkind_unwrapped level ~expand_component env
~unwrapped_ty:prev_unwrapped_ty
let type_jkind env ty =
let unwrapped_ty = get_unboxed_type_approximation env ty in
estimate_type_jkind_unwrapped (get_level ty) ~unwrapped_ty
~expand_component:get_unboxed_type_approximation env
let type_jkind_purely env ty =
if !Clflags.principal || Env.has_local_constraints env then
let snap = Btype.snapshot () in
let jkind = type_jkind env ty in
Btype.backtrack snap;
jkind
else
type_jkind env ty
let type_jkind_purely_if_principal env ty =
match is_principal ty with
| true -> Some (type_jkind_purely env ty)
| false -> None
let () = type_jkind_purely_if_principal' := type_jkind_purely_if_principal
let estimate_type_jkind =
estimate_type_jkind
~expand_component:(fun _env ty -> mk_unwrapped_type_expr ty)
let mk_jkind_context_check_principal env =
mk_jkind_context env (type_jkind_purely_if_principal env)
let mk_jkind_context_always_principal env =
mk_jkind_context env (fun ty -> Some (type_jkind_purely env ty))
let constrain_type_jkind ~fixed env ty jkind =
let rec loop ~fuel ~expanded env ty ty's_jkind jkind =
let type_equal = !type_equal' env in
let context = mk_jkind_context_check_principal env in
if Jkind.is_obviously_max jkind then Ok () else
if fuel < 0 then
Error (
Jkind.Violation.of_ ~context env (
Not_a_subjkind (ty's_jkind, jkind, [Constrain_ran_out_of_fuel])))
else
match get_desc ty with
| Tvar { jkind = ty's_jkind } when not fixed ->
let jkind_inter =
Jkind.intersection_or_error ~type_equal ~context
~reason:Tyvar_refinement_intersection env
ty's_jkind jkind
in
Result.map (set_var_jkind ty) jkind_inter
| Tpoly (t, _) ->
loop ~fuel ~expanded:false env t ty's_jkind jkind
| Tquote ty ->
loop ~fuel ~expanded (incr_stage env) ty ty's_jkind jkind
| Tsplice ty ->
loop ~fuel ~expanded (decr_stage env) ty ty's_jkind jkind
| Tquote_eval ty ->
loop ~fuel ~expanded (incr_stage env) ty ty's_jkind jkind
| _ ->
if !Clflags.ikinds_debug
then
Format.eprintf
"@[<v>[ikind-ctype] constrain_type_jkind: sub_or_intersect call@,\
[ikind-ctype] lhs(ty_jkind)=%a@,\
[ikind-ctype] rhs(bound)=%a@]@."
(Format_doc.compat (Jkind.format env))
ty's_jkind
(Format_doc.compat (Jkind.format env))
jkind;
let sub_result =
Ikind.sub_or_intersect ~type_equal ~context env
ty's_jkind jkind
in
if !Clflags.ikinds_debug
then
Format.eprintf
"[ikind-ctype] constrain_type_jkind: sub_or_intersect=%s@."
(match sub_result with
| Sub -> "Sub"
| Disjoint _ -> "Disjoint"
| May_have_intersection _ -> "May_have_intersection");
match sub_result with
| Sub -> Ok ()
| Disjoint sub_failure_reasons ->
Error (Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind,
Nonempty_list.to_list sub_failure_reasons)))
| May_have_intersection sub_failure_reasons ->
if !Clflags.ikinds_debug
then begin
let verbosity =
Jkind.Format_verbosity.Expanded_with_all_mod_bounds
in
Format.eprintf
"@[<v>[ikind-ctype] constrain_type_jkind: may_intersect \
reasons=[%s]@,\
[ikind-ctype] lhs(verbose)=%a@,\
[ikind-ctype] rhs(verbose)=%a@,\
[ikind-ctype] lhs.mod_bounds=%a@,\
[ikind-ctype] rhs.mod_bounds=%a@,\
[ikind-ctype] lhs.with_bounds=%a@,\
[ikind-ctype] rhs.with_bounds=%a@]@."
(String.concat ", "
(List.map
(fun (reason : Jkind.Sub_failure_reason.t) ->
match reason with
| Axis_disagreement (Jkind_axis.Axis.Pack axis) ->
"Axis_disagreement("
^ Jkind_axis.Axis.name axis
^ ")"
| Layout_disagreement -> "Layout_disagreement"
| With_bounds_on_left -> "With_bounds_on_left"
| Constrain_ran_out_of_fuel ->
"Constrain_ran_out_of_fuel")
(Misc.Nonempty_list.to_list sub_failure_reasons)))
(Format_doc.compat
(Jkind.format_verbose ~verbosity env))
ty's_jkind
(Format_doc.compat
(Jkind.format_verbose ~verbosity env))
jkind
Jkind.Mod_bounds.debug_print
ty's_jkind.jkind.mod_bounds
Jkind.Mod_bounds.debug_print
jkind.jkind.mod_bounds
Jkind.With_bounds.debug_print
ty's_jkind.jkind.with_bounds
Jkind.With_bounds.debug_print
jkind.jkind.with_bounds;
end;
let sub_failure_reasons = Nonempty_list.to_list sub_failure_reasons in
let product ~fuel unwrapped_tys =
let num_components = List.length unwrapped_tys in
let recur ty's_jkinds jkinds =
let results =
Misc.Stdlib.List.map3
(fun unwrapped_ty ty's_jkind jkind ->
let jkind = apply_jkind_wrapping_r jkind ~unwrapped_ty in
loop ~fuel ~expanded:false env unwrapped_ty.ty ty's_jkind
jkind)
unwrapped_tys ty's_jkinds jkinds
in
if List.for_all Result.is_ok results
then Ok ()
else Error (Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind, sub_failure_reasons)))
in
begin match Jkind.decompose_product env ty's_jkind,
Jkind.decompose_product env jkind with
| Some ty's_jkinds, Some jkinds
when List.length ty's_jkinds = num_components
&& List.length jkinds = num_components ->
recur ty's_jkinds jkinds
| Some ty's_jkinds, None
when Jkind.has_layout_any env jkind
&& List.length ty's_jkinds = num_components ->
recur ty's_jkinds (List.init num_components (fun _ -> jkind))
| _ ->
Error (Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind, sub_failure_reasons)))
end
in
let or_null ~fuel ty modality =
let error () =
Error (Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind, sub_failure_reasons)))
in
let jkind = Jkind.apply_modality_r modality jkind in
match
Jkind.apply_or_null_r jkind
with
| Ok jkind ->
(match
estimate_jkind_and_loop ~fuel ~expanded:false env ty jkind
with
| Ok () -> Ok ()
| Error _ ->
error ())
| Error () ->
error ()
in
match get_desc ty with
| Tconstr _ ->
if not expanded
then
let ty = expand_head_opt env ty in
estimate_jkind_and_loop ~fuel ~expanded:true env ty jkind
else
begin match unbox_once env (mk_unwrapped_type_expr ty) with
| Missing path ->
Error (Jkind.Violation.of_ ~context ~missing_cmi:path env
(Not_a_subjkind (ty's_jkind, jkind,
sub_failure_reasons)))
| Final_result ->
Error
(Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind, sub_failure_reasons)))
| Stepped { ty; modality; or_null = None } ->
let jkind = Jkind.apply_modality_r modality jkind in
estimate_jkind_and_loop ~fuel:(fuel - 1) ~expanded:false env ty
jkind
| Stepped { ty; modality; or_null = Some _ } ->
or_null ~fuel:(fuel - 1) ty modality
| Stepped_record_unboxed_product unwrapped_tys ->
product ~fuel:(fuel - 1) unwrapped_tys
end
| Tunboxed_tuple ltys ->
product ~fuel (List.map (fun (_, ty) ->
mk_unwrapped_type_expr ty) ltys)
| _ ->
Error (Jkind.Violation.of_ ~context env
(Not_a_subjkind (ty's_jkind, jkind, sub_failure_reasons)))
and estimate_jkind_and_loop ~fuel ~expanded env ty jkind : _ result =
let jkind = Jkind.fully_expand_aliases env jkind in
let ignore_mod_bounds = Jkind.mod_bounds_are_obviously_max jkind in
let ty's_jkind = estimate_type_jkind ~ignore_mod_bounds env ty in
loop ~fuel ~expanded env ty ty's_jkind jkind
in
estimate_jkind_and_loop ~fuel:100 ~expanded:false env ty
(Jkind.disallow_left jkind)
let estimate_type_jkind = estimate_type_jkind ~ignore_mod_bounds:false
let type_sort ~why ~fixed env ty =
let jkind, sort = Jkind.of_new_sort_var ~level:!current_level ~why in
match constrain_type_jkind ~fixed env ty jkind with
| Ok _ -> Ok sort
| Error _ as e -> e
let check_type_jkind env ty jkind =
constrain_type_jkind ~fixed:true env ty jkind
let constrain_type_jkind env ty jkind =
constrain_type_jkind ~fixed:false env ty jkind
let () =
Env.constrain_type_jkind := constrain_type_jkind
let check_type_externality env ty ext =
let upper_bound =
Jkind.set_externality_upper_bound (Jkind.Builtin.any ~why:Dummy_jkind) ext
in
match check_type_jkind env ty upper_bound with
| Ok () -> true
| Error _ -> false
let check_type_nullability env ty null =
let upper_bound =
Jkind.set_root_nullability (Jkind.Builtin.any ~why:Dummy_jkind) null
in
match check_type_jkind env ty upper_bound with
| Ok () -> true
| Error _ -> false
let check_type_separability jkind env ty sep =
let upper_bound = Jkind.set_root_separability jkind sep in
match check_type_jkind env ty upper_bound with
| Ok () -> true
| Error _ -> false
let is_always_gc_ignorable env ty =
check_type_externality env ty
(Jkind_axis.Externality.upper_bound_if_is_always_gc_ignorable ())
||
check_type_separability (Jkind.Builtin.scannable ~why:Dummy_jkind) env ty
(Jkind_axis.Separability.upper_bound_if_is_always_gc_ignorable ())
let check_type_separability env ty sep =
check_type_separability (Jkind.Builtin.any ~why:Dummy_jkind) env ty sep
let check_type_jkind_exn env texn ty jkind =
match check_type_jkind env ty jkind with
| Ok _ -> ()
| Error err -> raise_for texn (Bad_jkind (ty,err))
let constrain_type_jkind_exn env texn ty jkind =
match constrain_type_jkind env ty jkind with
| Ok _ -> ()
| Error err -> raise_for texn (Bad_jkind (ty,err))
let rec intersect_type_jkind ~reason env ty1 jkind2 =
match get_desc ty1 with
| Tpoly (ty, _) -> intersect_type_jkind ~reason env ty jkind2
| _ ->
let type_equal = !type_equal' env in
let jkind1 = type_jkind env ty1 in
let context = mk_jkind_context_check_principal env in
let jkind1 = Jkind.round_up ~context env jkind1 in
let jkind2 = Jkind.round_up ~context env jkind2 in
match jkind1, jkind2 with
| Some jkind1, Some jkind2 ->
Jkind.intersection ~type_equal ~context ~reason env jkind1 jkind2
| _, _ -> Jkind.Unknown
let unification_jkind_check uenv ty jkind =
if not (in_subst_mode uenv) then
match !lmode with
| Perform_checks -> constrain_type_jkind_exn (get_env uenv) Unify ty jkind
| Delay_checks r -> r := (ty,jkind) :: !r
let check_and_update_generalized_ty_jkind ?name ~loc ty =
let generalization_check level jkind =
if level = generic_level then
Jkind.History.(update_reason jkind (Generalized (name, loc)))
else jkind
in
let rec inner mark ty =
let level = get_level ty in
if try_mark_node mark ty then begin
begin match get_desc ty with
| Tvar ({ jkind; _ } as r) ->
let new_jkind = generalization_check level jkind in
set_type_desc ty (Tvar {r with jkind = new_jkind})
| Tunivar ({ jkind; _ } as r) ->
let new_jkind = generalization_check level jkind in
set_type_desc ty (Tunivar {r with jkind = new_jkind})
| _ -> ()
end;
iter_type_expr (inner mark) ty
end
in
with_type_mark (fun mark -> inner mark ty)
let is_principal ty =
not !Clflags.principal || get_level ty = generic_level
let full_expand ~may_forget_scope env ty =
let ty =
if may_forget_scope then
try expand_head_unif env ty with Unify_trace _ ->
with_level ~level:(get_level ty) begin fun () ->
try try_expand_head try_expand_safe env (correct_levels ty) with
| Cannot_expand -> ty
end
else expand_head env ty
in
match get_desc ty with
Tobject (fi, {contents = Some (_, v::_)}) when is_Tvar v ->
newty2 ~level:(get_level ty) (Tobject (fi, ref None))
| _ ->
ty
let generic_abbrev env path =
try
let (_, body, _) = Env.find_type_expansion path env in
get_level body = generic_level
with
Not_found ->
false
let generic_private_abbrev env path =
try
match Env.find_type path env with
{type_kind = Type_abstract _;
type_private = Private;
type_manifest = Some body} ->
get_level body = generic_level
| _ -> false
with Not_found -> false
let is_contractive env p =
try
let decl = Env.find_type p env in
in_pervasives p && decl.type_manifest = None || is_datatype decl
with Not_found -> false
exception Occur
let rec occur_rec env visited allow_recursive parents ty0 ty =
if not_marked_node visited ty then begin
if eq_type ty ty0 then raise Occur;
begin match get_desc ty with
Tconstr(p, _tl, _abbrev) ->
if allow_recursive && is_contractive env p then () else
begin try
if TypeSet.mem ty parents then raise Occur;
let parents = TypeSet.add ty parents in
iter_type_expr (occur_rec env visited allow_recursive parents ty0) ty
with Occur -> try
let ty' = try_expand_head try_expand_safe env ty in
occur_rec env visited allow_recursive parents ty0 ty'
with Cannot_expand ->
raise Occur
end
| Tobject _ | Tvariant _ ->
()
| _ ->
if allow_recursive || TypeSet.mem ty parents then () else begin
let parents = TypeSet.add ty parents in
iter_type_expr_with_stages
(fun env -> occur_rec env visited allow_recursive parents ty0)
env ty
end
end;
ignore (try_mark_node visited ty)
end
let type_changed = ref false
let merge r b = if b then r := true
let occur uenv ty0 ty =
let env = get_env uenv in
let allow_recursive = allow_recursive_equations uenv in
let old = !type_changed in
try
while
type_changed := false;
if not (eq_type ty0 ty) then
with_type_mark (fun mark ->
occur_rec env mark allow_recursive TypeSet.empty ty0 ty);
!type_changed
do () done;
merge type_changed old
with exn ->
merge type_changed old;
raise exn
let occur_for tr_exn uenv t1 t2 =
try
occur uenv t1 t2
with Occur -> raise_for tr_exn (Rec_occur(t1, t2))
let occur_in env ty0 t =
try occur (Expression {env; in_subst = false}) ty0 t; false with Occur -> true
let rec local_non_recursive_abbrev ~allow_rec strict visited env p ty =
if not (List.memq (get_id ty) visited) then begin
match get_desc ty with
Tconstr(p', args, _abbrev) ->
if Path.same p p' then raise Occur;
if allow_rec && not strict && is_contractive env p' then () else
let visited = get_id ty :: visited in
begin try
local_non_recursive_abbrev ~allow_rec strict visited env p
(try_expand_head try_expand_safe_opt env ty)
with Cannot_expand ->
let params =
try (Env.find_type p' env).type_params
with Not_found -> args
in
List.iter2
(fun tv ty ->
let strict = strict || not (is_Tvar tv) in
local_non_recursive_abbrev ~allow_rec strict visited env p ty)
params args
end
| Tobject _ | Tvariant _ when not strict ->
()
| _ ->
if strict || not allow_rec then
let visited = get_id ty :: visited in
iter_type_expr_with_stages
(fun env ->
local_non_recursive_abbrev ~allow_rec true visited env p)
env ty
end
let local_non_recursive_abbrev uenv p ty =
let env = get_env uenv in
let allow_rec = allow_recursive_equations uenv in
try
wrap_trace_gadt_instances env
(local_non_recursive_abbrev ~allow_rec false [] env p) ty;
true
with Occur -> false
let unify_univar env t1 t2 jkind1 jkind2 pairs =
if not (Jkind.equal env jkind1 jkind2) then
raise Cannot_unify_universal_variables;
let rec inner t1 t2 = function
(cl1, cl2) :: rem ->
let find_univ t cl =
List.find_map (fun (t', r) ->
if eq_type t t' then Some r else None
) cl
in
begin match find_univ t1 cl1, find_univ t2 cl2 with
Some {contents=Some t'2}, Some _ when eq_type t2 t'2 ->
()
| Some({contents=None} as r1), Some({contents=None} as r2) ->
set_univar r1 t2; set_univar r2 t1
| None, None ->
inner t1 t2 rem
| _ ->
raise Cannot_unify_universal_variables
end
| [] -> raise Cannot_unify_universal_variables
in
inner t1 t2 pairs
let unify_univar_for tr_exn env t1 t2 jkind1 jkind2 univar_pairs =
try unify_univar env t1 t2 jkind1 jkind2 univar_pairs
with Cannot_unify_universal_variables -> raise_unexplained_for tr_exn
let occur_univar ?(inj_only=false) env ty =
let visited = ref TypeMap.empty in
with_type_mark begin fun mark ->
let rec occur_rec env bound ty =
if not_marked_node mark ty then
if TypeSet.is_empty bound then
(ignore (try_mark_node mark ty); occur_desc env bound ty)
else try
let bound' = TypeMap.find ty !visited in
if not (TypeSet.subset bound' bound) then begin
visited := TypeMap.add ty (TypeSet.inter bound bound') !visited;
occur_desc env bound ty
end
with Not_found ->
visited := TypeMap.add ty bound !visited;
occur_desc env bound ty
and occur_desc env bound ty =
match get_desc ty with
Tunivar _ ->
if not (TypeSet.mem ty bound) then
raise_escape_exn (Univ ty)
| Tpoly (ty, tyl) ->
let bound = List.fold_right TypeSet.add tyl bound in
occur_rec env bound ty
| Trepr (ty, _sort_vars) ->
occur_rec env bound ty
| Tconstr (_, [], _) -> ()
| Tconstr (p, tl, _) ->
begin try
let td = Env.find_type p env in
List.iter2
(fun t v ->
if Variance.(if inj_only then mem Inj v else not (eq v null))
then occur_rec env bound t)
tl td.type_variance
with Not_found ->
if not inj_only then List.iter (occur_rec env bound) tl
end
| _ -> iter_type_expr_with_stages (fun env -> occur_rec env bound) env ty
in
occur_rec env TypeSet.empty ty
end
let has_free_univars env ty =
try occur_univar ~inj_only:false env ty; false with Escape _ -> true
let has_injective_univars env ty =
try occur_univar ~inj_only:true env ty; false with Escape _ -> true
let occur_univar_for tr_exn env ty =
try
occur_univar env ty
with Escape e -> raise_for tr_exn (Escape e)
let add_univars =
List.fold_left (fun s (t,_) -> TypeSet.add t s)
let get_univar_family univar_pairs univars =
if univars = [] then TypeSet.empty else
let insert s = function
cl1, (_::_ as cl2) ->
if List.exists (fun (t1,_) -> TypeSet.mem t1 s) cl1 then
add_univars s cl2
else s
| _ -> s
in
let s = List.fold_right TypeSet.add univars TypeSet.empty in
List.fold_left insert s univar_pairs
let univars_escape env univar_pairs vl ty =
let family = get_univar_family univar_pairs vl in
with_type_mark begin fun mark ->
let rec occur env t =
if try_mark_node mark t then begin
match get_desc t with
Tpoly (t, tl) ->
if List.exists (fun t -> TypeSet.mem t family) tl then ()
else occur env t
| Tunivar _ -> if TypeSet.mem t family then raise_escape_exn (Univ t)
| Tconstr (_, [], _) -> ()
| Tconstr (p, tl, _) ->
begin try
let td = Env.find_type p env in
List.iter2
(fun t v -> if not Variance.(eq v null) then occur env t)
tl td.type_variance
with Not_found ->
List.iter (occur env) tl
end
| _ ->
iter_type_expr_with_stages occur env t
end
in
occur env ty
end
let enter_poly env univar_pairs t1 tl1 t2 tl2 f =
let old_univars = !univar_pairs in
let known_univars =
List.fold_left (fun s (cl,_) -> add_univars s cl)
TypeSet.empty old_univars
in
if List.exists (fun t -> TypeSet.mem t known_univars) tl1 then
univars_escape env old_univars tl1 (newty(Tpoly(t2,tl2)));
if List.exists (fun t -> TypeSet.mem t known_univars) tl2 then
univars_escape env old_univars tl2 (newty(Tpoly(t1,tl1)));
let cl1 = List.map (fun t -> t, ref None) tl1
and cl2 = List.map (fun t -> t, ref None) tl2 in
univar_pairs := (cl1,cl2) :: (cl2,cl1) :: old_univars;
Misc.try_finally (fun () -> f t1 t2)
~always:(fun () -> univar_pairs := old_univars)
let enter_poly_for tr_exn env univar_pairs t1 tl1 t2 tl2 f =
try
enter_poly env univar_pairs t1 tl1 t2 tl2 f
with Escape e -> raise_for tr_exn (Escape e)
let univar_pairs = ref []
let polyfy env ty vars =
let subst_univar copy_scope ty =
match get_desc ty with
| Tvar { name; jkind } when get_level ty = generic_level ->
let t = newty (Tunivar { name; jkind }) in
For_copy.redirect_desc copy_scope ty (Tsubst (t, None));
Some t
| _ -> None
in
let vars = List.map (expand_head env) vars in
let vars = List.map (expand_head env) vars in
For_copy.with_scope (fun copy_scope ->
let vars' = List.filter_map (subst_univar copy_scope) vars in
let ty = copy copy_scope ty in
let ty = newty2 ~level:(get_level ty) (Tpoly(ty, vars')) in
let complete = List.length vars = List.length vars' in
ty, complete
)
let reify_univars env ty =
let vars = free_variables ty in
let ty, _ = polyfy env ty vars in
ty
let rec has_cached_expansion p abbrev =
match abbrev with
Mnil -> false
| Mcons(_, p', _, _, rem) -> Path.same p p' || has_cached_expansion p rem
| Mlink rem -> has_cached_expansion p !rem
let expand_type env ty =
let env =
if contains_toplevel_splice (Env.stage env :> int) ty
then Env.enter_future env
else env
in
{ ty = ty;
expanded = full_expand ~may_forget_scope:true env ty }
let expand_any_trace map env trace =
map (expand_type env) trace
let expand_trace env trace =
expand_any_trace Errortrace.map env trace
let expand_subtype_trace env trace =
expand_any_trace Subtype.map env trace
let expand_to_unification_error env trace =
unification_error ~trace:(expand_trace env trace)
let expand_to_equality_error env trace subst =
equality_error ~trace:(expand_trace env trace) ~subst
let expand_to_moregen_error env trace =
moregen_error ~trace:(expand_trace env trace)
let expanded_diff env ~got ~expected =
Diff (map_diff (expand_type env) {got; expected})
let unexpanded_diff ~got ~expected =
Diff (map_diff trivial_expansion {got; expected})
let rec deep_occur_rec mark t0 ty =
if get_level ty >= get_level t0 && try_mark_node mark ty then begin
if eq_type ty t0 then raise Occur;
iter_type_expr (deep_occur_rec mark t0) ty
end
let deep_occur_list t0 tyl =
with_type_mark (fun mark ->
try
List.iter (deep_occur_rec mark t0) tyl;
false
with Occur ->
true)
let deep_occur t0 ty =
with_type_mark (fun mark ->
try
deep_occur_rec mark t0 ty;
false
with Occur ->
true)
let reify uenv t =
let fresh_constr_scope = get_equations_scope uenv in
let create_fresh_constr lev name jkind =
let name = match name with Some s -> "$'"^s | _ -> "$" in
let decl = new_local_type Definition jkind in
let env = get_env uenv in
let new_name =
if in_counterexample uenv then name else get_new_abstract_name env name
in
let (id, new_env) =
Env.enter_type new_name decl env ~scope:fresh_constr_scope in
let path = Path.Pident id in
let t = newty2 ~level:lev (Tconstr (path,[],ref Mnil)) in
set_env uenv new_env;
path, t
in
let visited = ref TypeSet.empty in
let rec iterator ty =
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match get_desc ty with
Tvar { name; jkind } ->
let level = get_level ty in
let path, t = create_fresh_constr level name jkind in
link_type ty t;
if level < fresh_constr_scope then
raise_for Unify (Escape (escape (Constructor path)))
| Tvariant r ->
if not (static_row r) then begin
if is_fixed r then iterator (row_more r) else
let m = row_more r in
match get_desc m with
Tvar { name; jkind } ->
let level = get_level m in
let path, t = create_fresh_constr level name jkind in
let row =
let fixed = Some (Reified path) in
create_row ~fields:[] ~more:t ~fixed
~name:(row_name r) ~closed:(row_closed r) in
link_type m (newty2 ~level (Tvariant row));
if level < fresh_constr_scope then
raise_for Unify (Escape (escape (Constructor path)))
| _ -> assert false
end;
iter_row iterator r
| _ ->
iter_type_expr iterator ty
end
in
iterator t
let find_expansion_scope env path =
match Env.find_type path env with
| { type_manifest = None ; _ } | exception Not_found -> generic_level
| decl -> decl.type_expansion_scope
let non_aliasable p decl =
in_current_module p && not decl.type_is_newtype
let is_instantiable env ~for_jkind_eqn p =
try
let decl = Env.find_type p env in
type_kind_is_abstract decl &&
decl.type_private = Public &&
decl.type_arity = 0 &&
decl.type_manifest = None &&
(for_jkind_eqn || not (non_aliasable p decl))
with Not_found -> false
let rec is_flexible_ty ty =
match get_desc ty with
| Tvar _ -> true
| Tquote ty' -> is_flexible_ty ty'
| Tsplice ty' -> is_flexible_ty ty'
| _ -> false
let is_aliasable p decl =
not (non_aliasable p decl) && not (is_datatype decl)
let rec is_aliasable_ty env ty =
match get_desc ty with
| Tconstr (p, _, _) -> Env.find_type p env |> is_aliasable p
| Tquote ty' -> is_aliasable_ty (incr_stage env) ty'
| Tsplice ty' -> is_aliasable_ty (decr_stage env) ty'
| _ -> false
let compatible_paths p1 p2 =
let open Predef in
Path.same p1 p2 ||
Path.same p1 path_bytes && Path.same p2 path_string ||
Path.same p1 path_string && Path.same p2 path_bytes
let rec expands_to_datatype env ty =
match get_desc ty with
Tconstr (p, _, _) ->
begin try
is_datatype (Env.find_type p env) ||
expands_to_datatype env (try_expand_safe env ty)
with Not_found | Cannot_expand -> false
end
| _ -> false
let equivalent_with_nolabels l1 l2 =
l1 = l2 || (match l1, l2 with
| (Nolabel | Labelled _), (Nolabel | Labelled _) -> true
| _ -> false)
let may_have_jkind_intersection_tk env ty jkind =
Jkind.may_have_intersection env (type_jkind env ty) jkind
let rec mcomp type_pairs env t1 t2 =
let check_jkinds ty jkind =
if not (may_have_jkind_intersection_tk env ty
(Jkind.disallow_right jkind))
then raise Incompatible
in
if eq_type t1 t2 then () else
match (get_desc t1, get_desc t2, t1, t2) with
| (Tvar { jkind }, _, _, other)
| (_, Tvar { jkind }, other, _) -> check_jkinds other jkind
| (Tconstr (p1, [], _), Tconstr (p2, [], _), _, _) when Path.same p1 p2 ->
()
| _ ->
let t1' = expand_head_opt env t1 in
let t2' = expand_head_opt env t2 in
if eq_type t1' t2' then () else
if not (TypePairs.mem type_pairs (t1', t2')) then begin
TypePairs.add type_pairs (t1', t2');
let flexible1 = is_flexible_ty t1' in
let flexible2 = is_flexible_ty t2' in
let aliasable1 = is_aliasable_ty env t1' in
let aliasable2 = is_aliasable_ty env t2' in
let neither_flexible = not flexible1 && not flexible2 in
let target1 = flexible1 || (neither_flexible && aliasable1) in
let target2 = not target1 && (flexible2 || aliasable2) in
match (get_desc t1', get_desc t2', t1', t2') with
| (Tquote s1, _, _, _) when target1 ->
mcomp type_pairs (incr_stage env) s1 (new_splice_ty t2')
| (Tsplice s1, _, _, _) when target1 ->
mcomp type_pairs (decr_stage env) s1 (new_quote_ty t2')
| (_, Tquote s2, _, _) when target2 ->
mcomp type_pairs (incr_stage env) (new_splice_ty t1') s2
| (_, Tsplice s2, _, _) when target2 ->
mcomp type_pairs (decr_stage env) (new_quote_ty t1') s2
| (Tvar { jkind }, _, _, other)
| (_, Tvar { jkind }, other, _) -> check_jkinds other jkind
| (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _), _, _) ->
mcomp_type_decl type_pairs env p1 p2 tl1 tl2
| (Tconstr (_, [], _), _, _, _) when has_injective_univars env t2' ->
raise_unexplained_for Unify
| (_, Tconstr (_, [], _), _, _) when has_injective_univars env t1' ->
raise_unexplained_for Unify
| (Tconstr (p, _, _), _, _, other) | (_, Tconstr (p, _, _), other, _) ->
begin try
let decl = Env.find_type p env in
if not (is_aliasable p decl &&
may_have_jkind_intersection_tk env
other decl.type_jkind)
then raise Incompatible
with Not_found -> ()
end
| (Tarrow ((l1,_,_), t1, u1, _), Tarrow ((l2,_,_), t2, u2, _), _, _)
when equivalent_with_nolabels l1 l2 ->
mcomp type_pairs env t1 t2;
mcomp type_pairs env u1 u2;
| (Ttuple tl1, Ttuple tl2, _, _) ->
mcomp_labeled_list type_pairs env tl1 tl2
| (Tpackage _, Tpackage _, _, _) -> ()
| (Tvariant row1, Tvariant row2, _, _) ->
mcomp_row type_pairs env row1 row2
| (Tobject (fi1, _), Tobject (fi2, _), _, _) ->
mcomp_fields type_pairs env fi1 fi2
| (Tfield _, Tfield _, _, _) ->
mcomp_fields type_pairs env t1' t2'
| (Tquote t1, Tquote t2, _, _) ->
mcomp type_pairs (incr_stage env) t1 t2
| (Tsplice t1, Tsplice t2, _, _) ->
mcomp type_pairs (decr_stage env) t1 t2
| (Tquote_eval t1, Tquote_eval t2, _, _) ->
mcomp type_pairs (incr_stage env) t1 t2
| (Tnil, Tnil, _, _) ->
()
| (Tpoly (t1, []), Tpoly (t2, []), _, _) ->
mcomp type_pairs env t1 t2
| (Tpoly (t1, tl1), Tpoly (t2, tl2), _, _) ->
(try
enter_poly env univar_pairs
t1 tl1 t2 tl2 (mcomp type_pairs env)
with Escape _ -> raise Incompatible)
| (Trepr (t1, sort_vars1), Trepr (t2, sort_vars2), _, _) ->
(try
let pairs = List.combine sort_vars1 sort_vars2 in
Jkind_types.Sort.enter_repr pairs
(fun () -> mcomp type_pairs env t1 t2)
with Invalid_argument _ -> raise Incompatible)
| (Tunivar {jkind=jkind1}, Tunivar {jkind=jkind2}, _, _) ->
(try unify_univar env t1' t2' jkind1 jkind2 !univar_pairs
with Cannot_unify_universal_variables -> raise Incompatible)
| (_, _, _, _) ->
raise Incompatible
end
and mcomp_list type_pairs env tl1 tl2 =
if List.length tl1 <> List.length tl2 then
raise Incompatible;
List.iter2 (mcomp type_pairs env) tl1 tl2
and mcomp_labeled_list type_pairs env labeled_tl1 labeled_tl2 =
if not (Int.equal (List.length labeled_tl1) (List.length labeled_tl2)) then
raise Incompatible;
List.iter2
(fun (label1, ty1) (label2, ty2) ->
if not (Option.equal String.equal label1 label2) then
raise Incompatible;
mcomp type_pairs env ty1 ty2)
labeled_tl1 labeled_tl2
and mcomp_fields type_pairs env ty1 ty2 =
if not (concrete_object ty1 && concrete_object ty2) then assert false;
let (fields2, rest2) = flatten_fields ty2 in
let (fields1, rest1) = flatten_fields ty1 in
let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
let has_present =
List.exists (fun (_, k, _) -> field_kind_repr k = Fpublic) in
mcomp type_pairs env rest1 rest2;
if has_present miss1 && get_desc (object_row ty2) = Tnil
|| has_present miss2 && get_desc (object_row ty1) = Tnil
then raise Incompatible;
List.iter
(function (_n, k1, t1, k2, t2) ->
mcomp_kind k1 k2;
mcomp type_pairs env t1 t2)
pairs
and mcomp_kind k1 k2 =
let k1 = field_kind_repr k1 in
let k2 = field_kind_repr k2 in
match k1, k2 with
(Fpublic, Fabsent)
| (Fabsent, Fpublic) -> raise Incompatible
| _ -> ()
and mcomp_row type_pairs env row1 row2 =
let r1, r2, pairs = merge_row_fields (row_fields row1) (row_fields row2) in
let cannot_erase (_,f) =
match row_field_repr f with
Rpresent _ -> true
| Rabsent | Reither _ -> false
in
if row_closed row1 && List.exists cannot_erase r2
|| row_closed row2 && List.exists cannot_erase r1 then raise Incompatible;
List.iter
(fun (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
| Rpresent None, (Rpresent (Some _) | Reither (_, _::_, _) | Rabsent)
| Rpresent (Some _), (Rpresent None | Reither (true, _, _) | Rabsent)
| (Reither (_, _::_, _) | Rabsent), Rpresent None
| (Reither (true, _, _) | Rabsent), Rpresent (Some _) ->
raise Incompatible
| Rpresent(Some t1), Rpresent(Some t2) ->
mcomp type_pairs env t1 t2
| Rpresent(Some t1), Reither(false, tl2, _) ->
List.iter (mcomp type_pairs env t1) tl2
| Reither(false, tl1, _), Rpresent(Some t2) ->
List.iter (mcomp type_pairs env t2) tl1
| _ -> ())
pairs
and mcomp_unsafe_mode_crossing type_pairs env umc1 umc2 =
match umc1, umc2 with
| None, None -> ()
| Some _, None -> raise Incompatible
| None, Some _ -> raise Incompatible
| Some umc1, Some umc2 ->
if
equal_unsafe_mode_crossing
~type_equal:(fun ty1 ty2 ->
match mcomp type_pairs env ty1 ty2 with
| () -> true
| exception Incompatible -> false)
umc1 umc2
then ()
else raise Incompatible
and mcomp_type_decl type_pairs env p1 p2 tl1 tl2 =
try
let decl = Env.find_type p1 env in
let decl' = Env.find_type p2 env in
let check_jkinds () =
if not (Jkind.may_have_intersection env
decl.type_jkind decl'.type_jkind)
then raise Incompatible
in
if compatible_paths p1 p2 then begin
let inj =
try List.map Variance.(mem Inj) (Env.find_type p1 env).type_variance
with Not_found -> List.map (fun _ -> false) tl1
in
List.iter2
(fun i (t1,t2) -> if i then mcomp type_pairs env t1 t2)
inj (List.combine tl1 tl2)
end else if non_aliasable p1 decl && non_aliasable p2 decl' then
raise Incompatible
else
match decl.type_kind, decl'.type_kind with
| Type_record (lst,r,umc), Type_record (lst',r',umc')
when equal_record_representation_up_to_scannable_axes r r' ->
mcomp_list type_pairs env tl1 tl2;
mcomp_record_description type_pairs env lst lst';
mcomp_unsafe_mode_crossing type_pairs env umc umc'
| Type_record_unboxed_product (lst,r,umc),
Type_record_unboxed_product (lst',r',umc')
when
equal_record_unboxed_product_representation_up_to_scannable_axes r r'
->
mcomp_list type_pairs env tl1 tl2;
mcomp_record_description type_pairs env lst lst';
mcomp_unsafe_mode_crossing type_pairs env umc umc'
| Type_variant (v1,r,umc), Type_variant (v2,r',umc')
when equal_variant_representation_up_to_scannable_axes r r' ->
mcomp_list type_pairs env tl1 tl2;
mcomp_variant_description type_pairs env v1 v2;
mcomp_unsafe_mode_crossing type_pairs env umc umc'
| Type_open, Type_open ->
mcomp_list type_pairs env tl1 tl2
| Type_abstract _, Type_abstract _ -> check_jkinds ()
| Type_abstract _, _ when not (non_aliasable p1 decl)-> check_jkinds ()
| _, Type_abstract _ when not (non_aliasable p2 decl') -> check_jkinds ()
| _ -> raise Incompatible
with Not_found -> ()
and mcomp_type_option type_pairs env t t' =
match t, t' with
None, None -> ()
| Some t, Some t' -> mcomp type_pairs env t t'
| _ -> raise Incompatible
and mcomp_variant_description type_pairs env xs ys =
let rec iter = fun x y ->
match x, y with
| c1 :: xs, c2 :: ys ->
mcomp_type_option type_pairs env c1.cd_res c2.cd_res;
begin match c1.cd_args, c2.cd_args with
| Cstr_tuple l1, Cstr_tuple l2 -> mcomp_tuple_description type_pairs env l1 l2
| Cstr_record l1, Cstr_record l2 ->
mcomp_record_description type_pairs env l1 l2
| _ -> raise Incompatible
end;
if Ident.name c1.cd_id = Ident.name c2.cd_id
then iter xs ys
else raise Incompatible
| [],[] -> ()
| _ -> raise Incompatible
in
iter xs ys
and mcomp_tuple_description type_pairs env =
let rec iter x y =
match x, y with
| {ca_type=ty1; ca_modalities=gf1; _} :: xs, {ca_type=ty2; ca_modalities=gf2} :: ys ->
mcomp type_pairs env ty1 ty2;
if gf1 = gf2
then iter xs ys
else raise Incompatible
| [], [] -> ()
| _ -> raise Incompatible
in
iter
and mcomp_record_description type_pairs env =
let rec iter x y =
match x, y with
| l1 :: xs, l2 :: ys ->
mcomp type_pairs env l1.ld_type l2.ld_type;
if Ident.name l1.ld_id = Ident.name l2.ld_id &&
l1.ld_mutable = l2.ld_mutable &&
l1.ld_modalities = l2.ld_modalities
then iter xs ys
else raise Incompatible
| [], [] -> ()
| _ -> raise Incompatible
in
iter
let mcomp env t1 t2 =
mcomp (TypePairs.create 4) env t1 t2
let mcomp_for tr_exn env t1 t2 =
try
mcomp env t1 t2
with Incompatible -> raise_unexplained_for tr_exn
let find_lowest_level ty =
let lowest = ref generic_level in
with_type_mark begin fun mark ->
let rec find ty =
if try_mark_node mark ty then begin
let level = get_level ty in
if level < !lowest then lowest := level;
iter_type_expr find ty
end
in find ty
end;
!lowest
let jkind_of_abstract_type_declaration env p =
try
let typ = Env.find_type p env in
typ.type_jkind
with
Not_found -> assert false
let add_jkind_equation ~reason uenv destination jkind1 =
let env = get_env uenv in
match
intersect_type_jkind ~reason env destination jkind1
with
| Jkind.No_intersection err -> raise_for Unify (Bad_jkind (destination,err))
| Jkind.Unknown -> ()
| Jkind.Intersection jkind -> begin
match get_desc destination with
| Tconstr (p, _, _)
when is_instantiable ~for_jkind_eqn:true env p ->
begin
try
let decl = Env.find_type p env in
match Jkind.try_allow_r jkind, Jkind.try_allow_r decl.type_jkind with
| Some jkind, Some decl_jkind
when not (Jkind.equal env jkind decl_jkind) ->
let refined_decl =
{ decl with type_jkind = Jkind.disallow_right jkind }
in
set_env uenv
(Env.add_local_constraint ~stage:(Env.stage env) p
refined_decl env)
| _ -> ()
with
Not_found -> ()
end
| _ -> ()
end
let add_gadt_equation uenv source destination =
let env = get_env uenv in
if has_free_univars env destination then
occur_univar ~inj_only:true env destination
else if local_non_recursive_abbrev uenv source destination then begin
let destination = duplicate_type destination in
let expansion_scope =
Int.max (Path.scope source) (get_equations_scope uenv)
in
let type_origin =
match Env.find_type source env with
| decl -> type_origin decl
| exception Not_found -> assert false
in
let jkind = jkind_of_abstract_type_declaration env source in
let jkind = match Jkind.try_allow_r jkind with
| None -> Misc.fatal_errorf "Abstract kind with [with]: %a"
(Format_doc.compat (Jkind.format env))
jkind
| Some jkind -> jkind
in
add_jkind_equation ~reason:(Gadt_equation source)
uenv destination jkind;
let env = get_env uenv in
let decl =
new_local_type
~manifest_and_scope:(destination, expansion_scope)
type_origin
jkind
in
set_env uenv
(Env.add_local_constraint ~stage:(Env.stage env) source decl env);
cleanup_abbrev ()
end
let eq_package_path env p1 p2 =
Path.same p1 p2 ||
Path.same (normalize_package_path env p1) (normalize_package_path env p2)
let nondep_type' = ref (fun _ _ _ -> assert false)
let package_subtype = ref (fun _ _ _ _ _ -> assert false)
exception Nondep_cannot_erase of Ident.t
let rec concat_longident lid1 =
let open Longident in
function
Lident s -> Ldot (lid1, s)
| Ldot (lid2, s) -> Ldot (concat_longident lid1 lid2, s)
| Lapply (lid2, lid) -> Lapply (concat_longident lid1 lid2, lid)
let nondep_instance env level id ty =
let ty = !nondep_type' env [id] ty in
if level = generic_level then duplicate_type ty else
let old = !current_level in
current_level := level;
let ty = instance ty in
current_level := old;
ty
let complete_type_list ?(allow_absent=false) env fl1 lv2 mty2 fl2 =
let id2 = Ident.create_local "Pkg" in
let env' = Env.add_module id2 Mp_present mty2 env in
let rec complete fl1 fl2 =
match fl1, fl2 with
[], _ -> fl2
| (n, _) :: nl, (n2, _ as nt2) :: ntl' when n >= n2 ->
nt2 :: complete (if n = n2 then nl else fl1) ntl'
| (n, _) :: nl, _ ->
let lid = concat_longident (Longident.Lident "Pkg") n in
match Env.find_type_by_name lid env' with
| (_, {type_arity = 0; type_kind = Type_abstract _;
type_private = Public; type_manifest = Some t2}) ->
begin match nondep_instance env' lv2 id2 t2 with
| t -> (n, t) :: complete nl fl2
| exception Nondep_cannot_erase _ ->
if allow_absent then
complete nl fl2
else
raise Exit
end
| (_, {type_arity = 0; type_kind = Type_abstract _;
type_private = Public; type_manifest = None})
when allow_absent ->
complete nl fl2
| _ -> raise Exit
| exception Not_found when allow_absent->
complete nl fl2
in
match complete fl1 fl2 with
| res -> res
| exception Exit -> raise Not_found
let rec is_instantiable_ty uenv ty =
match get_desc ty with
| Tconstr (path, [], _) ->
can_generate_equations uenv &&
is_instantiable (get_env uenv) ~for_jkind_eqn:false path
| Tquote ty' ->
unify_with_incr_stage uenv (fun uenv ->
is_instantiable_ty uenv ty')
| Tsplice ty' ->
unify_with_decr_stage uenv (fun uenv ->
is_instantiable_ty uenv ty')
| _ -> false
let rec is_equatable_ty ty =
match get_desc ty with
| Tconstr (_, _, _) -> true
| Tquote ty' -> is_equatable_ty ty'
| Tsplice ty' -> is_equatable_ty ty'
| _ -> false
let rec instantiable_scope ty =
match get_desc ty with
| Tconstr (path, [], _) -> Path.scope path
| Tquote ty' -> instantiable_scope ty'
| Tsplice ty' -> instantiable_scope ty'
| _ -> -1
let unify_package env unify_list lv1 p1 fl1 lv2 p2 fl2 =
let ntl2 = complete_type_list env fl1 lv2 (Mty_ident p2) fl2
and ntl1 = complete_type_list env fl2 lv1 (Mty_ident p1) fl1 in
unify_list (List.map snd ntl1) (List.map snd ntl2);
if eq_package_path env p1 p2
|| !package_subtype env p1 fl1 p2 fl2
&& !package_subtype env p2 fl2 p1 fl1 then () else raise Not_found
let unify_alloc_mode_for tr_exn a b =
match Alloc.equate a b with
| Ok () -> ()
| Error _ -> raise_unexplained_for tr_exn
let rigid_variants = ref false
let unify1_var uenv t1 t2 =
let jkind = match get_desc t1 with
| Tvar { jkind } -> jkind
| _ -> assert false
in
occur_for Unify uenv t1 t2;
let env = get_env uenv in
match
occur_univar_for Unify env t2;
unification_jkind_check uenv t2 (Jkind.disallow_left jkind)
with
| () ->
begin
try
update_level env (get_level t1) t2;
update_scope (get_scope t1) t2;
with Escape e ->
raise_for Unify (Escape e)
end;
link_type t1 t2;
true
| exception Unify_trace _ when in_pattern_mode uenv ->
false
let unify3_var uenv jkind1 t1' t2 t2' =
occur_for Unify uenv t1' t2;
let snap = snapshot () in
match
occur_univar_for Unify (get_env uenv) t2;
unification_jkind_check uenv t2' (Jkind.disallow_left jkind1)
with
| () -> link_type t1' t2
| exception Unify_trace _ when in_pattern_mode uenv ->
backtrack snap;
reify uenv t1';
reify uenv t2';
if can_generate_equations uenv then begin
begin match get_desc t2' with
| Tconstr(path,[],_)
when is_instantiable (get_env uenv) ~for_jkind_eqn:false path ->
add_gadt_equation uenv path t1'
| _ ->
occur_univar ~inj_only:true (get_env uenv) t2';
mcomp_for Unify (get_env uenv) t1' t2'
end;
record_equation uenv t1' t2';
end
let rec unify uenv t1 t2 =
if unify_eq uenv t1 t2 then () else
let reset_tracing = check_trace_gadt_instances (get_env uenv) in
try
type_changed := true;
begin match (get_desc t1, get_desc t2) with
(Tconstr _, Tvar _) when deep_occur t2 t1 ->
unify2 uenv t1 t2
| (Tvar _, Tconstr _) when deep_occur t1 t2 ->
unify2 uenv t1 t2
| (Tquote _, Tvar _) when deep_occur t2 t1 ->
unify2 uenv t1 t2
| (Tvar _, Tquote _) when deep_occur t1 t2 ->
unify2 uenv t1 t2
| (Tsplice _, Tvar _) when deep_occur t2 t1 ->
unify2 uenv t1 t2
| (Tvar _, Tsplice _) when deep_occur t1 t2 ->
unify2 uenv t1 t2
| (Tvar _, _) ->
if unify1_var uenv t1 t2 then () else unify2 uenv t1 t2
| (_, Tvar _) ->
if unify1_var uenv t2 t1 then () else unify2 uenv t1 t2
| (Tunivar { jkind = k1 }, Tunivar { jkind = k2 }) ->
unify_univar_for Unify (get_env uenv) t1 t2 k1 k2 !univar_pairs;
update_level_for Unify (get_env uenv) (get_level t1) t2;
update_scope_for Unify (get_scope t1) t2;
link_type t1 t2
| (Tconstr (p1, [], a1), Tconstr (p2, [], a2))
when Path.same p1 p2
&& not (has_cached_expansion p1 !a1
|| has_cached_expansion p2 !a2) ->
update_level_for Unify (get_env uenv) (get_level t1) t2;
update_scope_for Unify (get_scope t1) t2;
link_type t1 t2
| (Tconstr _, Tconstr _) when Env.has_local_constraints (get_env uenv) ->
unify2_rec uenv t1 t1 t2 t2
| _ ->
unify2 uenv t1 t2
end;
reset_trace_gadt_instances reset_tracing;
with Unify_trace trace ->
reset_trace_gadt_instances reset_tracing;
raise_trace_for Unify (Diff {got = t1; expected = t2} :: trace)
and unify2 uenv t1 t2 = unify2_expand uenv t1 t1 t2 t2
and unify2_rec uenv t10 t1 t20 t2 =
if unify_eq uenv t1 t2 then () else
try match (get_desc t1, get_desc t2) with
| (Tconstr (p1, tl1, a1), Tconstr (p2, tl2, a2)) ->
if Path.same p1 p2 && tl1 = [] && tl2 = []
&& not (has_cached_expansion p1 !a1 || has_cached_expansion p2 !a2)
then begin
update_level_for Unify (get_env uenv) (get_level t1) t2;
update_scope_for Unify (get_scope t1) t2;
link_type t1 t2
end else
let env = get_env uenv in
if find_expansion_scope env p1 > find_expansion_scope env p2
then unify2_rec uenv t10 t1 t20 (try_expand_safe env t2)
else unify2_rec uenv t10 (try_expand_safe env t1) t20 t2
| _ ->
raise Cannot_expand
with Cannot_expand ->
unify2_expand uenv t10 t1 t20 t2
and unify2_expand uenv t1 t1' t2 t2' =
let env = get_env uenv in
ignore (expand_head_unif env t1');
ignore (expand_head_unif env t2');
let t1' = expand_head_unif env t1' in
let t2' = expand_head_unif env t2' in
let lv = Int.min (get_level t1') (get_level t2') in
let scope = Int.max (get_scope t1') (get_scope t2') in
update_level_for Unify env lv t2;
update_level_for Unify env lv t1;
update_scope_for Unify scope t2;
update_scope_for Unify scope t1;
if unify_eq uenv t1' t2' then () else
let t1, t2 =
if !Clflags.principal
&& (find_lowest_level t1' < lv || find_lowest_level t2' < lv) then
(match get_desc t1 with Tconstr (_, [], _) -> t1' | _ -> t1),
(match get_desc t2 with Tconstr (_, [], _) -> t2' | _ -> t2)
else (t1, t2)
in
if unify_eq uenv t1 t1' || not (unify_eq uenv t2 t2') then
unify3 uenv t1 t1' t2 t2'
else
try unify3 uenv t2 t2' t1 t1' with Unify_trace trace ->
raise_trace_for Unify (swap_trace trace)
and unify3 uenv t1 t1' t2 t2' =
let tt1' = Transient_expr.repr t1' in
let d1 = tt1'.desc and d2 = get_desc t2' in
let create_recursion =
(not (eq_type t2 t2')) && (deep_occur t1' t2) in
begin match (d1, d2) with
(Tunivar { jkind = k1 }, Tunivar { jkind = k2 }) ->
unify_univar_for Unify (get_env uenv) t1' t2' k1 k2 !univar_pairs;
link_type t1' t2'
| (Tvar { jkind }, _) ->
unify3_var uenv jkind t1' t2 t2'
| (_, Tvar { jkind }) ->
unify3_var uenv jkind t2' t1 t1'
| (Tquote t1, Tquote t2) ->
unify_with_incr_stage uenv (fun uenv -> unify uenv t1 t2)
| (Tsplice t1, Tsplice t2) ->
unify_with_decr_stage uenv (fun uenv -> unify uenv t1 t2)
| (Tquote_eval t1, Tquote_eval t2) ->
unify_with_incr_stage uenv (fun uenv -> unify uenv t1 t2)
| (Tsplice s1, _) when is_flexible_ty s1 ->
unify_with_decr_stage uenv (fun uenv -> unify uenv s1 (new_quote_ty t2'))
| (Tquote s1, _) when is_flexible_ty s1 ->
unify_with_incr_stage uenv (fun uenv -> unify uenv s1 (new_splice_ty t2'))
| (_, Tsplice s2) when is_flexible_ty s2 ->
unify_with_decr_stage uenv (fun uenv -> unify uenv (new_quote_ty t1') s2)
| (_, Tquote s2) when is_flexible_ty s2 ->
unify_with_incr_stage uenv (fun uenv -> unify uenv (new_splice_ty t1') s2)
| (Tfield _, Tfield _) ->
unify_fields uenv t1' t2'
| _ ->
if in_pattern_mode uenv then
add_type_equality uenv t1' t2'
else begin
occur_for Unify uenv t1' t2;
link_type t1' t2
end;
try
begin match (d1, d2) with
(Tarrow ((l1,a1,r1), t1, u1, c1),
Tarrow ((l2,a2,r2), t2, u2, c2))
when
(l1 = l2 ||
(!Clflags.classic || in_pattern_mode uenv) &&
equivalent_with_nolabels l1 l2) ->
unify_alloc_mode_for Unify a1 a2;
unify_alloc_mode_for Unify r1 r2;
unify uenv t1 t2; unify uenv u1 u2;
begin match is_commu_ok c1, is_commu_ok c2 with
| false, true -> set_commu_ok c1
| true, false -> set_commu_ok c2
| false, false -> link_commu ~inside:c1 c2
| true, true -> ()
end
| (Ttuple labeled_tl1, Ttuple labeled_tl2) ->
unify_labeled_list uenv labeled_tl1 labeled_tl2
| (Tunboxed_tuple labeled_tl1, Tunboxed_tuple labeled_tl2) ->
unify_labeled_list uenv labeled_tl1 labeled_tl2
| (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _)) when Path.same p1 p2 ->
if not (can_generate_equations uenv) then
unify_list uenv tl1 tl2
else if can_assume_injective uenv then
without_assume_injective uenv (fun uenv -> unify_list uenv tl1 tl2)
else if in_current_module p1
|| List.exists (expands_to_datatype (get_env uenv)) [t1'; t1; t2]
then
unify_list uenv tl1 tl2
else
let inj =
try List.map Variance.(mem Inj)
(Env.find_type p1 (get_env uenv)).type_variance
with Not_found -> List.map (fun _ -> false) tl1
in
List.iter2
(fun i (t1, t2) ->
if i then unify uenv t1 t2 else
without_generating_equations uenv
begin fun uenv ->
let snap = snapshot () in
try unify uenv t1 t2 with Unify_trace _ ->
backtrack snap;
reify uenv t1;
reify uenv t2
end)
inj (List.combine tl1 tl2)
| (Tconstr (path,[],_),
Tconstr (path',[],_))
when let env = get_env uenv in
is_instantiable env ~for_jkind_eqn:false path
&& is_instantiable env ~for_jkind_eqn:false path'
&& can_generate_equations uenv ->
let source, destination =
if Path.scope path > Path.scope path'
then path , t2'
else path', t1'
in
record_equation uenv t1' t2';
add_gadt_equation uenv source destination
| (Tconstr (path,[],_), _)
when is_instantiable (get_env uenv) ~for_jkind_eqn:false path
&& can_generate_equations uenv ->
reify uenv t2';
record_equation uenv t1' t2';
add_gadt_equation uenv path t2'
| (_, Tconstr (path,[],_))
when is_instantiable (get_env uenv) ~for_jkind_eqn:false path
&& can_generate_equations uenv ->
reify uenv t1';
record_equation uenv t1' t2';
add_gadt_equation uenv path t1'
| (Tsplice s1, _)
when is_instantiable_ty uenv t1'
&& (not (is_instantiable_ty uenv t2')
|| instantiable_scope s1 > instantiable_scope t2') ->
unify_with_decr_stage uenv
(fun uenv -> unify uenv s1 (new_quote_ty t2'))
| (Tquote s1, _)
when is_instantiable_ty uenv t1'
&& (not (is_instantiable_ty uenv t2')
|| instantiable_scope s1 > instantiable_scope t2') ->
unify_with_incr_stage uenv
(fun uenv -> unify uenv s1 (new_splice_ty t2'))
| (_, Tsplice s2)
when is_instantiable_ty uenv t2'
&& (not (is_instantiable_ty uenv t1')
|| instantiable_scope s2 >= instantiable_scope t1') ->
unify_with_decr_stage uenv
(fun uenv -> unify uenv (new_quote_ty t1') s2)
| (_, Tquote s2)
when is_instantiable_ty uenv t2'
&& (not (is_instantiable_ty uenv t1')
|| instantiable_scope s2 >= instantiable_scope t1') ->
unify_with_incr_stage uenv
(fun uenv -> unify uenv (new_splice_ty t1') s2)
| (Tconstr (_,_,_), _) | (_, Tconstr (_,_,_))
| (Tquote _, _) | (Tsplice _, _)
| (_, Tquote _) | (_, Tsplice _)
when in_pattern_mode uenv
&& (is_equatable_ty t1 || is_equatable_ty t2) ->
reify uenv t1';
reify uenv t2';
if can_generate_equations uenv then (
mcomp_for Unify (get_env uenv) t1' t2';
record_equation uenv t1' t2'
)
| (Tobject (fi1, nm1), Tobject (fi2, _)) ->
unify_fields uenv fi1 fi2;
begin match get_desc t2' with
Tobject (_, {contents = Some (_, va::_)}) when
(match get_desc va with
Tvar _|Tunivar _|Tnil -> true | _ -> false) -> ()
| Tobject (_, nm2) -> set_name nm2 !nm1
| _ -> ()
end
| (Tvariant row1, Tvariant row2) ->
if not (in_pattern_mode uenv) then
unify_row uenv row1 row2
else begin
let snap = snapshot () in
try unify_row uenv row1 row2
with Unify_trace _ ->
backtrack snap;
reify uenv t1';
reify uenv t2';
if can_generate_equations uenv then (
mcomp_for Unify (get_env uenv) t1' t2';
record_equation uenv t1' t2'
)
end
| (Tfield(f,kind,_,rem), Tnil) | (Tnil, Tfield(f,kind,_,rem)) ->
begin match field_kind_repr kind with
Fprivate when f <> dummy_method ->
link_kind ~inside:kind field_absent;
if d2 = Tnil then unify uenv rem t2'
else unify uenv (newgenty Tnil) rem
| _ ->
if f = dummy_method then
raise_for Unify (Obj Self_cannot_be_closed)
else if d1 = Tnil then
raise_for Unify (Obj (Missing_field(First, f)))
else
raise_for Unify (Obj (Missing_field(Second, f)))
end
| (Tnil, Tnil) ->
()
| (Tpoly (t1, []), Tpoly (t2, [])) ->
unify uenv t1 t2
| (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
enter_poly_for Unify (get_env uenv) univar_pairs t1 tl1 t2 tl2
(unify uenv)
| (Trepr (t1, sort_vars1), Trepr (t2, sort_vars2)) ->
(try
let pairs = List.combine sort_vars1 sort_vars2 in
Jkind_types.Sort.enter_repr pairs
(fun () -> unify uenv t1 t2)
with Invalid_argument _ -> raise_unexplained_for Unify)
| (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
begin try
unify_package (get_env uenv) (unify_list uenv)
(get_level t1) p1 fl1 (get_level t2) p2 fl2
with Not_found ->
if not (in_pattern_mode uenv) then raise_unexplained_for Unify;
List.iter (fun (_n, ty) -> reify uenv ty) (fl1 @ fl2);
end
| (Tnil, Tconstr _ ) ->
raise_for Unify (Obj (Abstract_row Second))
| (Tconstr _, Tnil ) ->
raise_for Unify (Obj (Abstract_row First))
| (_, _) -> raise_unexplained_for Unify
end;
if create_recursion then
match get_desc t2 with
Tconstr (p, tl, abbrev) ->
forget_abbrev abbrev p;
let t2'' = expand_head_unif (get_env uenv) t2 in
if not (closed_parameterized_type tl t2'') then
link_type t2 t2'
| _ ->
()
with Unify_trace trace ->
Transient_expr.set_desc tt1' d1;
raise_trace_for Unify trace
end
and unify_list env tl1 tl2 =
if List.length tl1 <> List.length tl2 then
raise_unexplained_for Unify;
List.iter2 (unify env) tl1 tl2
and unify_labeled_list env labeled_tl1 labeled_tl2 =
if not (Int.equal (List.length labeled_tl1) (List.length labeled_tl2)) then
raise_unexplained_for Unify;
List.iter2
(fun (label1, ty1) (label2, ty2) ->
if not (Option.equal String.equal label1 label2) then
raise_unexplained_for Unify;
unify env ty1 ty2)
labeled_tl1 labeled_tl2
and make_rowvar level use1 rest1 use2 rest2 =
let set_name ty name =
match get_desc ty with
Tvar { name = None; jkind } -> set_type_desc ty (Tvar { name; jkind })
| _ -> ()
in
let name =
match get_desc rest1, get_desc rest2 with
Tvar { name = Some _ as name1 }, Tvar { name = Some _ as name2 } ->
if get_level rest1 <= get_level rest2 then name1 else name2
| Tvar { name = Some _ as name }, _ ->
if use2 then set_name rest2 name; name
| _, Tvar { name = Some _ as name } ->
if use1 then set_name rest2 name; name
| _ -> None
in
if use1 then rest1 else
if use2 then rest2
else newty2 ~level (Tvar { name; jkind = Jkind.Builtin.value ~why:Row_variable })
and unify_fields uenv ty1 ty2 =
let (fields1, rest1) = flatten_fields ty1
and (fields2, rest2) = flatten_fields ty2 in
let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
let l1 = get_level ty1 and l2 = get_level ty2 in
let va = make_rowvar (Int.min l1 l2) (miss2=[]) rest1 (miss1=[]) rest2 in
let tr1 = Transient_expr.repr rest1 and tr2 = Transient_expr.repr rest2 in
let d1 = tr1.desc and d2 = tr2.desc in
try
unify uenv (build_fields l1 miss1 va) rest2;
unify uenv rest1 (build_fields l2 miss2 va);
List.iter
(fun (name, k1, t1, k2, t2) ->
unify_kind k1 k2;
try
if !trace_gadt_instances && not (in_subst_mode uenv) then begin
update_level_for Unify (get_env uenv) (get_level va) t1;
update_scope_for Unify (get_scope va) t1
end;
unify uenv t1 t2
with Unify_trace trace ->
raise_trace_for Unify
(incompatible_fields ~name ~got:t1 ~expected:t2 :: trace)
)
pairs
with exn ->
Transient_expr.set_desc tr1 d1;
Transient_expr.set_desc tr2 d2;
raise exn
and unify_kind k1 k2 =
match field_kind_repr k1, field_kind_repr k2 with
(Fprivate, (Fprivate | Fpublic)) -> link_kind ~inside:k1 k2
| (Fpublic, Fprivate) -> link_kind ~inside:k2 k1
| (Fpublic, Fpublic) -> ()
| _ -> assert false
and unify_row uenv row1 row2 =
let Row {fields = row1_fields; more = rm1;
closed = row1_closed; name = row1_name} = row_repr row1 in
let Row {fields = row2_fields; more = rm2;
closed = row2_closed; name = row2_name} = row_repr row2 in
if unify_eq uenv rm1 rm2 then () else
let r1, r2, pairs = merge_row_fields row1_fields row2_fields in
if r1 <> [] && r2 <> [] then begin
let ht = Hashtbl.create (List.length r1) in
List.iter (fun (l,_) -> Hashtbl.add ht (hash_variant l) l) r1;
List.iter
(fun (l,_) ->
try raise (Tags(l, Hashtbl.find ht (hash_variant l)))
with Not_found -> ())
r2
end;
let fixed1 = fixed_explanation row1 and fixed2 = fixed_explanation row2 in
let more = match fixed1, fixed2 with
| Some _, Some _ -> if get_level rm2 < get_level rm1 then rm2 else rm1
| Some _, None -> rm1
| None, Some _ -> rm2
| None, None ->
newty2 ~level:(Int.min (get_level rm1) (get_level rm2))
(Tvar { name = None; jkind = Jkind.Builtin.value ~why:Row_variable })
in
let fixed = merge_fixed_explanation fixed1 fixed2
and closed = row1_closed || row2_closed in
let keep switch =
List.for_all
(fun (_,f1,f2) ->
let f1, f2 = switch f1 f2 in
row_field_repr f1 = Rabsent || row_field_repr f2 <> Rabsent)
pairs
in
let empty fields =
List.for_all (fun (_,f) -> row_field_repr f = Rabsent) fields in
if closed && (empty r1 || row2_closed) && (empty r2 || row1_closed)
&& List.for_all
(fun (_,f1,f2) ->
row_field_repr f1 = Rabsent || row_field_repr f2 = Rabsent)
pairs
then raise_for Unify (Variant No_intersection);
let name =
if row1_name <> None && (row1_closed || empty r2) &&
(not row2_closed || keep (fun f1 f2 -> f1, f2) && empty r1)
then row1_name
else if row2_name <> None && (row2_closed || empty r1) &&
(not row1_closed || keep (fun f1 f2 -> f2, f1) && empty r2)
then row2_name
else None
in
let set_more pos row rest =
let rest =
if closed then
filter_row_fields (row_closed row) rest
else rest in
begin match fixed_explanation row with
| None ->
if rest <> [] && row_closed row then
raise_for Unify (Variant (No_tags(pos,rest)))
| Some fixed ->
if closed && not (row_closed row) then
raise_for Unify (Variant (Fixed_row(pos,Cannot_be_closed,fixed)))
else if rest <> [] then
let case = Cannot_add_tags (List.map fst rest) in
raise_for Unify (Variant (Fixed_row(pos,case,fixed)))
end;
let rm = row_more row in
if !trace_gadt_instances && not (in_subst_mode uenv) then
update_level_for Unify (get_env uenv) (get_level rm)
(newgenty (Tvariant row));
if has_fixed_explanation row then
if eq_type more rm then () else
if is_Tvar rm then link_type rm more else unify uenv rm more
else
let ty =
newgenty (Tvariant
(create_row ~fields:rest ~more ~closed ~fixed ~name))
in
update_level_for Unify (get_env uenv) (get_level rm) ty;
update_scope_for Unify (get_scope rm) ty;
link_type rm ty
in
let tm1 = Transient_expr.repr rm1 and tm2 = Transient_expr.repr rm2 in
let md1 = tm1.desc and md2 = tm2.desc in
begin try
set_more Second row2 r1;
set_more First row1 r2;
List.iter
(fun (l,f1,f2) ->
try unify_row_field uenv fixed1 fixed2 rm1 rm2 l f1 f2
with Unify_trace trace ->
raise_trace_for Unify (Variant (Incompatible_types_for l) :: trace)
)
pairs;
if static_row row1 then begin
let rm = row_more row1 in
if is_Tvar rm then link_type rm (newty2 ~level:(get_level rm) Tnil)
end
with exn ->
Transient_expr.set_desc tm1 md1;
Transient_expr.set_desc tm2 md2;
raise exn
end
and unify_row_field uenv fixed1 fixed2 rm1 rm2 l f1 f2 =
let if_not_fixed (pos,fixed) f =
match fixed with
| None -> f ()
| Some fix ->
let tr = [Variant(Fixed_row(pos,Cannot_add_tags [l],fix))] in
raise_trace_for Unify tr in
let first = First, fixed1 and second = Second, fixed2 in
let either_fixed = match fixed1, fixed2 with
| None, None -> false
| _ -> true in
if f1 == f2 then () else
match row_field_repr f1, row_field_repr f2 with
Rpresent(Some t1), Rpresent(Some t2) -> unify uenv t1 t2
| Rpresent None, Rpresent None -> ()
| Reither(c1, tl1, m1), Reither(c2, tl2, m2) ->
if eq_row_field_ext f1 f2 then () else
let no_arg = c1 || c2 and matched = m1 || m2 in
if either_fixed && not no_arg
&& List.length tl1 = List.length tl2 then begin
let f = rf_either [] ~no_arg ~matched in
link_row_field_ext ~inside:f1 f; link_row_field_ext ~inside:f2 f;
List.iter2 (unify uenv) tl1 tl2
end
else let redo =
(m1 || m2 || either_fixed ||
!rigid_variants && (List.length tl1 = 1 || List.length tl2 = 1)) &&
begin match tl1 @ tl2 with [] -> false
| t1 :: tl ->
if no_arg then raise_unexplained_for Unify;
Types.changed_row_field_exts [f1;f2] (fun () ->
List.iter (unify uenv t1) tl
)
end in
if redo then unify_row_field uenv fixed1 fixed2 rm1 rm2 l f1 f2 else
let remq tl =
List.filter (fun ty -> not (List.exists (eq_type ty) tl)) in
let tl1' = remq tl2 tl1 and tl2' = remq tl1 tl2 in
let env = get_env uenv in
let (tlu1,tl1') = List.partition (has_free_univars env) tl1'
and (tlu2,tl2') = List.partition (has_free_univars env) tl2' in
begin match tlu1, tlu2 with
[], [] -> ()
| (tu1::tlu1), _ :: _ ->
List.iter (unify uenv tu1) (tlu1@tlu2)
| (tu::_, []) | ([], tu::_) ->
occur_univar_for Unify env tu
end;
let update_levels rm =
let env = get_env uenv in
List.iter
(fun ty ->
update_level_for Unify env (get_level rm) ty;
update_scope_for Unify (get_scope rm) ty)
in
update_levels rm2 tl1';
update_levels rm1 tl2';
let f1' = rf_either tl2' ~no_arg ~matched in
let f2' = rf_either tl1' ~use_ext_of:f1' ~no_arg ~matched in
link_row_field_ext ~inside:f1 f1'; link_row_field_ext ~inside:f2 f2';
| Reither(_, _, false), Rabsent ->
if_not_fixed first (fun () -> link_row_field_ext ~inside:f1 f2)
| Rabsent, Reither(_, _, false) ->
if_not_fixed second (fun () -> link_row_field_ext ~inside:f2 f1)
| Rabsent, Rabsent -> ()
| Reither(false, tl, _), Rpresent(Some t2) ->
if_not_fixed first (fun () ->
let s = snapshot () in
link_row_field_ext ~inside:f1 f2;
update_level_for Unify (get_env uenv) (get_level rm1) t2;
update_scope_for Unify (get_scope rm1) t2;
(try List.iter (fun t1 -> unify uenv t1 t2) tl
with exn -> undo_first_change_after s; raise exn)
)
| Rpresent(Some t1), Reither(false, tl, _) ->
if_not_fixed second (fun () ->
let s = snapshot () in
link_row_field_ext ~inside:f2 f1;
update_level_for Unify (get_env uenv) (get_level rm2) t1;
update_scope_for Unify (get_scope rm2) t1;
(try List.iter (unify uenv t1) tl
with exn -> undo_first_change_after s; raise exn)
)
| Reither(true, [], _), Rpresent None ->
if_not_fixed first (fun () -> link_row_field_ext ~inside:f1 f2)
| Rpresent None, Reither(true, [], _) ->
if_not_fixed second (fun () -> link_row_field_ext ~inside:f2 f1)
| Rabsent, (Rpresent _ | Reither(_,_,true)) ->
raise_trace_for Unify [Variant(No_tags(First, [l,f1]))]
| (Rpresent _ | Reither (_,_,true)), Rabsent ->
raise_trace_for Unify [Variant(No_tags(Second, [l,f2]))]
| (Rpresent (Some _) | Reither(false,_,_)),
(Rpresent None | Reither(true,_,_))
| (Rpresent None | Reither(true,_,_)),
(Rpresent (Some _) | Reither(false,_,_)) ->
raise_unexplained_for Unify
| Reither(true, _ :: _, _ ), Rpresent _
| Rpresent _ , Reither(true, _ :: _, _ ) ->
raise_unexplained_for Unify
let unify uenv ty1 ty2 =
let snap = Btype.snapshot () in
try
unify uenv ty1 ty2
with
Unify_trace trace ->
undo_compress snap;
raise (Unify (expand_to_unification_error (get_env uenv) trace))
let unify_gadt (penv : Pattern_env.t) ty1 ty2 =
Misc.protect_refs [R (univar_pairs, [])] begin fun () ->
let equated_types = TypePairs.create 0 in
let equations_generation =
Allowed { equated_types; pattern_stage = Env.stage penv.env }
in
let uenv = Pattern
{ penv;
equations_generation;
assume_injective = true;
unify_eq_set = TypePairs.create 11; }
in
unify uenv ty1 ty2;
equated_types
end
let unify_var uenv t1 t2 =
if eq_type t1 t2 then () else
match get_desc t1, get_desc t2 with
Tvar _, Tconstr _ when deep_occur t1 t2 ->
unify uenv t1 t2
| Tvar { jkind }, _ ->
let env = get_env uenv in
let reset_tracing = check_trace_gadt_instances env in
begin try
occur_for Unify uenv t1 t2;
update_level_for Unify env (get_level t1) t2;
update_scope_for Unify (get_scope t1) t2;
unification_jkind_check uenv t2 (Jkind.disallow_left jkind);
link_type t1 t2;
reset_trace_gadt_instances reset_tracing;
with Unify_trace trace ->
reset_trace_gadt_instances reset_tracing;
raise (Unify (expand_to_unification_error
env
(Diff { got = t1; expected = t2 } :: trace)))
end
| _ ->
unify uenv t1 t2
let _ = unify_var' := unify_var
let unify_var env ty1 ty2 =
unify_var (Expression {env; in_subst = false}) ty1 ty2
let unify_pairs env ty1 ty2 pairs =
Misc.protect_refs [R (univar_pairs, pairs)] begin fun () ->
univar_pairs := pairs;
unify (Expression {env; in_subst = false}) ty1 ty2
end
let unify env ty1 ty2 =
unify_pairs env ty1 ty2 []
let unify_delaying_jkind_checks env ty1 ty2 =
delay_jkind_checks_in (fun () ->
unify_pairs env ty1 ty2 [])
let enforce_current_level env ty =
unify_var env (newvar (Jkind.Builtin.any ~why:Dummy_jkind)) ty
let expand_head_trace env t =
let reset_tracing = check_trace_gadt_instances env in
let t = expand_head_unif env t in
reset_trace_gadt_instances reset_tracing;
t
type filter_arrow_failure =
| Unification_error of unification_error
| Label_mismatch of
{ got : arg_label
; expected : arg_label
; expected_type : type_expr
}
| Not_a_function
| Jkind_error of type_expr * Jkind.Violation.t
exception Filter_arrow_failed of filter_arrow_failure
type filtered_arrow =
{ ty_arg : type_expr;
arg_mode : Mode.Alloc.lr;
ty_ret : type_expr;
ret_mode : Mode.Alloc.lr
}
let filter_arrow env t l ~force_tpoly =
let function_type level =
let k_arg = Jkind.Builtin.any ~why:Inside_of_Tarrow in
let k_res = Jkind.Builtin.any ~why:Inside_of_Tarrow in
let ty_arg =
if not force_tpoly then begin
assert (not (is_optional l));
newvar2 level k_arg
end else begin
let t1 =
if is_optional l then
newty2 ~level
(Tconstr(Predef.path_option,
[newvar2 level Predef.option_argument_jkind],
ref Mnil))
else if is_position l then
newty2 ~level (Tconstr (Predef.path_lexing_position, [], ref Mnil))
else
newvar2 level k_arg
in
newty2 ~level (Tpoly(t1, []))
end
in
let ty_ret = newvar2 level k_res in
let arg_mode = Alloc.newvar () in
let ret_mode = Alloc.newvar () in
let t' =
newty2 ~level (Tarrow ((l, arg_mode, ret_mode), ty_arg, ty_ret, commu_ok))
in
t', { ty_arg; arg_mode; ty_ret; ret_mode }
in
let t =
try expand_head_trace env t
with Unify_trace trace ->
let t', _ = function_type (get_level t) in
raise (Filter_arrow_failed
(Unification_error
(expand_to_unification_error
env
(Diff { got = t'; expected = t } :: trace))))
in
match get_desc t with
Tvar { jkind } ->
let t', arrow_desc = function_type (get_level t) in
begin match constrain_type_jkind env t' (Jkind.disallow_left jkind) with
| Ok _ -> ()
| Error err ->
raise (Filter_arrow_failed
(Unification_error
(expand_to_unification_error
env
[Bad_jkind (t',err)])))
end;
link_type t t';
arrow_desc
| Tarrow((l', arg_mode, ret_mode), ty_arg, ty_ret, _) ->
if l = l' || !Clflags.classic && l = Nolabel &&
equivalent_with_nolabels l l'
then
{ ty_arg; arg_mode; ty_ret; ret_mode }
else raise (Filter_arrow_failed
(Label_mismatch
{ got = l; expected = l'; expected_type = t }))
| _ ->
raise (Filter_arrow_failed Not_a_function)
exception Filter_mono_failed
let filter_mono ty =
match get_desc ty with
| Tpoly(ty, []) -> ty
| Tpoly _ -> raise Filter_mono_failed
| _ -> assert false
exception Filter_arrow_mono_failed
let filter_arrow_mono env t l =
match filter_arrow env t l ~force_tpoly:true with
| exception Filter_arrow_failed _ -> raise Filter_arrow_mono_failed
| {ty_arg; _} as farr ->
match filter_mono ty_arg with
| exception Filter_mono_failed -> raise Filter_arrow_mono_failed
| ty_arg -> { farr with ty_arg }
type filter_method_failure =
| Unification_error of unification_error
| Not_a_method
| Not_an_object of type_expr
| Not_a_value of Jkind.Violation.t
exception Filter_method_failed of filter_method_failure
let rec filter_method_field env name ty =
let method_type ~level =
let ty1 = newvar2 level (Jkind.Builtin.value ~why:Object_field) in
let ty2 = newvar2 level (Jkind.Builtin.value ~why:Row_variable) in
let ty' = newty2 ~level (Tfield (name, field_public, ty1, ty2)) in
ty', ty1
in
let ty =
try expand_head_trace env ty
with Unify_trace trace ->
let level = get_level ty in
let ty', _ = method_type ~level in
raise (Filter_method_failed
(Unification_error
(expand_to_unification_error
env
(Diff { got = ty; expected = ty' } :: trace))))
in
match get_desc ty with
| Tvar _ ->
let level = get_level ty in
let ty', ty1 = method_type ~level in
link_type ty ty';
ty1
| Tfield(n, kind, ty1, ty2) ->
if n = name then begin
unify_kind kind field_public;
ty1
end else
filter_method_field env name ty2
| _ ->
raise (Filter_method_failed Not_a_method)
let filter_method env name ty =
let object_type ~level ~scope =
let ty1 = newvar2 level (Jkind.Builtin.value ~why:Row_variable) in
let ty' = newty3 ~level ~scope (Tobject (ty1, ref None)) in
let ty_meth = filter_method_field env name ty1 in
(ty', ty_meth)
in
let ty =
try expand_head_trace env ty
with Unify_trace trace ->
let level = get_level ty in
let scope = get_scope ty in
let ty', _ = object_type ~level ~scope in
raise (Filter_method_failed
(Unification_error
(expand_to_unification_error
env
(Diff { got = ty; expected = ty' } :: trace))))
in
match get_desc ty with
| Tvar _ ->
let level = get_level ty in
let scope = get_scope ty in
let ty', ty_meth = object_type ~level ~scope in
begin match
constrain_type_jkind env ty (Jkind.Builtin.value ~why:Object)
with
| Ok _ -> ()
| Error err -> raise (Filter_method_failed (Not_a_value err))
end;
link_type ty ty';
ty_meth
| Tobject(f, _) ->
filter_method_field env name f
| _ ->
raise (Filter_method_failed (Not_an_object ty))
exception Filter_method_row_failed
let rec filter_method_row env name priv ty =
let ty = expand_head env ty in
match get_desc ty with
| Tvar _ ->
let level = get_level ty in
let field = newvar2 level (Jkind.Builtin.value ~why:Object_field) in
let row = newvar2 level (Jkind.Builtin.value ~why:Row_variable) in
let kind, priv =
match priv with
| Private ->
let kind = field_private () in
kind, Mprivate kind
| Public ->
field_public, Mpublic
in
let ty' = newty2 ~level (Tfield (name, kind, field, row)) in
link_type ty ty';
priv, field, row
| Tfield(n, kind, ty1, ty2) ->
if n = name then begin
let priv =
match priv with
| Public ->
unify_kind kind field_public;
Mpublic
| Private -> Mprivate kind
in
priv, ty1, ty2
end else begin
let level = get_level ty in
let priv, field, row = filter_method_row env name priv ty2 in
let row = newty2 ~level (Tfield (n, kind, ty1, row)) in
priv, field, row
end
| Tnil ->
if name = Btype.dummy_method then raise Filter_method_row_failed
else begin
match priv with
| Public -> raise Filter_method_row_failed
| Private ->
let level = get_level ty in
let kind = field_absent in
Mprivate kind, newvar2 level (Jkind.Builtin.value ~why:Object_field), ty
end
| _ ->
raise Filter_method_row_failed
let new_class_signature () =
let row = newvar (Jkind.Builtin.value ~why:Row_variable) in
let self = newobj row in
{ csig_self = self;
csig_self_row = row;
csig_vars = Vars.empty;
csig_meths = Meths.empty; }
let add_dummy_method env ~scope sign =
let _, ty, row =
filter_method_row env dummy_method Private sign.csig_self_row
in
unify env ty (new_scoped_ty scope (Ttuple []));
sign.csig_self_row <- row
type add_method_failure =
| Unexpected_method
| Type_mismatch of Errortrace.unification_error
exception Add_method_failed of add_method_failure
let add_method env label priv virt ty sign =
let meths = sign.csig_meths in
let priv, virt =
match Meths.find label meths with
| (priv', virt', ty') -> begin
let priv =
match priv' with
| Mpublic -> Mpublic
| Mprivate k ->
match priv with
| Public ->
begin match field_kind_repr k with
| Fpublic -> ()
| Fprivate -> link_kind ~inside:k field_public
| Fabsent -> assert false
end;
Mpublic
| Private -> priv'
in
let virt =
match virt' with
| Concrete -> Concrete
| Virtual -> virt
in
match unify env ty ty' with
| () -> priv, virt
| exception Unify trace ->
raise (Add_method_failed (Type_mismatch trace))
end
| exception Not_found -> begin
let priv, ty', row =
match filter_method_row env label priv sign.csig_self_row with
| priv, ty', row ->
priv, ty', row
| exception Filter_method_row_failed ->
raise (Add_method_failed Unexpected_method)
in
match unify env ty ty' with
| () ->
sign.csig_self_row <- row;
priv, virt
| exception Unify trace ->
raise (Add_method_failed (Type_mismatch trace))
end
in
let meths = Meths.add label (priv, virt, ty) meths in
sign.csig_meths <- meths
type add_instance_variable_failure =
| Mutability_mismatch of mutable_flag
| Type_mismatch of Errortrace.unification_error
exception Add_instance_variable_failed of add_instance_variable_failure
let check_mutability (mut : mutable_flag) (mut' : mutable_flag) =
match mut, mut' with
| Mutable, Mutable -> ()
| Immutable, Immutable -> ()
| Mutable, Immutable | Immutable, Mutable ->
raise (Add_instance_variable_failed (Mutability_mismatch mut))
let add_instance_variable ~strict env label mut virt ty sign =
let vars = sign.csig_vars in
let virt =
match Vars.find label vars with
| (mut', virt', ty') ->
let virt =
match virt' with
| Concrete -> Concrete
| Virtual -> virt
in
if strict then begin
check_mutability mut mut';
match unify env ty ty' with
| () -> ()
| exception Unify trace ->
raise (Add_instance_variable_failed (Type_mismatch trace))
end;
virt
| exception Not_found -> virt
in
let vars = Vars.add label (mut, virt, ty) vars in
sign.csig_vars <- vars
type inherit_class_signature_failure =
| Self_type_mismatch of Errortrace.unification_error
| Method of label * add_method_failure
| Instance_variable of label * add_instance_variable_failure
exception Inherit_class_signature_failed of inherit_class_signature_failure
let unify_self_types env sign1 sign2 =
let self_type1 = sign1.csig_self in
let self_type2 = sign2.csig_self in
match unify env self_type1 self_type2 with
| () -> ()
| exception Unify err -> begin
match err.trace with
| Errortrace.Diff _ :: Errortrace.Incompatible_fields {name; _} :: rem ->
let err = Errortrace.unification_error ~trace:rem in
let failure = Method (name, Type_mismatch err) in
raise (Inherit_class_signature_failed failure)
| _ ->
raise (Inherit_class_signature_failed (Self_type_mismatch err))
end
let inherit_class_signature ~strict env sign1 sign2 =
unify_self_types env sign1 sign2;
Meths.iter
(fun label (priv, virt, ty) ->
let priv =
match priv with
| Mpublic -> Public
| Mprivate kind ->
assert (field_kind_repr kind = Fabsent);
Private
in
match add_method env label priv virt ty sign1 with
| () -> ()
| exception Add_method_failed failure ->
let failure = Method(label, failure) in
raise (Inherit_class_signature_failed failure))
sign2.csig_meths;
Vars.iter
(fun label (mut, virt, ty) ->
match add_instance_variable ~strict env label mut virt ty sign1 with
| () -> ()
| exception Add_instance_variable_failed failure ->
let failure = Instance_variable(label, failure) in
raise (Inherit_class_signature_failed failure))
sign2.csig_vars
let update_class_signature env sign =
let self = expand_head env sign.Types.csig_self in
let fields, row = flatten_fields (object_fields self) in
let meths, implicitly_public, implicitly_declared =
List.fold_left
(fun (meths, implicitly_public, implicitly_declared) (lab, k, ty) ->
if lab = dummy_method then
meths, implicitly_public, implicitly_declared
else begin
match Meths.find lab meths with
| priv, virt, ty' ->
let meths, implicitly_public =
match priv, field_kind_repr k with
| Mpublic, _ -> meths, implicitly_public
| Mprivate _, Fpublic ->
let meths = Meths.add lab (Mpublic, virt, ty') meths in
let implicitly_public = lab :: implicitly_public in
meths, implicitly_public
| Mprivate _, _ -> meths, implicitly_public
in
meths, implicitly_public, implicitly_declared
| exception Not_found ->
let meths, implicitly_declared =
match field_kind_repr k with
| Fpublic ->
let meths = Meths.add lab (Mpublic, Virtual, ty) meths in
let implicitly_declared = lab :: implicitly_declared in
meths, implicitly_declared
| Fprivate ->
let meths =
Meths.add lab (Mprivate k, Virtual, ty) meths
in
let implicitly_declared = lab :: implicitly_declared in
meths, implicitly_declared
| Fabsent -> meths, implicitly_declared
in
meths, implicitly_public, implicitly_declared
end)
(sign.csig_meths, [], []) fields
in
sign.csig_meths <- meths;
sign.csig_self_row <- row;
implicitly_public, implicitly_declared
let hide_private_methods env sign =
let self = expand_head env sign.Types.csig_self in
let fields, _ = flatten_fields (object_fields self) in
List.iter
(fun (_, k, _) ->
match field_kind_repr k with
| Fprivate -> link_kind ~inside:k field_absent
| _ -> ())
fields
let close_class_signature env sign =
let rec close env ty =
let ty = expand_head env ty in
match get_desc ty with
| Tvar _ ->
let level = get_level ty in
link_type ty (newty2 ~level Tnil); true
| Tfield(lab, _, _, _) when lab = dummy_method ->
false
| Tfield(_, _, _, ty') -> close env ty'
| Tnil -> true
| _ -> assert false
in
let self = expand_head env sign.csig_self in
close env (object_fields self)
let generalize_class_signature_spine env sign =
let meths = sign.csig_meths in
Meths.iter (fun _ (_, _, ty) -> generalize_spine ty) meths;
let new_meths =
Meths.map
(fun (priv, virt, ty) -> (priv, virt, generic_instance ty))
meths
in
Meths.iter
(fun _ (_, _, ty) ->
unify_var env (newvar (Jkind.Builtin.value ~why:Object)) ty)
meths;
sign.csig_meths <- new_meths
let moregen_occur env level ty =
with_type_mark begin fun mark ->
let rec occur ty =
let lv = get_level ty in
if lv <= level then () else
if is_Tvar ty && lv >= generic_level - 1 then raise Occur else
if try_mark_node mark ty then iter_type_expr occur ty
in
try
occur ty
with Occur ->
raise_unexplained_for Moregen
end;
occur_univar_for Moregen env ty;
update_level_for Moregen env level ty
type moregen_pairs =
{ invariant_pairs : TypePairs.t;
covariant_pairs : TypePairs.t;
contravariant_pairs : TypePairs.t;
bivariant_pairs : TypePairs.t; }
let fresh_moregen_pairs () =
{ invariant_pairs = TypePairs.create 13;
covariant_pairs = TypePairs.create 13;
contravariant_pairs = TypePairs.create 13;
bivariant_pairs = TypePairs.create 13; }
type moregen_variance =
| Invariant
| Covariant
| Contravariant
| Bivariant
let neg_variance = function
| Invariant -> Invariant
| Covariant -> Contravariant
| Contravariant -> Covariant
| Bivariant -> Bivariant
let compose_variance variance v =
match variance with
| Invariant -> Invariant
| Bivariant -> Bivariant
| Covariant | Contravariant ->
match Variance.get_upper v with
| true, true -> Invariant
| false, false -> Bivariant
| false, true -> neg_variance variance
| true, false -> variance
let relevant_pairs pairs v =
match v with
| Invariant -> pairs.invariant_pairs
| Covariant -> pairs.covariant_pairs
| Contravariant -> pairs.contravariant_pairs
| Bivariant -> pairs.bivariant_pairs
let zap_modalities_to_floor_if_modes_enabled_at level =
if Language_extension.(is_at_least Mode level)
then Mode.Modality.zap_to_floor
else Mode.Modality.zap_to_id
(** The mode crossing of the memory block of a structure. *)
let mode_crossing_structure_memaddr =
Mode.Crossing.create
~uniqueness:false
~contention:true
~visibility:true
~regionality:false
~linearity:true
~portability:true
~forkable:true
~yielding:true
~statefulness:true
~staticity:false
(** The mode crossing of a functor. *)
let mode_crossing_functor =
Mode.Crossing.create
~uniqueness:true
~contention:true
~visibility:true
~regionality:false
~linearity:false
~portability:false
~forkable:false
~yielding:false
~statefulness:false
~staticity:false
(** The mode crossing of any module. *)
let mode_crossing_module = Mode.Crossing.max
let zap_modalities_to_floor_if_at_least level =
if Language_extension.(is_at_least Mode level)
then Mode.Modality.zap_to_floor
else Mode.Modality.zap_to_id
let crossing_of_jkind env jkind =
let context = mk_jkind_context_check_principal env in
Ikind.crossing_of_jkind ~context env jkind
let crossing_of_ty env ?modalities ty =
let principal = is_principal ty in
let crossing =
if not principal
then Crossing.max
else
let jkind_crossing () =
let jkind = type_jkind_purely env ty in
crossing_of_jkind env jkind
in
if !Clflags.ikinds
then (
let ikind_crossing = Ikind.crossing_of_type env ty in
if debug_ikind_crossing_mismatch then (
let old_jkind_crossing = jkind_crossing () in
if not (Crossing.equal ikind_crossing old_jkind_crossing)
then
Format.eprintf
"@[<v>[ikind-crossing-mismatch]@ \
type=%a@ \
ikind=%a@ \
jkind=%a@]@."
!Btype.print_raw ty
(Format_doc.compat Crossing.print) ikind_crossing
(Format_doc.compat Crossing.print) old_jkind_crossing
);
ikind_crossing)
else
jkind_crossing ()
in
match modalities with
| None -> crossing
| Some m -> Crossing.modality m crossing
let cross_left env ?modalities ty mode =
let crossing = crossing_of_ty env ?modalities ty in
mode |> Value.disallow_right |> Crossing.apply_left crossing
let cross_right env ?modalities ty mode =
let crossing = crossing_of_ty env ?modalities ty in
mode |> Value.disallow_left |> Crossing.apply_right crossing
let cross_left_alloc env ?modalities ty mode =
let crossing = crossing_of_ty env ?modalities ty in
mode |> Alloc.disallow_right |> Crossing.apply_left_alloc crossing
let cross_right_alloc env ?modalities ty mode =
let crossing = crossing_of_ty env ?modalities ty in
mode |> Alloc.disallow_left |> Crossing.apply_right_alloc crossing
let submode_with_cross env ~is_ret ty l r =
let r' = cross_right_alloc env ty r in
let r' =
if is_ret then
Alloc.meet
[r';
Alloc.max_with_comonadic Areality (Alloc.proj_comonadic Areality r)]
else
r'
in
Alloc.submode l r'
let moregen_alloc_mode env ~is_ret ty v a1 a2 =
match
match v with
| Invariant ->
Result.bind (submode_with_cross env ~is_ret ty a1 a2)
(fun _ -> submode_with_cross env ~is_ret ty a2 a1)
|> Result.map_error ignore
| Covariant -> Result.map_error ignore (submode_with_cross env ~is_ret ty a1 a2)
| Contravariant -> Result.map_error ignore (submode_with_cross env ~is_ret ty a2 a1)
| Bivariant -> Ok ()
with
| Ok () -> ()
| Error _ -> raise_unexplained_for Moregen
let may_instantiate inst_nongen t1 =
let level = get_level t1 in
if inst_nongen then level <> generic_level - 1
else level = generic_level
let rec moregen inst_nongen variance type_pairs env t1 t2 =
if eq_type t1 t2 then () else
try
match (get_desc t1, get_desc t2) with
(Tvar { jkind }, _) when may_instantiate inst_nongen t1
&& not (deep_occur t1 t2) ->
moregen_occur env (get_level t1) t2;
update_scope_for Moregen (get_scope t1) t2;
check_type_jkind_exn env Moregen t2 (Jkind.disallow_left jkind);
link_type t1 t2
| (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
()
| _ ->
let t1' = expand_head env t1 in
let t2' = expand_head env t2 in
if eq_type t1' t2' then () else
let pairs = relevant_pairs type_pairs variance in
if not (TypePairs.mem pairs (t1', t2')) then begin
TypePairs.add pairs (t1', t2');
match (get_desc t1', get_desc t2') with
(Tvar { jkind }, _) when may_instantiate inst_nongen t1' ->
let t2 = reduce_head ~expand_eval:false env t2 in
moregen_occur env (get_level t1') t2;
update_scope_for Moregen (get_scope t1') t2;
check_type_jkind_exn env Moregen t2 (Jkind.disallow_left jkind);
link_type t1' t2
| (Tarrow ((l1,a1,r1), t1, u1, _),
Tarrow ((l2,a2,r2), t2, u2, _)) when
(l1 = l2
|| !Clflags.classic && equivalent_with_nolabels l1 l2) ->
moregen inst_nongen (neg_variance variance) type_pairs env t1 t2;
moregen inst_nongen variance type_pairs env u1 u2;
moregen_alloc_mode env t2 ~is_ret:false (neg_variance variance) a1 a2;
moregen_alloc_mode env u2 ~is_ret:true variance r1 r2
| (Ttuple labeled_tl1, Ttuple labeled_tl2) ->
moregen_labeled_list inst_nongen variance type_pairs env
labeled_tl1 labeled_tl2
| (Tunboxed_tuple labeled_tl1, Tunboxed_tuple labeled_tl2) ->
moregen_labeled_list inst_nongen variance type_pairs env
labeled_tl1 labeled_tl2
| (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _))
when Path.same p1 p2 -> begin
match variance with
| Invariant | Bivariant ->
moregen_list inst_nongen variance type_pairs env tl1 tl2
| _ ->
match Env.find_type p1 env with
| decl ->
moregen_param_list inst_nongen variance type_pairs env
decl.type_variance tl1 tl2
| exception Not_found ->
moregen_list inst_nongen Invariant type_pairs env tl1 tl2
end
| (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
begin try
unify_package env (moregen_list inst_nongen variance type_pairs env)
(get_level t1') p1 fl1 (get_level t2') p2 fl2
with Not_found -> raise_unexplained_for Moregen
end
| (Tnil, Tconstr _ ) -> raise_for Moregen (Obj (Abstract_row Second))
| (Tconstr _, Tnil ) -> raise_for Moregen (Obj (Abstract_row First))
| (Tvariant row1, Tvariant row2) ->
moregen_row inst_nongen variance type_pairs env row1 row2
| (Tobject (fi1, _nm1), Tobject (fi2, _nm2)) ->
moregen_fields inst_nongen variance type_pairs env fi1 fi2
| (Tfield _, Tfield _) ->
moregen_fields inst_nongen variance type_pairs env
t1' t2'
| (Tnil, Tnil) ->
()
| (Tpoly (t1, []), Tpoly (t2, [])) ->
moregen inst_nongen variance type_pairs env t1 t2
| (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
enter_poly_for Moregen env univar_pairs t1 tl1 t2 tl2
(moregen inst_nongen variance type_pairs env)
| (Trepr (t1, sort_vars1), Trepr (t2, sort_vars2)) ->
(try
let pairs = List.combine sort_vars1 sort_vars2 in
Jkind_types.Sort.enter_repr pairs (fun () ->
moregen inst_nongen variance type_pairs env t1 t2)
with Invalid_argument _ -> raise_unexplained_for Moregen)
| (Tunivar {jkind=k1}, Tunivar {jkind=k2}) ->
unify_univar_for Moregen env t1' t2' k1 k2 !univar_pairs
| (Tquote t1, _) ->
moregen inst_nongen variance type_pairs
(incr_stage env) t1 (new_splice_ty t2)
| (Tsplice t1, _) ->
moregen inst_nongen variance type_pairs
(decr_stage env) t1 (new_quote_ty t2)
| (Tquote_eval t1, Tquote_eval t2) ->
moregen inst_nongen variance type_pairs
(incr_stage env) t1 t2
| (_, _) ->
raise_unexplained_for Moregen
end
with Moregen_trace trace ->
raise_trace_for Moregen (Diff {got = t1; expected = t2} :: trace)
and moregen_list inst_nongen variance type_pairs env tl1 tl2 =
if List.length tl1 <> List.length tl2 then
raise_unexplained_for Moregen;
List.iter2 (moregen inst_nongen variance type_pairs env) tl1 tl2
and moregen_labeled_list inst_nongen variance type_pairs env labeled_tl1
labeled_tl2 =
if not (Int.equal (List.length labeled_tl1) (List.length labeled_tl2)) then
raise_unexplained_for Moregen;
List.iter2
(fun (label1, ty1) (label2, ty2) ->
if not (Option.equal String.equal label1 label2) then
raise_unexplained_for Moregen;
moregen inst_nongen variance type_pairs env ty1 ty2)
labeled_tl1 labeled_tl2
and moregen_param_list inst_nongen variance type_pairs env vl tl1 tl2 =
match vl, tl1, tl2 with
| [], [], [] -> ()
| v :: vl, t1 :: tl1, t2 :: tl2 ->
let param_variance = compose_variance variance v in
moregen inst_nongen param_variance type_pairs env t1 t2;
moregen_param_list inst_nongen variance type_pairs env vl tl1 tl2
| _, _, _ -> raise_unexplained_for Moregen
and moregen_fields inst_nongen variance type_pairs env ty1 ty2 =
let (fields1, rest1) = flatten_fields ty1
and (fields2, rest2) = flatten_fields ty2 in
let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
begin
match miss1 with
| (n, _, _) :: _ -> raise_for Moregen (Obj (Missing_field (Second, n)))
| [] -> ()
end;
moregen inst_nongen variance type_pairs env rest1
(build_fields (get_level ty2) miss2 rest2);
List.iter
(fun (name, k1, t1, k2, t2) ->
moregen_kind k1 k2;
try moregen inst_nongen variance type_pairs env t1 t2 with Moregen_trace trace ->
raise_trace_for Moregen
(incompatible_fields ~name ~got:t1 ~expected:t2 :: trace)
)
pairs
and moregen_kind k1 k2 =
match field_kind_repr k1, field_kind_repr k2 with
(Fprivate, (Fprivate | Fpublic)) -> link_kind ~inside:k1 k2
| (Fpublic, Fpublic) -> ()
| (Fpublic, Fprivate) -> raise Public_method_to_private_method
| (Fabsent, _) | (_, Fabsent) -> assert false
and moregen_row inst_nongen variance type_pairs env row1 row2 =
let Row {fields = row1_fields; more = rm1; closed = row1_closed} =
row_repr row1 in
let Row {fields = row2_fields; more = rm2; closed = row2_closed;
fixed = row2_fixed} = row_repr row2 in
if eq_type rm1 rm2 then () else
let may_inst =
is_Tvar rm1 && may_instantiate inst_nongen rm1 || get_desc rm1 = Tnil in
let r1, r2, pairs = merge_row_fields row1_fields row2_fields in
let r1, r2 =
if row2_closed then
filter_row_fields may_inst r1, filter_row_fields false r2
else r1, r2
in
begin
if r1 <> [] then raise_for Moregen (Variant (No_tags (Second, r1)))
end;
if row1_closed then begin
match row2_closed, r2 with
| false, _ -> raise_for Moregen (Variant (Openness Second))
| _, _ :: _ -> raise_for Moregen (Variant (No_tags (First, r2)))
| _, [] -> ()
end;
let md1 = get_desc rm1 in
begin match md1, get_desc rm2 with
Tunivar {jkind=k1}, Tunivar {jkind=k2} ->
unify_univar_for Moregen env rm1 rm2 k1 k2 !univar_pairs
| Tunivar _, _ | _, Tunivar _ ->
raise_unexplained_for Moregen
| _ when static_row row1 -> ()
| _ when may_inst ->
let ext =
newgenty (Tvariant
(create_row ~fields:r2 ~more:rm2 ~name:None
~fixed:row2_fixed ~closed:row2_closed))
in
moregen_occur env (get_level rm1) ext;
update_scope_for Moregen (get_scope rm1) ext;
link_type rm1 ext
| Tconstr _, Tconstr _ ->
moregen inst_nongen variance type_pairs env rm1 rm2
| _ -> raise_unexplained_for Moregen
end;
try
List.iter
(fun (l,f1,f2) ->
if f1 == f2 then () else
match row_field_repr f1, row_field_repr f2 with
| Rpresent(Some t1), Rpresent(Some t2) -> begin
try
moregen inst_nongen variance type_pairs env t1 t2
with Moregen_trace trace ->
raise_trace_for Moregen
(Variant (Incompatible_types_for l) :: trace)
end
| Rpresent None, Rpresent None -> ()
| Reither(c1, tl1, _), Reither(c2, tl2, m2) -> begin
try
if not (eq_row_field_ext f1 f2) then begin
if c1 && not c2 then raise_unexplained_for Moregen;
let f2' =
rf_either [] ~use_ext_of:f2 ~no_arg:c2 ~matched:m2 in
link_row_field_ext ~inside:f1 f2';
if List.length tl1 = List.length tl2 then
List.iter2 (moregen inst_nongen variance type_pairs env) tl1 tl2
else match tl2 with
| t2 :: _ ->
List.iter
(fun t1 -> moregen inst_nongen variance type_pairs env t1 t2)
tl1
| [] -> if tl1 <> [] then raise_unexplained_for Moregen
end
with Moregen_trace trace ->
raise_trace_for Moregen
(Variant (Incompatible_types_for l) :: trace)
end
| Reither(false, tl1, _), Rpresent(Some t2) when may_inst -> begin
try
link_row_field_ext ~inside:f1 f2;
List.iter
(fun t1 -> moregen inst_nongen variance type_pairs env t1 t2)
tl1
with Moregen_trace trace ->
raise_trace_for Moregen
(Variant (Incompatible_types_for l) :: trace)
end
| Reither(true, [], _), Rpresent None when may_inst ->
link_row_field_ext ~inside:f1 f2
| Reither(_, _, _), Rabsent when may_inst ->
link_row_field_ext ~inside:f1 f2
| Rabsent, Rabsent -> ()
| Rpresent (Some _), Rpresent None
| Rpresent None, Rpresent (Some _) ->
raise_for Moregen (Variant (Incompatible_types_for l))
| Reither _, Rpresent _ ->
raise_for Moregen
(Variant (Presence_not_guaranteed_for (First, l)))
| Rpresent _, Reither _ ->
raise_for Moregen
(Variant (Presence_not_guaranteed_for (Second, l)))
| Rabsent, (Rpresent _ | Reither _) ->
raise_for Moregen (Variant (No_tags (First, [l, f2])))
| (Rpresent _ | Reither _), Rabsent ->
raise_for Moregen (Variant (No_tags (Second, [l, f1]))))
pairs
with exn ->
set_type_desc rm1 md1; raise exn
let moregeneral env inst_nongen pat_sort_vars subj_sort_vars pat_sch subj_sch =
let old_level = !current_level in
Misc.try_finally
(fun () ->
current_level := generic_level - 1;
let (subj_sorts, subj_inst) =
Jkind_types.Sort.instance_with ~level:!current_level subj_sort_vars
(fun () -> instance subj_sch)
in
let subj = duplicate_type subj_inst in
current_level := generic_level;
let (pat_sorts, patt) =
Jkind_types.Sort.instance_with ~level:!current_level pat_sort_vars
(fun () -> instance pat_sch)
in
try
Misc.protect_refs [R (univar_pairs, [])] begin fun () ->
let type_pairs = fresh_moregen_pairs () in
moregen inst_nongen Covariant type_pairs env patt subj;
let subj_sort_vars =
List.map (fun v -> Jkind_types.Sort.Var v) subj_sort_vars
in
let subst_map = List.combine subj_sorts subj_sort_vars in
List.map
(fun v ->
v
|> Jkind_types.Sort.get_representable_var
|> Option.map (Jkind_types.Sort.subst subst_map))
pat_sorts
end
with Moregen_trace trace ->
current_level := generic_level - 2;
let (), _sub_sorts =
Jkind_types.Sort.generalize_with (fun () -> generalize subj_inst)
in
raise (Moregen (expand_to_moregen_error env trace)))
~always:(fun () -> current_level := old_level)
let is_moregeneral env inst_nongen pat_sch subj_sch =
match moregeneral env inst_nongen [] [] pat_sch subj_sch with
| _ -> true
| exception Moregen _ -> false
let all_distinct_vars env vars =
let tys = ref TypeSet.empty in
List.for_all
(fun ty ->
let ty = expand_head env ty in
if TypeSet.mem ty !tys then false else begin
tys := TypeSet.add ty !tys;
is_Tvar ty
end)
vars
type matches_result =
| Unification_failure of Errortrace.unification_error
| Jkind_mismatch of { original_jkind : jkind_lr; inferred_jkind : jkind_lr
; ty : type_expr }
| All_good
module Rigidify = struct
let rec rigidify_rec mark vars ty =
if try_mark_node mark ty then
begin match get_desc ty with
| Tvar { name; jkind } ->
vars := TypeMap.add ty (name, jkind) !vars
| Tvariant row ->
let Row {more; name; closed} = row_repr row in
if is_Tvar more && not (has_fixed_explanation row) then begin
let more' = newty2 ~level:(get_level more) (get_desc more) in
let row' =
create_row ~fixed:(Some Rigid) ~fields:[] ~more:more'
~name ~closed
in link_type more (newty2 ~level:(get_level ty) (Tvariant row'))
end;
iter_row (rigidify_rec mark vars) row;
if not (static_row row) then
rigidify_rec mark vars (row_more row)
| _ ->
iter_type_expr (rigidify_rec mark vars) ty
end
type var = { name : string option
; original_jkind : jkind_lr
; ty : type_expr }
type t = var list
let rigidify_list tys =
let vars = ref TypeMap.empty in
with_type_mark (fun mark -> List.iter (rigidify_rec mark vars) tys);
List.map (fun (trans_expr, (name, original_jkind)) ->
{ ty = Transient_expr.type_expr trans_expr; name; original_jkind })
(TypeMap.bindings !vars)
let rigidify ty = rigidify_list [ty]
type matches_result =
| Unification_failure of
{ name : string option; ty : type_expr }
| Jkind_mismatch of { original_jkind : jkind_lr; inferred_jkind : jkind_lr
; ty : type_expr }
| All_good
let all_distinct_vars_with_original_jkinds env vars =
let tys = ref TypeSet.empty in
let folder acc { ty; name; original_jkind } =
match acc with
| Unification_failure _ | Jkind_mismatch _ -> acc
| All_good ->
let ty = expand_head env ty in
if TypeSet.mem ty !tys then Unification_failure { name; ty } else begin
tys := TypeSet.add ty !tys;
match get_desc ty with
| Tvar { jkind = inferred_jkind } ->
if Jkind.equate env inferred_jkind original_jkind
then All_good
else Jkind_mismatch { original_jkind; inferred_jkind; ty }
| _ -> Unification_failure { name; ty }
end
in
List.fold_left folder All_good vars
end
let matches ~expand_error_trace env ty ty' =
let snap = snapshot () in
let rigidify_info = Rigidify.rigidify ty in
cleanup_abbrev ();
match unify env ty ty' with
| () ->
let result =
match Rigidify.all_distinct_vars_with_original_jkinds env rigidify_info
with
| Unification_failure _name ->
let diff =
if expand_error_trace
then expanded_diff env ~got:ty ~expected:ty'
else unexpanded_diff ~got:ty ~expected:ty'
in
Unification_failure (unification_error ~trace:[diff])
| Jkind_mismatch { original_jkind; inferred_jkind; ty } ->
Jkind_mismatch { original_jkind; inferred_jkind; ty }
| All_good -> All_good
in
backtrack snap;
result
| exception Unify err ->
backtrack snap;
Unification_failure err
let expand_head_rigid env ty =
let old = !rigid_variants in
rigid_variants := true;
let ty' = expand_head env ty in
rigid_variants := old; ty'
let eqtype_subst env type_pairs subst t1 k1 t2 k2 ~do_jkind_check =
if List.exists
(fun (t,t') ->
let found1 = eq_type t1 t in
let found2 = eq_type t2 t' in
if found1 && found2 then true else
if found1 || found2 then raise_unexplained_for Equality else false)
!subst
then ()
else begin
if do_jkind_check && not (Jkind.equal env k1 k2)
then raise_for Equality (Unequal_var_jkinds (t1, k1, t2, k2));
subst := (t1, t2) :: !subst;
TypePairs.add type_pairs (t1, t2)
end
let rec eqtype rename type_pairs subst env ~do_jkind_check t1 t2 =
let check_phys_eq t1 t2 =
not rename && eq_type t1 t2
in
if check_phys_eq t1 t2 then () else
try
match (get_desc t1, get_desc t2) with
(Tvar { jkind = k1 }, Tvar { jkind = k2 }) when rename ->
eqtype_subst env type_pairs subst t1 k1 t2 k2 ~do_jkind_check
| (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
()
| (Tof_kind k1, Tof_kind k2) ->
if not (Jkind.equal env k1 k2)
then raise_for Equality (Unequal_tof_kind_jkinds (k1, k2))
| _ ->
let t1' = expand_head_rigid env t1 in
let t2' = expand_head_rigid env t2 in
if check_phys_eq t1' t2' then () else
if not (TypePairs.mem type_pairs (t1', t2')) then begin
TypePairs.add type_pairs (t1', t2');
match (get_desc t1', get_desc t2') with
(Tvar { jkind = k1 }, Tvar { jkind = k2 }) when rename ->
eqtype_subst env type_pairs subst t1' k1 t2' k2 ~do_jkind_check
| (Tarrow ((l1,a1,r1), t1, u1, _),
Tarrow ((l2,a2,r2), t2, u2, _)) when
(l1 = l2
|| !Clflags.classic && equivalent_with_nolabels l1 l2) ->
eqtype rename type_pairs subst env t1 t2 ~do_jkind_check:true;
eqtype rename type_pairs subst env u1 u2 ~do_jkind_check:true;
eqtype_alloc_mode a1 a2;
eqtype_alloc_mode r1 r2
| (Ttuple labeled_tl1, Ttuple labeled_tl2) ->
eqtype_labeled_list rename type_pairs subst env labeled_tl1
labeled_tl2
| (Tunboxed_tuple labeled_tl1, Tunboxed_tuple labeled_tl2) ->
eqtype_labeled_list rename type_pairs subst env labeled_tl1
labeled_tl2
| (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _))
when Path.same p1 p2 ->
eqtype_list_same_length rename type_pairs subst env tl1 tl2
~do_jkind_check:true
| (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
begin try
unify_package env
(eqtype_list rename type_pairs subst env ~do_jkind_check:true)
(get_level t1') p1 fl1 (get_level t2') p2 fl2
with Not_found -> raise_unexplained_for Equality
end
| (Tnil, Tconstr _ ) ->
raise_for Equality (Obj (Abstract_row Second))
| (Tconstr _, Tnil ) ->
raise_for Equality (Obj (Abstract_row First))
| (Tvariant row1, Tvariant row2) ->
eqtype_row rename type_pairs subst env row1 row2
| (Tobject (fi1, _nm1), Tobject (fi2, _nm2)) ->
eqtype_fields rename type_pairs subst env fi1 fi2
| (Tfield _, Tfield _) ->
eqtype_fields rename type_pairs subst env
t1' t2'
| (Tnil, Tnil) ->
()
| (Tpoly (t1, []), Tpoly (t2, [])) ->
eqtype rename type_pairs subst env t1 t2 ~do_jkind_check
| (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
enter_poly_for Equality env univar_pairs t1 tl1 t2 tl2
(eqtype rename type_pairs subst env ~do_jkind_check)
| (Trepr (t1, sort_vars1), Trepr (t2, sort_vars2)) ->
(try
let pairs = List.combine sort_vars1 sort_vars2 in
Jkind_types.Sort.enter_repr pairs (fun () ->
eqtype rename type_pairs subst env t1 t2 ~do_jkind_check)
with Invalid_argument _ -> raise_unexplained_for Equality)
| (Tunivar {jkind=k1}, Tunivar {jkind=k2}) ->
unify_univar_for Equality env t1' t2' k1 k2 !univar_pairs
| (Tquote t1, Tquote t2) ->
eqtype rename type_pairs subst
(incr_stage env) ~do_jkind_check t1 t2
| (Tsplice t1, Tsplice t2) ->
eqtype rename type_pairs subst
(decr_stage env) ~do_jkind_check t1 t2
| (Tquote_eval t1, Tquote_eval t2) ->
eqtype rename type_pairs subst
(incr_stage env) ~do_jkind_check t1 t2
| (_, _) ->
raise_unexplained_for Equality
end
with Equality_trace trace ->
raise_trace_for Equality (Diff {got = t1; expected = t2} :: trace)
and eqtype_list_same_length
rename type_pairs subst env tl1 tl2 ~do_jkind_check =
List.iter2 (eqtype rename type_pairs subst env ~do_jkind_check) tl1 tl2
and eqtype_list rename type_pairs subst env tl1 tl2 ~do_jkind_check =
if List.length tl1 <> List.length tl2 then
raise_unexplained_for Equality;
eqtype_list_same_length rename type_pairs subst env tl1 tl2 ~do_jkind_check
and eqtype_labeled_list rename type_pairs subst env labeled_tl1 labeled_tl2 =
if not (Int.equal (List.length labeled_tl1) (List.length labeled_tl2)) then
raise_unexplained_for Equality;
List.iter2
(fun (label1, ty1) (label2, ty2) ->
if not (Option.equal String.equal label1 label2) then
raise_unexplained_for Equality;
eqtype rename type_pairs subst env ty1 ty2 ~do_jkind_check:true)
labeled_tl1 labeled_tl2
and eqtype_fields rename type_pairs subst env ty1 ty2 =
let (fields1, rest1) = flatten_fields ty1 in
let (fields2, rest2) = flatten_fields ty2 in
let same_row =
(not rename && eq_type rest1 rest2) ||
TypePairs.mem type_pairs (rest1,rest2)
in
if same_row then () else
match get_desc (expand_head_rigid env rest2) with
Tobject(ty2,_) -> eqtype_fields rename type_pairs subst env ty1 ty2
| _ ->
let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
eqtype rename type_pairs subst env rest1 rest2 ~do_jkind_check:true;
match miss1, miss2 with
| ((n, _, _)::_, _) -> raise_for Equality (Obj (Missing_field (Second, n)))
| (_, (n, _, _)::_) -> raise_for Equality (Obj (Missing_field (First, n)))
| [], [] ->
List.iter
(function (name, k1, t1, k2, t2) ->
eqtype_kind k1 k2;
try
eqtype rename type_pairs subst env t1 t2 ~do_jkind_check:true;
with Equality_trace trace ->
raise_trace_for Equality
(incompatible_fields ~name ~got:t1 ~expected:t2 :: trace))
pairs
and eqtype_kind k1 k2 =
let k1 = field_kind_repr k1 in
let k2 = field_kind_repr k2 in
match k1, k2 with
| (Fprivate, Fprivate)
| (Fpublic, Fpublic) -> ()
| _ -> raise_unexplained_for Unify
and eqtype_row rename type_pairs subst env row1 row2 =
let eqtype = eqtype ~do_jkind_check:true in
match get_desc (expand_head_rigid env (row_more row2)) with
Tvariant row2 -> eqtype_row rename type_pairs subst env row1 row2
| _ ->
let r1, r2, pairs = merge_row_fields (row_fields row1) (row_fields row2) in
if row_closed row1 <> row_closed row2 then begin
raise_for Equality
(Variant (Openness (if row_closed row2 then First else Second)))
end;
if not (row_closed row1) then begin
match r1, r2 with
| _::_, _ -> raise_for Equality (Variant (No_tags (Second, r1)))
| _, _::_ -> raise_for Equality (Variant (No_tags (First, r2)))
| _, _ -> ()
end;
begin
match filter_row_fields false r1 with
| [] -> ();
| _ :: _ as r1 -> raise_for Equality (Variant (No_tags (Second, r1)))
end;
begin
match filter_row_fields false r2 with
| [] -> ()
| _ :: _ as r2 -> raise_for Equality (Variant (No_tags (First, r2)))
end;
if not (static_row row1) then
eqtype rename type_pairs subst env (row_more row1) (row_more row2);
List.iter
(fun (l,f1,f2) ->
if f1 == f2 then () else
match row_field_repr f1, row_field_repr f2 with
| Rpresent(Some t1), Rpresent(Some t2) -> begin
try
eqtype rename type_pairs subst env t1 t2
with Equality_trace trace ->
raise_trace_for Equality
(Variant (Incompatible_types_for l) :: trace)
end
| Rpresent None, Rpresent None -> ()
| Reither(c1, [], _), Reither(c2, [], _) when c1 = c2 -> ()
| Reither(c1, t1::tl1, _), Reither(c2, t2::tl2, _)
when c1 = c2 -> begin
try
eqtype rename type_pairs subst env t1 t2;
if List.length tl1 = List.length tl2 then
List.iter2 (eqtype rename type_pairs subst env) tl1 tl2
else begin
List.iter (eqtype rename type_pairs subst env t1) tl2;
List.iter
(fun t1 -> eqtype rename type_pairs subst env t1 t2) tl1
end
with Equality_trace trace ->
raise_trace_for Equality
(Variant (Incompatible_types_for l) :: trace)
end
| Rabsent, Rabsent -> ()
| Rpresent (Some _), Rpresent None
| Rpresent None, Rpresent (Some _)
| Reither _, Reither _ ->
raise_for Equality (Variant (Incompatible_types_for l))
| Reither _, Rpresent _ ->
raise_for Equality
(Variant (Presence_not_guaranteed_for (First, l)))
| Rpresent _, Reither _ ->
raise_for Equality
(Variant (Presence_not_guaranteed_for (Second, l)))
| Rabsent, (Rpresent _ | Reither _) ->
raise_for Equality (Variant (No_tags (First, [l, f2])))
| (Rpresent _ | Reither _), Rabsent ->
raise_for Equality (Variant (No_tags (Second, [l, f1]))))
pairs
and eqtype_alloc_mode m1 m2 =
unify_alloc_mode_for Equality m1 m2
let eqtype_list_same_length
rename type_pairs subst env tl1 tl2 ~do_jkind_check =
Misc.protect_refs [R (univar_pairs, [])] begin fun () ->
let snap = Btype.snapshot () in
Misc.try_finally
~always:(fun () -> backtrack snap)
(fun () -> eqtype_list_same_length rename type_pairs subst env
tl1 tl2 ~do_jkind_check)
end
let eqtype rename type_pairs subst env t1 t2 =
eqtype_list ~do_jkind_check:true rename type_pairs subst env [t1] [t2]
let equal ?(do_jkind_check = true) env rename tyl1 tyl2 =
if List.length tyl1 <> List.length tyl2 then
raise_unexplained_for Equality;
if List.for_all2 eq_type tyl1 tyl2 then () else
let subst = ref [] in
try eqtype_list_same_length ~do_jkind_check rename (TypePairs.create 11)
subst env tyl1 tyl2
with Equality_trace trace ->
raise (Equality (expand_to_equality_error env trace !subst))
let is_equal env rename tyl1 tyl2 =
match equal env rename tyl1 tyl2 with
| () -> true
| exception Equality _ -> false
let rec equal_private env ty1 ty2 =
try
equal env false [ty1] [ty2]
with
| Equality _ as err ->
match try_expand_safe_opt env (expand_head env ty1) with
| ty1' -> equal_private env ty1' ty2
| exception Cannot_expand -> raise err
type class_match_failure =
CM_Virtual_class
| CM_Parameter_arity_mismatch of int * int
| CM_Type_parameter_mismatch of int * Env.t * equality_error
| CM_Class_type_mismatch of Env.t * class_type * class_type
| CM_Parameter_mismatch of int * Env.t * moregen_error
| CM_Val_type_mismatch of string * Env.t * comparison_error
| CM_Meth_type_mismatch of string * Env.t * comparison_error
| CM_Non_mutable_value of string
| CM_Non_concrete_value of string
| CM_Missing_value of string
| CM_Missing_method of string
| CM_Hide_public of string
| CM_Hide_virtual of string * string
| CM_Public_method of string
| CM_Private_method of string
| CM_Virtual_method of string
exception Failure of class_match_failure list
let match_class_sig_shape ~strict sign1 sign2 =
let errors =
Meths.fold
(fun lab (priv, vr, _) err ->
match Meths.find lab sign1.csig_meths with
| exception Not_found -> CM_Missing_method lab::err
| (priv', vr', _) ->
match priv', priv with
| Mpublic, Mprivate _ -> CM_Public_method lab::err
| Mprivate _, Mpublic when strict -> CM_Private_method lab::err
| _, _ ->
match vr', vr with
| Virtual, Concrete -> CM_Virtual_method lab::err
| _, _ -> err)
sign2.csig_meths []
in
let errors =
Meths.fold
(fun lab (priv, vr, _) err ->
if Meths.mem lab sign2.csig_meths then err
else begin
let err =
match priv with
| Mpublic -> CM_Hide_public lab :: err
| Mprivate _ -> err
in
match vr with
| Virtual -> CM_Hide_virtual ("method", lab) :: err
| Concrete -> err
end)
sign1.csig_meths errors
in
let errors =
Vars.fold
(fun lab ((mut:Asttypes.mutable_flag), vr, _) err ->
match Vars.find lab sign1.csig_vars with
| exception Not_found -> CM_Missing_value lab::err
| ((mut':Asttypes.mutable_flag), vr', _) ->
match mut', mut with
| Immutable, Mutable -> CM_Non_mutable_value lab::err
| _, _ ->
match vr', vr with
| Virtual, Concrete -> CM_Non_concrete_value lab::err
| _, _ -> err)
sign2.csig_vars errors
in
Vars.fold
(fun lab (_,vr,_) err ->
if vr = Virtual && not (Vars.mem lab sign2.csig_vars) then
CM_Hide_virtual ("instance variable", lab) :: err
else err)
sign1.csig_vars errors
let rec moregen_clty ~arrow_index trace type_pairs env cty1 cty2 =
try
match cty1, cty2 with
| Cty_constr (_, _, cty1), _ ->
moregen_clty ~arrow_index true type_pairs env cty1 cty2
| _, Cty_constr (_, _, cty2) ->
moregen_clty ~arrow_index true type_pairs env cty1 cty2
| Cty_arrow (l1, ty1, cty1'), Cty_arrow (l2, ty2, cty2') when l1 = l2 ->
let arrow_index = arrow_index + 1 in
begin
try moregen true Covariant type_pairs env ty1 ty2 with Moregen_trace trace ->
raise (Failure [
CM_Parameter_mismatch
(arrow_index, env, expand_to_moregen_error env trace)])
end;
moregen_clty ~arrow_index false type_pairs env cty1' cty2'
| Cty_signature sign1, Cty_signature sign2 ->
Meths.iter
(fun lab (_, _, ty) ->
match Meths.find lab sign1.csig_meths with
| exception Not_found ->
assert false
| (_, _, ty') ->
match moregen true Covariant type_pairs env ty' ty with
| () -> ()
| exception Moregen_trace trace ->
raise (Failure [
CM_Meth_type_mismatch
(lab,
env,
Moregen_error
(expand_to_moregen_error env trace))]))
sign2.csig_meths;
Vars.iter
(fun lab (_, _, ty) ->
match Vars.find lab sign1.csig_vars with
| exception Not_found ->
assert false
| (_, _, ty') ->
match moregen true Covariant type_pairs env ty' ty with
| () -> ()
| exception Moregen_trace trace ->
raise (Failure [
CM_Val_type_mismatch
(lab,
env,
Moregen_error
(expand_to_moregen_error env trace))]))
sign2.csig_vars
| _ ->
raise (Failure [])
with
Failure error when trace || error = [] ->
raise (Failure (CM_Class_type_mismatch (env, cty1, cty2)::error))
let moregen_clty trace type_pairs env cty1 cty2 =
moregen_clty ~arrow_index:0 trace type_pairs env cty1 cty2
let match_class_types ?(trace=true) env pat_sch subj_sch =
let sign1 = signature_of_class_type pat_sch in
let sign2 = signature_of_class_type subj_sch in
let errors = match_class_sig_shape ~strict:false sign1 sign2 in
match errors with
| [] ->
let old_level = !current_level in
current_level := generic_level - 1;
let (_, subj_inst) = instance_class [] subj_sch in
let subj = duplicate_class_type subj_inst in
current_level := generic_level;
let (_, patt) = instance_class [] pat_sch in
let type_pairs = fresh_moregen_pairs () in
let sign1 = signature_of_class_type patt in
let sign2 = signature_of_class_type subj in
let self1 = sign1.csig_self in
let self2 = sign2.csig_self in
let row1 = sign1.csig_self_row in
let row2 = sign2.csig_self_row in
TypePairs.add type_pairs.invariant_pairs (self1, self2);
moregen true Covariant type_pairs env row1 row2;
let res =
match moregen_clty trace type_pairs env patt subj with
| () -> []
| exception Failure res ->
current_level := generic_level - 2;
generalize_class_type subj_inst;
res
in
current_level := old_level;
res
| errors ->
CM_Class_type_mismatch (env, pat_sch, subj_sch) :: errors
let equal_clsig trace type_pairs subst env sign1 sign2 =
try
Meths.iter
(fun lab (_, _, ty) ->
match Meths.find lab sign1.csig_meths with
| exception Not_found ->
assert false
| (_, _, ty') ->
match eqtype true type_pairs subst env ty' ty with
| () -> ()
| exception Equality_trace trace ->
raise (Failure [
CM_Meth_type_mismatch
(lab,
env,
Equality_error
(expand_to_equality_error env trace !subst))]))
sign2.csig_meths;
Vars.iter
(fun lab (_, _, ty) ->
match Vars.find lab sign1.csig_vars with
| exception Not_found ->
assert false
| (_, _, ty') ->
match eqtype true type_pairs subst env ty' ty with
| () -> ()
| exception Equality_trace trace ->
raise (Failure [
CM_Val_type_mismatch
(lab,
env,
Equality_error
(expand_to_equality_error env trace !subst))]))
sign2.csig_vars
with
Failure error when trace ->
raise (Failure (CM_Class_type_mismatch
(env, Cty_signature sign1, Cty_signature sign2)::error))
let match_class_declarations env patt_params patt_type subj_params subj_type =
let sign1 = signature_of_class_type patt_type in
let sign2 = signature_of_class_type subj_type in
let errors = match_class_sig_shape ~strict:true sign1 sign2 in
match errors with
| [] -> begin
try
let subst = ref [] in
let type_pairs = TypePairs.create 53 in
let self1 = sign1.csig_self in
let self2 = sign2.csig_self in
let row1 = sign1.csig_self_row in
let row2 = sign2.csig_self_row in
TypePairs.add type_pairs (self1, self2);
eqtype true type_pairs subst env row1 row2;
let lp = List.length patt_params in
let ls = List.length subj_params in
if lp <> ls then
raise (Failure [CM_Parameter_arity_mismatch (lp, ls)]);
Stdlib.List.iteri2 (fun n p s ->
try eqtype true type_pairs subst env p s with Equality_trace trace ->
raise (Failure
[CM_Type_parameter_mismatch
(n+1, env, expand_to_equality_error env trace !subst)]))
patt_params subj_params;
equal_clsig false type_pairs subst env sign1 sign2;
let clty_params =
List.fold_right (fun ty cty -> Cty_arrow (Labelled "*",ty,cty)) in
match_class_types ~trace:false env
(clty_params patt_params patt_type)
(clty_params subj_params subj_type)
with Failure r -> r
end
| error ->
error
let warn = ref false
let pred_expand n = if n mod 2 = 0 && n > 0 then pred n else n
let pred_enlarge n = if n mod 2 = 1 then pred n else n
type change = Unchanged | Equiv | Changed
let max_change c1 c2 =
match c1, c2 with
| _, Changed | Changed, _ -> Changed
| Equiv, _ | _, Equiv -> Equiv
| _ -> Unchanged
let collect l = List.fold_left (fun c1 (_, c2) -> max_change c1 c2) Unchanged l
let rec filter_visited = function
[] -> []
| {desc=Tobject _|Tvariant _} :: _ as l -> l
| _ :: l -> filter_visited l
let memq_warn t visited =
if List.memq t visited then (warn := true; true) else false
let find_cltype_for_path env p =
let cl_abbr = Env.find_hash_type p env in
match cl_abbr.type_manifest with
Some ty ->
begin match get_desc ty with
Tobject(_,{contents=Some(p',_)}) when Path.same p p' -> cl_abbr, ty
| _ -> raise Not_found
end
| None -> assert false
let has_constr_row' env t =
has_constr_row (expand_abbrev env t)
let build_submode_pos m =
let m', changed = Alloc.newvar_below m in
let c = if changed then Changed else Unchanged in
m', c
let build_submode_neg m =
let m', changed = Alloc.newvar_above m in
let c = if changed then Changed else Unchanged in
m', c
let build_submode posi m =
if posi then build_submode_pos (Alloc.allow_left m)
else build_submode_neg (Alloc.allow_right m)
let rec build_subtype env (visited : transient_expr list)
(loops : (int * type_expr) list) posi level t =
match get_desc t with
Tvar _ ->
if posi then
try
let t' = List.assq (get_id t) loops in
warn := true;
(t', Equiv)
with Not_found ->
(t, Unchanged)
else
(t, Unchanged)
| Tarrow((l,a,r), t1, t2, _) ->
let tt = Transient_expr.repr t in
if memq_warn tt visited then (t, Unchanged) else
let visited = tt :: visited in
let (t1', c1) = build_subtype env visited loops (not posi) level t1 in
let (t2', c2) = build_subtype env visited loops posi level t2 in
let (a', c3) =
if level > 2 then begin
let t1 = if posi then t1 else t1' in
let posi_arg = not posi in
if posi_arg then begin
let a = cross_right_alloc env t1 a in
build_submode_pos a
end else begin
let a = cross_left_alloc env t1 a in
build_submode_neg a
end
end else a, Unchanged
in
let (r', c4) =
if level > 2 then build_submode posi r else r, Unchanged
in
let c = max_change c1 (max_change c2 (max_change c3 c4)) in
if c > Unchanged
then (newty (Tarrow((l,a',r'), t1', t2', commu_ok)), c)
else (t, Unchanged)
| Ttuple labeled_tlist ->
build_subtype_tuple env visited loops posi level t labeled_tlist
(fun x -> Ttuple x)
| Tunboxed_tuple labeled_tlist ->
build_subtype_tuple env visited loops posi level t labeled_tlist
(fun x -> Tunboxed_tuple x)
| Tconstr(p, tl, abbrev)
when level > 0 && generic_abbrev env p && safe_abbrev env t
&& not (has_constr_row' env t) ->
let t' = expand_abbrev env t in
let level' = pred_expand level in
begin try match get_desc t' with
Tobject _ when posi && not (opened_object t') ->
let cl_abbr, body = find_cltype_for_path env p in
let ty =
try
subst env !current_level Public abbrev None
cl_abbr.type_params tl body
with Cannot_subst -> assert false in
let ty1, tl1 =
match get_desc ty with
Tobject(ty1,{contents=Some(p',tl1)}) when Path.same p p' ->
ty1, tl1
| _ -> raise Not_found
in
if deep_occur_list ty tl1 then raise Not_found;
set_type_desc ty
(Tvar { name = None;
jkind = Jkind.Builtin.value
~why:(Unknown "build subtype 1")});
let t'' = newvar (Jkind.Builtin.value ~why:(Unknown "build subtype 2"))
in
let loops = (get_id ty, t'') :: loops in
let (ty1', c) =
build_subtype env [Transient_expr.repr t']
loops posi (pred_enlarge level') ty1 in
assert (is_Tvar t'');
let nm =
if c > Equiv || deep_occur ty ty1' then None else Some(p,tl1) in
set_type_desc t'' (Tobject (ty1', ref nm));
(try unify_var env ty t with Unify _ -> assert false);
( t'', Changed)
| _ -> raise Not_found
with Not_found ->
let (t'',c) =
build_subtype env visited loops posi level' t' in
if c > Unchanged then (t'',c)
else (t, Unchanged)
end
| Tconstr(p, tl, _abbrev) ->
let tt = Transient_expr.repr t in
if memq_warn tt visited then (t, Unchanged) else
let visited = tt :: visited in
begin try
let decl = Env.find_type p env in
if level = 0 && generic_abbrev env p && safe_abbrev env t
&& not (has_constr_row' env t)
then warn := true;
let tl' =
List.map2
(fun v t ->
let (co,cn) = Variance.get_upper v in
if cn then
if co then (t, Unchanged)
else build_subtype env visited loops (not posi) level t
else
if co then build_subtype env visited loops posi level t
else (newvar (Jkind.Builtin.value
~why:(Unknown "build_subtype 3")),
Changed))
decl.type_variance tl
in
let c = collect tl' in
if c > Unchanged then (newconstr p (List.map fst tl'), c)
else (t, Unchanged)
with Not_found ->
(t, Unchanged)
end
| Tvariant row ->
let tt = Transient_expr.repr t in
if memq_warn tt visited || not (static_row row) then (t, Unchanged) else
let level' = pred_enlarge level in
let visited =
tt :: if level' < level then [] else filter_visited visited in
let fields = filter_row_fields false (row_fields row) in
let fields =
List.map
(fun (l,f as orig) -> match row_field_repr f with
Rpresent None ->
if posi then
(l, rf_either_of None), Unchanged
else
orig, Unchanged
| Rpresent(Some t) ->
let (t', c) = build_subtype env visited loops posi level' t in
let f =
if posi && level > 0
then rf_either_of (Some t')
else rf_present (Some t')
in (l, f), c
| _ -> assert false)
fields
in
let c = collect fields in
let row =
create_row ~fields:(List.map fst fields)
~more:(newvar (Jkind.Builtin.value ~why:Row_variable))
~closed:posi ~fixed:None
~name:(if c > Unchanged then None else row_name row)
in
(newty (Tvariant row), Changed)
| Tobject (t1, _) ->
let tt = Transient_expr.repr t in
if memq_warn tt visited || opened_object t1 then (t, Unchanged) else
let level' = pred_enlarge level in
let visited =
tt :: if level' < level then [] else filter_visited visited in
let (t1', c) = build_subtype env visited loops posi level' t1 in
if c > Unchanged then (newty (Tobject (t1', ref None)), c)
else (t, Unchanged)
| Tfield(s, _, t1, t2) ->
let (t1', c1) = build_subtype env visited loops posi level t1 in
let (t2', c2) = build_subtype env visited loops posi level t2 in
let c = max_change c1 c2 in
if c > Unchanged then (newty (Tfield(s, field_public, t1', t2')), c)
else (t, Unchanged)
| Tquote t1 ->
let (t1', c) =
build_subtype (incr_stage env) visited loops posi level t1
in
if c > Unchanged then (newty (Tquote t1'), c)
else (t, Unchanged)
| Tsplice t1 ->
let (t1', c) =
build_subtype (decr_stage env) visited loops posi level t1
in
if c > Unchanged then (newty (Tsplice t1'), c)
else (t, Unchanged)
| Tquote_eval t1 ->
let (t1', c) =
build_subtype (incr_stage env) visited loops posi level t1
in
if c > Unchanged then (newty (Tquote_eval t1'), c)
else (t, Unchanged)
| Tnil ->
if posi then
let v = newvar (Jkind.Builtin.value ~why:Tnil) in
(v, Changed)
else begin
warn := true;
(t, Unchanged)
end
| Tsubst _ | Tlink _ ->
assert false
| Tpoly(t1, tl) ->
let (t1', c) = build_subtype env visited loops posi level t1 in
if c > Unchanged then (newty (Tpoly(t1', tl)), c)
else (t, Unchanged)
| Trepr(t1, tl) ->
let (t1', c) = build_subtype env visited loops posi level t1 in
if c > Unchanged then (newty (Trepr(t1', tl)), c)
else (t, Unchanged)
| Tunivar _ | Tpackage _ | Tof_kind _ -> (t, Unchanged)
and build_subtype_tuple env visited loops posi level t labeled_tlist
constructor =
let tt = Transient_expr.repr t in
if memq_warn tt visited then (t, Unchanged) else
let visited = tt :: visited in
let labels, tlist = List.split labeled_tlist in
let tlist' =
List.map (build_subtype env visited loops posi level) tlist
in
let c = collect tlist' in
if c > Unchanged then
(newty (constructor (List.combine labels (List.map fst tlist'))), c)
else (t, Unchanged)
let enlarge_type env ty =
warn := false;
let (ty', _) = build_subtype env [] [] true 4 ty in
(ty', !warn)
let subtypes = TypePairs.create 17
let subtype_error ~env ~trace ~unification_trace =
raise (Subtype (Subtype.error
~trace:(expand_subtype_trace env (List.rev trace))
~unification_trace))
let subtype_alloc_mode env trace a1 a2 =
match Alloc.submode a1 a2 with
| Ok () -> ()
| Error _ -> subtype_error ~env ~trace ~unification_trace:[]
let rec subtype_rec env trace t1 t2 cstrs =
if eq_type t1 t2 then cstrs else
if TypePairs.mem subtypes (t1, t2) then
cstrs
else begin
TypePairs.add subtypes (t1, t2);
match (get_desc t1, get_desc t2) with
(Tvar _, _) | (_, Tvar _) ->
(trace, t1, t2, !univar_pairs)::cstrs
| (Tarrow((l1,a1,r1), t1, u1, _),
Tarrow((l2,a2,r2), t2, u2, _)) when l1 = l2
|| !Clflags.classic && equivalent_with_nolabels l1 l2 ->
let cstrs =
subtype_rec
env
(Subtype.Diff {got = t2; expected = t1} :: trace)
t2 t1
cstrs
in
let a2 = cross_left_alloc env t2 a2 in
subtype_alloc_mode env trace a2 a1;
subtype_alloc_mode env trace r1 r2;
subtype_rec
env
(Subtype.Diff {got = u1; expected = u2} :: trace)
u1 u2
cstrs
| (Ttuple tl1, Ttuple tl2) ->
subtype_labeled_list env trace tl1 tl2 cstrs
| (Tunboxed_tuple tl1, Tunboxed_tuple tl2) ->
subtype_labeled_list env trace tl1 tl2 cstrs
| (Tconstr(p1, [], _), Tconstr(p2, [], _)) when Path.same p1 p2 ->
cstrs
| (Tconstr(p1, _tl1, _abbrev1), _)
when generic_abbrev env p1 && safe_abbrev env t1 ->
subtype_rec env trace (expand_abbrev env t1) t2 cstrs
| (_, Tconstr(p2, _tl2, _abbrev2))
when generic_abbrev env p2 && safe_abbrev env t2 ->
subtype_rec env trace t1 (expand_abbrev env t2) cstrs
| (Tconstr(p1, tl1, _), Tconstr(p2, tl2, _)) when Path.same p1 p2 ->
begin try
let decl = Env.find_type p1 env in
List.fold_left2
(fun cstrs v (t1, t2) ->
let (co, cn) = Variance.get_upper v in
if co then
if cn then
(trace, newty2 ~level:(get_level t1) (Ttuple[None, t1]),
newty2 ~level:(get_level t2) (Ttuple[None, t2]), !univar_pairs)
:: cstrs
else
subtype_rec
env
(Subtype.Diff {got = t1; expected = t2} :: trace)
t1 t2
cstrs
else
if cn
then
subtype_rec
env
(Subtype.Diff {got = t2; expected = t1} :: trace)
t2 t1
cstrs
else cstrs)
cstrs decl.type_variance (List.combine tl1 tl2)
with Not_found ->
(trace, t1, t2, !univar_pairs)::cstrs
end
| (Tconstr(p1, _, _), _)
when generic_private_abbrev env p1 && safe_abbrev_opt env t1 ->
subtype_rec env trace (expand_abbrev_opt env t1) t2 cstrs
| (Tobject (f1, _), Tobject (f2, _))
when is_Tvar (object_row f1) && is_Tvar (object_row f2) ->
(trace, t1, t2, !univar_pairs)::cstrs
| (Tobject (f1, _), Tobject (f2, _)) ->
subtype_fields env trace f1 f2 cstrs
| (Tvariant row1, Tvariant row2) ->
begin try
subtype_row env trace row1 row2 cstrs
with Exit ->
(trace, t1, t2, !univar_pairs)::cstrs
end
| (Tpoly (u1, []), Tpoly (u2, [])) ->
subtype_rec env trace u1 u2 cstrs
| (Tpoly (u1, tl1), Tpoly (u2, [])) ->
let u1' = instance_poly tl1 u1 in
subtype_rec env trace u1' u2 cstrs
| (Tpoly (u1, tl1), Tpoly (u2,tl2)) ->
begin try
enter_poly env univar_pairs u1 tl1 u2 tl2
(fun t1 t2 -> subtype_rec env trace t1 t2 cstrs)
with Escape _ ->
(trace, t1, t2, !univar_pairs)::cstrs
end
| (Trepr (u1, sort_vars1), Trepr (u2, sort_vars2)) ->
(try
let pairs = List.combine sort_vars1 sort_vars2 in
Jkind_types.Sort.enter_repr pairs
(fun () -> subtype_rec env trace u1 u2 cstrs)
with Invalid_argument _ -> (trace, t1, t2, !univar_pairs)::cstrs)
| (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
begin try
let ntl1 =
complete_type_list env fl2 (get_level t1) (Mty_ident p1) fl1
and ntl2 =
complete_type_list env fl1 (get_level t2) (Mty_ident p2) fl2
~allow_absent:true in
let cstrs' =
List.map
(fun (n2,t2) -> (trace, List.assoc n2 ntl1, t2, !univar_pairs))
ntl2
in
if eq_package_path env p1 p2 then cstrs' @ cstrs
else begin
let snap = Btype.snapshot () in
match List.iter (fun (_, t1, t2, _) -> unify env t1 t2) cstrs' with
| () when !package_subtype env p1 fl1 p2 fl2 ->
Btype.backtrack snap; cstrs' @ cstrs
| () | exception Unify _ ->
Btype.backtrack snap; raise Not_found
end
with Not_found ->
(trace, t1, t2, !univar_pairs)::cstrs
end
| (Tquote t1, Tquote t2) ->
subtype_rec (incr_stage env) trace t1 t2 cstrs
| (Tsplice t1, Tsplice t2) ->
subtype_rec (decr_stage env) trace t1 t2 cstrs
| (Tquote_eval t1, Tquote_eval t2) ->
subtype_rec (incr_stage env) trace t1 t2 cstrs
| (_, _) ->
(trace, t1, t2, !univar_pairs)::cstrs
end
and subtype_labeled_list env trace labeled_tl1 labeled_tl2 cstrs =
if not (Int.equal (List.length labeled_tl1) (List.length labeled_tl2)) then
subtype_error ~env ~trace ~unification_trace:[];
List.fold_left2
(fun cstrs (label1, ty1) (label2, ty2) ->
if not (Option.equal String.equal label1 label2) then
subtype_error ~env ~trace ~unification_trace:[];
subtype_rec
env
(Subtype.Diff { got = ty1; expected = ty2 } :: trace)
ty1 ty2
cstrs)
cstrs labeled_tl1 labeled_tl2
and subtype_fields env trace ty1 ty2 cstrs =
let (fields1, rest1) = flatten_fields ty1 in
let (fields2, rest2) = flatten_fields ty2 in
let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
let cstrs =
if get_desc rest2 = Tnil then cstrs else
if miss1 = [] then
subtype_rec
env
(Subtype.Diff {got = rest1; expected = rest2} :: trace)
rest1 rest2
cstrs
else
(trace, build_fields (get_level ty1) miss1 rest1, rest2,
!univar_pairs) :: cstrs
in
let cstrs =
if miss2 = [] then cstrs else
(trace, rest1, build_fields (get_level ty2) miss2
(newvar (Jkind.Builtin.value ~why:Object_field)),
!univar_pairs) :: cstrs
in
List.fold_left
(fun cstrs (_, _k1, t1, _k2, t2) ->
subtype_rec
env
(Subtype.Diff {got = t1; expected = t2} :: trace)
t1 t2
cstrs)
cstrs pairs
and subtype_row env trace row1 row2 cstrs =
let Row {fields = row1_fields; more = more1; closed = row1_closed} =
row_repr row1 in
let Row {fields = row2_fields; more = more2; closed = row2_closed} =
row_repr row2 in
let r1, r2, pairs =
merge_row_fields row1_fields row2_fields in
let r1 = if row2_closed then filter_row_fields false r1 else r1 in
let r2 = if row1_closed then filter_row_fields false r2 else r2 in
match get_desc more1, get_desc more2 with
Tconstr(p1,_,_), Tconstr(p2,_,_) when Path.same p1 p2 ->
subtype_rec
env
(Subtype.Diff {got = more1; expected = more2} :: trace)
more1 more2
cstrs
| (Tvar _|Tconstr _|Tnil), (Tvar _|Tconstr _|Tnil)
when row1_closed && r1 = [] ->
List.fold_left
(fun cstrs (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
(Rpresent None|Reither(true,_,_)), Rpresent None ->
cstrs
| Rpresent(Some t1), Rpresent(Some t2) ->
subtype_rec
env
(Subtype.Diff {got = t1; expected = t2} :: trace)
t1 t2
cstrs
| Reither(false, t1::_, _), Rpresent(Some t2) ->
subtype_rec
env
(Subtype.Diff {got = t1; expected = t2} :: trace)
t1 t2
cstrs
| Rabsent, _ -> cstrs
| _ -> raise Exit)
cstrs pairs
| Tunivar _, Tunivar _
when row1_closed = row2_closed && r1 = [] && r2 = [] ->
let cstrs =
subtype_rec
env
(Subtype.Diff {got = more1; expected = more2} :: trace)
more1 more2
cstrs
in
List.fold_left
(fun cstrs (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
Rpresent None, Rpresent None
| Reither(true,[],_), Reither(true,[],_)
| Rabsent, Rabsent ->
cstrs
| Rpresent(Some t1), Rpresent(Some t2)
| Reither(false,[t1],_), Reither(false,[t2],_) ->
subtype_rec
env
(Subtype.Diff {got = t1; expected = t2} :: trace)
t1 t2
cstrs
| _ -> raise Exit)
cstrs pairs
| _ ->
raise Exit
let subtype env ty1 ty2 =
TypePairs.clear subtypes;
Misc.protect_refs [R (univar_pairs, [])] begin fun () ->
let cstrs =
subtype_rec env [Subtype.Diff {got = ty1; expected = ty2}] ty1 ty2 []
in
TypePairs.clear subtypes;
function () ->
List.iter
(function (trace0, t1, t2, pairs) ->
try unify_pairs env t1 t2 pairs with Unify {trace} ->
subtype_error ~env ~trace:trace0 ~unification_trace:(List.tl trace))
(List.rev cstrs)
end
let rec unalias_object ty =
let level = get_level ty in
match get_desc ty with
Tfield (s, k, t1, t2) ->
newty2 ~level (Tfield (s, k, t1, unalias_object t2))
| Tvar _ | Tnil as desc ->
newty2 ~level desc
| Tunivar _ ->
ty
| Tconstr _ ->
newvar2 level (Jkind.Builtin.any ~why:Dummy_jkind)
| _ ->
assert false
let unalias ty =
let level = get_level ty in
match get_desc ty with
Tvar _ | Tunivar _ ->
ty
| Tvariant row ->
let Row {fields; more; name; fixed; closed} = row_repr row in
newty2 ~level
(Tvariant
(create_row ~fields ~name ~fixed ~closed ~more:
(newty2 ~level:(get_level more) (get_desc more))))
| Tobject (ty, nm) ->
newty2 ~level (Tobject (unalias_object ty, nm))
| desc ->
newty2 ~level desc
let rec arity ty =
match get_desc ty with
Tarrow(_, _t1, t2, _) -> 1 + arity t2
| _ -> 0
let add_nongen_vars_in_schema =
let rec loop env ((visited, weak_set) as acc) ty =
if TypeSet.mem ty visited
then acc
else begin
let visited = TypeSet.add ty visited in
match get_desc ty with
| Tvar _ when get_level ty <> generic_level ->
visited, TypeSet.add ty weak_set
| Tconstr _ ->
let (_, unexpanded_candidate) as unexpanded_candidate' =
fold_type_expr
(loop env)
(visited, weak_set)
ty
in
if unexpanded_candidate == weak_set
then (visited, weak_set)
else begin
match
loop env (visited, weak_set)
(try_expand_head try_expand_safe env ty)
with
| exception Cannot_expand -> unexpanded_candidate'
| expanded_result -> expanded_result
end
| Tfield(_, kind, t1, t2) ->
let visited, weak_set =
match field_kind_repr kind with
| Fpublic -> loop env (visited, weak_set) t1
| _ -> visited, weak_set
in
loop env (visited, weak_set) t2
| Tvariant row ->
let visited, weak_set =
fold_row (loop env) (visited, weak_set) row
in
if not (static_row row)
then loop env (visited, weak_set) (row_more row)
else (visited, weak_set)
| _ ->
fold_type_expr (loop env) (visited, weak_set) ty
end
in
fun env acc ty ->
remove_mode_and_jkind_variables ty;
let _, result = loop env (TypeSet.empty, acc) ty in
result
let nongen_vars_in_schema env ty =
let result = add_nongen_vars_in_schema env TypeSet.empty ty in
if TypeSet.is_empty result
then None
else Some result
let nongen_class_type =
let add_nongen_vars_in_schema' ty weak_set =
add_nongen_vars_in_schema Env.empty weak_set ty
in
let add_nongen_vars_in_schema_fold fold m weak_set =
let f _key (_,_,ty) weak_set =
add_nongen_vars_in_schema Env.empty weak_set ty
in
fold f m weak_set
in
let rec nongen_class_type cty weak_set =
match cty with
| Cty_constr (_, params, _) ->
List.fold_left
(add_nongen_vars_in_schema Env.empty)
weak_set
params
| Cty_signature sign ->
weak_set
|> add_nongen_vars_in_schema' sign.csig_self
|> add_nongen_vars_in_schema' sign.csig_self_row
|> add_nongen_vars_in_schema_fold Meths.fold sign.csig_meths
|> add_nongen_vars_in_schema_fold Vars.fold sign.csig_vars
| Cty_arrow (_, ty, cty) ->
add_nongen_vars_in_schema' ty weak_set
|> nongen_class_type cty
in
nongen_class_type
let nongen_class_declaration cty =
List.fold_left
(add_nongen_vars_in_schema Env.empty)
TypeSet.empty
cty.cty_params
|> nongen_class_type cty.cty_type
let nongen_vars_in_class_declaration cty =
let result = nongen_class_declaration cty in
if TypeSet.is_empty result
then None
else Some result
let rec normalize_type_rec mark ty =
if try_mark_node mark ty then begin
let tm = row_of_type ty in
begin if not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm then
match get_desc tm with
Tconstr (Path.Pdot(m,i), tl, _abbrev) ->
let i' = String.sub i 0 (String.length i - 4) in
set_type_desc ty (Tconstr(Path.Pdot(m,i'), tl, ref Mnil))
| _ -> assert false
else match get_desc ty with
| Tvariant row ->
let Row {fields = orig_fields; more; name; fixed; closed} =
row_repr row in
let fields = List.map
(fun (l,f) ->
l,
match row_field_repr f with Reither(b, ty::(_::_ as tyl), m) ->
let tyl' =
List.fold_left
(fun tyl ty ->
let eq ty' =
is_equal (Env.enter_future Env.empty) false [ty] [ty']
in
if List.exists eq tyl
then tyl
else ty::tyl)
[ty] tyl
in
if List.length tyl' <= List.length tyl then
rf_either (List.rev tyl') ~use_ext_of:f ~no_arg:b ~matched:m
else f
| _ -> f)
orig_fields in
let fields =
List.sort (fun (p,_) (q,_) -> compare p q)
(List.filter (fun (_,fi) -> row_field_repr fi <> Rabsent) fields) in
set_type_desc ty (Tvariant
(create_row ~fields ~more ~name ~fixed ~closed))
| Tobject (fi, nm) ->
begin match !nm with
| None -> ()
| Some (n, v :: l) ->
if deep_occur_list ty l then
set_name nm None
else
begin match get_desc v with
| Tvar _ | Tunivar _ -> ()
| Tnil -> set_type_desc ty (Tconstr (n, l, ref Mnil))
| _ -> set_name nm None
end
| _ ->
fatal_error "Ctype.normalize_type_rec"
end;
let level = get_level fi in
if level < lowest_level then () else
let fields, row = flatten_fields fi in
let fi' = build_fields level fields row in
set_type_desc fi (get_desc fi')
| _ -> ()
end;
iter_type_expr (normalize_type_rec mark) ty;
end
let normalize_type ty =
with_type_mark (fun mark -> normalize_type_rec mark ty)
let nondep_hash = TypeHash.create 47
let nondep_variants = TypeHash.create 17
let clear_hash () =
TypeHash.clear nondep_hash; TypeHash.clear nondep_variants
let rec nondep_jkind_desc_base env ids ~desc_of_const jkind_desc =
match jkind_desc.base with
| Kconstr p -> begin
match Path.find_free_opt ids p with
| None -> jkind_desc
| Some id ->
match Jkind.Const.expand_once env jkind_desc with
| None -> raise (Nondep_cannot_erase id)
| Some jkind ->
nondep_jkind_desc_base env ids ~desc_of_const (desc_of_const jkind)
end
| Layout _ ->
jkind_desc
let nondep_jkind_const_desc_base env ids jkind_desc =
nondep_jkind_desc_base env ids ~desc_of_const:(fun x -> x) jkind_desc
let nondep_jkind_desc_base env ids jkind_desc =
nondep_jkind_desc_base env ids
~desc_of_const:Jkind.Base_and_axes.jkind_desc_of_const jkind_desc
let nondep_jkind_base env ids jkind =
let jkind_desc = nondep_jkind_desc_base env ids jkind.jkind in
if jkind_desc == jkind.jkind then jkind else { jkind with jkind = jkind_desc }
let rec nondep_type_rec ?(expand_private=false) env ids ty =
let try_expand env t =
if expand_private then try_expand_safe_opt env t
else try_expand_safe env t
in
match get_desc ty with
Tvar { name; jkind } ->
let jkind' = nondep_jkind_base env ids jkind in
if not (jkind' == jkind) then
set_type_desc ty (Tvar { name; jkind = jkind' });
ty
| Tunivar { name; jkind } ->
let jkind' = nondep_jkind_base env ids jkind in
if not (jkind' == jkind) then
set_type_desc ty (Tvar { name; jkind = jkind' });
ty
| _ -> try TypeHash.find nondep_hash ty
with Not_found ->
let ty' = newgenstub ~scope:(get_scope ty)
(Jkind.Builtin.any ~why:Dummy_jkind) in
TypeHash.add nondep_hash ty ty';
match
match get_desc ty with
| Tconstr(p, tl, _abbrev) as desc ->
begin try
match Path.find_free_opt ids p with
| Some id ->
raise (Nondep_cannot_erase id)
| None ->
Tconstr(p, List.map (nondep_type_rec env ids) tl, ref Mnil)
with (Nondep_cannot_erase _) as exn ->
try Tlink (nondep_type_rec ~expand_private env ids
(try_expand env (newty2 ~level:(get_level ty) desc)))
with Cannot_expand -> raise exn
end
| Tpackage(p, fl) when Path.exists_free ids p ->
let p' = normalize_package_path env p in
begin match Path.find_free_opt ids p' with
| Some id -> raise (Nondep_cannot_erase id)
| None ->
let nondep_field_rec (n, ty) = (n, nondep_type_rec env ids ty) in
Tpackage (p', List.map nondep_field_rec fl)
end
| Tobject (t1, name) ->
Tobject (nondep_type_rec env ids t1,
ref (match !name with
None -> None
| Some (p, tl) ->
if Path.exists_free ids p then None
else Some (p, List.map (nondep_type_rec env ids) tl)))
| Tvariant row ->
let more = row_more row in
begin try
let ty2 = TypeHash.find nondep_variants more in
TypeHash.add nondep_hash ty ty2;
Tlink ty2
with Not_found ->
TypeHash.add nondep_variants more ty';
let static = static_row row in
let more' =
if static then newgenty Tnil else nondep_type_rec env ids more
in
let row =
copy_row (nondep_type_rec env ids) true row true more' in
match row_name row with
Some (p, _tl) when Path.exists_free ids p ->
Tvariant (set_row_name row None)
| _ -> Tvariant row
end
| desc -> copy_type_desc (nondep_type_rec env ids) desc
with
| desc ->
Transient_expr.set_stub_desc ty' desc;
ty'
| exception e ->
TypeHash.remove nondep_hash ty;
raise e
let nondep_type env id ty =
try
let ty' = nondep_type_rec env id ty in
clear_hash ();
ty'
with Nondep_cannot_erase _ as exn ->
clear_hash ();
raise exn
let () = nondep_type' := nondep_type
let rec nondep_type_decl env mid is_covariant decl =
try
let params = List.map (nondep_type_rec env mid) decl.type_params in
let tk =
try map_kind (nondep_type_rec env mid) decl.type_kind
with Nondep_cannot_erase _ when is_covariant -> Type_abstract Definition
and tm, priv =
match decl.type_manifest with
| None -> None, decl.type_private
| Some ty ->
try Some (nondep_type_rec env mid ty), decl.type_private
with Nondep_cannot_erase _ when is_covariant ->
clear_hash ();
try Some (nondep_type_rec ~expand_private:true env mid ty),
Private
with Nondep_cannot_erase _ ->
None, decl.type_private
and jkind =
let jkind = nondep_jkind_base env mid decl.type_jkind in
try Jkind.map_type_expr (nondep_type_rec env mid) jkind
with Nondep_cannot_erase _ as err when is_covariant ->
let context = mk_jkind_context_check_principal env in
match Jkind.round_up ~context env jkind with
| None -> raise err
| Some jkind -> jkind |> Jkind.disallow_right
in
clear_hash ();
let priv =
match tm with
| Some ty when Btype.has_constr_row ty -> Private
| _ -> priv
in
let type_unboxed_version =
Option.map
(nondep_type_decl env mid is_covariant) decl.type_unboxed_version
in
{ type_params = params;
type_arity = decl.type_arity;
type_kind = tk;
type_jkind = jkind;
type_ikind = Types.ikinds_todo "nondep_type_decl";
type_manifest = tm;
type_private = priv;
type_variance = decl.type_variance;
type_separability = decl.type_separability;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = decl.type_loc;
type_attributes = decl.type_attributes;
type_unboxed_default = decl.type_unboxed_default;
type_uid = decl.type_uid;
type_unboxed_version;
}
with Nondep_cannot_erase _ as exn ->
clear_hash ();
raise exn
let nondep_extension_constructor env ids ext =
try
let type_path, type_params =
match Path.find_free_opt ids ext.ext_type_path with
| Some id ->
begin
let ty =
newgenty (Tconstr(ext.ext_type_path, ext.ext_type_params, ref Mnil))
in
let ty' = nondep_type_rec env ids ty in
match get_desc ty' with
Tconstr(p, tl, _) -> p, tl
| _ -> raise (Nondep_cannot_erase id)
end
| None ->
let type_params =
List.map (nondep_type_rec env ids) ext.ext_type_params
in
ext.ext_type_path, type_params
in
let args = map_type_expr_cstr_args (nondep_type_rec env ids) ext.ext_args in
let ret_type = Option.map (nondep_type_rec env ids) ext.ext_ret_type in
clear_hash ();
{ ext_type_path = type_path;
ext_type_params = type_params;
ext_args = args;
ext_shape = ext.ext_shape;
ext_constant = ext.ext_constant;
ext_ret_type = ret_type;
ext_private = ext.ext_private;
ext_attributes = ext.ext_attributes;
ext_loc = ext.ext_loc;
ext_uid = ext.ext_uid;
}
with Nondep_cannot_erase _ as exn ->
clear_hash ();
raise exn
let nondep_class_signature env id sign =
{ csig_self = nondep_type_rec env id sign.csig_self;
csig_self_row = nondep_type_rec env id sign.csig_self_row;
csig_vars =
Vars.map (function (m, v, t) -> (m, v, nondep_type_rec env id t))
sign.csig_vars;
csig_meths =
Meths.map (function (p, v, t) -> (p, v, nondep_type_rec env id t))
sign.csig_meths }
let rec nondep_class_type env ids =
function
Cty_constr (p, _, cty) when Path.exists_free ids p ->
nondep_class_type env ids cty
| Cty_constr (p, tyl, cty) ->
Cty_constr (p, List.map (nondep_type_rec env ids) tyl,
nondep_class_type env ids cty)
| Cty_signature sign ->
Cty_signature (nondep_class_signature env ids sign)
| Cty_arrow (l, ty, cty) ->
Cty_arrow (l, nondep_type_rec env ids ty, nondep_class_type env ids cty)
let nondep_class_declaration env ids decl =
assert (not (Path.exists_free ids decl.cty_path));
let decl =
{ cty_params = List.map (nondep_type_rec env ids) decl.cty_params;
cty_variance = decl.cty_variance;
cty_type = nondep_class_type env ids decl.cty_type;
cty_path = decl.cty_path;
cty_new =
begin match decl.cty_new with
None -> None
| Some ty -> Some (nondep_type_rec env ids ty)
end;
cty_loc = decl.cty_loc;
cty_attributes = decl.cty_attributes;
cty_uid = decl.cty_uid;
}
in
clear_hash ();
decl
let nondep_cltype_declaration env ids decl =
assert (not (Path.exists_free ids decl.clty_path));
let decl =
{ clty_params = List.map (nondep_type_rec env ids) decl.clty_params;
clty_variance = decl.clty_variance;
clty_type = nondep_class_type env ids decl.clty_type;
clty_path = decl.clty_path;
clty_hash_type = nondep_type_decl env ids false decl.clty_hash_type ;
clty_loc = decl.clty_loc;
clty_attributes = decl.clty_attributes;
clty_uid = decl.clty_uid;
}
in
clear_hash ();
decl
let nondep_jkind_declaration env ids decl =
match decl.jkind_manifest with
| None -> decl
| Some jkind ->
let jkind_manifest = nondep_jkind_const_desc_base env ids jkind in
if jkind_manifest == jkind
then decl
else { decl with jkind_manifest = Some jkind_manifest }
let rec collapse_conj env visited ty =
let id = get_id ty in
if List.memq id visited then () else
let visited = id :: visited in
match get_desc ty with
Tvariant row ->
List.iter
(fun (_l,fi) ->
match row_field_repr fi with
Reither (_c, t1::(_::_ as tl), _m) ->
List.iter (unify env t1) tl
| _ ->
())
(row_fields row);
iter_row (collapse_conj env visited) row
| _ ->
iter_type_expr_with_stages (fun env -> collapse_conj env visited) env ty
let collapse_conj_params env params =
List.iter (collapse_conj env []) params
let same_constr env t1 t2 =
let t1 = expand_head env t1 in
let t2 = expand_head env t2 in
match get_desc t1, get_desc t2 with
| Tconstr (p1, _, _), Tconstr (p2, _, _) -> Path.same p1 p2
| _ -> false
let () =
Env.same_constr := same_constr
type global_state =
{ current_level : int ref;
nongen_level : int ref;
global_level : int ref;
}
let global_state : global_state =
{ current_level;
nongen_level;
global_level;
}
let print_global_state fmt global_state =
let print_field fmt s r = Format.fprintf fmt "%s = %d;@;" s !r in
let print_fields fmt { current_level; nongen_level; global_level; } =
print_field fmt "current_level" current_level;
print_field fmt "nongen_level" nongen_level;
print_field fmt "global_level" global_level;
in
Format.fprintf fmt "@[<1>{@;%a}@]" print_fields global_state
let type_equal env ty1 ty2 = is_equal env false [ty1] [ty2]
let () = type_equal' := type_equal
let check_decl_jkind env decl jkind =
let type_equal = type_equal env in
let type_jkind_purely = type_jkind_purely env in
let context = mk_jkind_context_always_principal env in
let decl_jkind = match decl.type_kind, decl.type_manifest with
| Type_abstract _, Some inner_ty ->
Jkind.for_abbreviation ~type_jkind_purely
~modality:Mode.Modality.Const.id inner_ty
| Type_record ([{ ld_type = inner_ty; ld_modalities = modality }],
Record_unboxed, None), _
| Type_record_unboxed_product ([{ ld_type = inner_ty;
ld_modalities = modality }], _, None), _
| Type_variant (
[{ cd_args =
(Cstr_tuple [{ ca_type = inner_ty;
ca_modalities = modality }] |
Cstr_record [{ ld_type = inner_ty;
ld_modalities = modality }]) }],
Variant_unboxed, None), _ ->
Jkind.for_abbreviation ~type_jkind_purely ~modality inner_ty
| _ -> decl.type_jkind
in
match
Ikind.sub_jkind_l
~origin:
(Format.asprintf "ctype:decl %a" Location.print_loc decl.type_loc)
~type_equal ~context env decl_jkind jkind
with
| Ok () -> Ok ()
| Error _ as err ->
match decl.type_manifest with
| None -> err
| Some ty ->
let ty_jkind = type_jkind env ty in
match
Ikind.sub_jkind_l
~origin:
(Format.asprintf "ctype:manifest %a"
Location.print_loc decl.type_loc)
~type_equal ~context env ty_jkind jkind
with
| Ok () -> Ok ()
| Error _ as err -> err
let constrain_decl_jkind env decl jkind =
match Jkind.try_allow_r jkind with
| None ->
check_decl_jkind env decl jkind
| Some jkind ->
let type_equal = type_equal env in
let context = mk_jkind_context_always_principal env in
match
Ikind.sub_or_error ~type_equal ~context env
decl.type_jkind jkind
with
| Ok () as ok -> ok
| Error _ as err ->
match decl.type_manifest with
| None -> err
| Some ty -> constrain_type_jkind env ty jkind
let exn_constructor_crossing env lid ~args locks =
let vmode =
Env.walk_locks ~env ~loc:lid.loc lid.txt ~item:Constructor
None ((Mode.Value.(disallow_right min)), locks)
in
let monadic_mode = vmode.monadic in
let monadic =
[ monadic_mode
|> Mode.Value.Monadic.proj Contention
|> Mode.Value.Monadic.min_with Contention;
monadic_mode
|> Mode.Value.Monadic.proj Visibility
|> Mode.Value.Monadic.min_with Visibility
]
|> Mode.Value.Monadic.join
in
let comonadic_source =
Mode.Value.monadic_to_comonadic_max monadic_mode
in
let comonadic =
[ comonadic_source
|> Mode.Value.Comonadic.proj Portability
|> Mode.Value.Comonadic.max_with Portability;
comonadic_source
|> Mode.Value.Comonadic.proj Statefulness
|> Mode.Value.Comonadic.max_with Statefulness
]
|> Mode.Value.Comonadic.meet
in
let mode_crossing =
List.map (
fun ({ca_type; ca_modalities; _} : Types.constructor_argument) ->
crossing_of_ty env ~modalities:ca_modalities ca_type
) args
|> List.fold_left Mode.Crossing.join Mode.Crossing.min
in
let min_bound =
{ monadic;
comonadic = Mode.Value.Comonadic.(disallow_right min) }
in
let max_bound =
{ comonadic;
monadic = Mode.Value.Monadic.(disallow_left max)}
in
(mode_crossing, min_bound, max_bound)
let check_constructor_crossing ~default_mode ~for_extensible_variant
env lid tag ~res ~args held_locks =
match tag with
| Ordinary _ | Null -> Ok default_mode
| Extension _ ->
match get_desc (expand_head env res) with
| Tconstr (p, _, _) when Path.same Predef.path_exn p ->
let (mode_crossing, min_bound, max_bound) =
exn_constructor_crossing env lid ~args held_locks
in
for_extensible_variant mode_crossing min_bound max_bound
| _ -> Ok default_mode
let check_constructor_crossing_creation
env lid tag ~res ~args held_locks =
check_constructor_crossing
~default_mode:Mode.Value.(disallow_left max)
~for_extensible_variant:(fun mode_crossing min_bound max_bound ->
Result.bind
(Mode.Value.submode
(Mode.Crossing.apply_left mode_crossing min_bound)
Mode.Value.(disallow_left min))
(fun () -> Ok max_bound))
env lid tag ~res ~args held_locks
let check_constructor_crossing_destruction
env lid tag ~res ~args held_locks =
check_constructor_crossing
~default_mode:Mode.Value.(disallow_right min)
~for_extensible_variant:(fun mode_crossing min_bound max_bound ->
Result.bind
(Mode.Value.submode
Mode.Value.(disallow_right max)
(Mode.Crossing.apply_right mode_crossing max_bound))
(fun () -> Ok min_bound))
env lid tag ~res ~args held_locks
let apply_is_contained_by is_contained_by ?(modalities = Modality.Const.id)
mode =
let hint =
{ monadic = Hint.Is_contained_by (Monadic, is_contained_by);
comonadic = Hint.Is_contained_by (Comonadic, is_contained_by) }
in
Modality.Const.apply ~hint modalities mode