summaryrefslogtreecommitdiff
path: root/typing/env.ml
blob: 29d7cdb0e42ba40dc68939b5792a650e112b1655 (plain)
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
(**************************************************************************)
(*                                                                        *)
(*                                 OCaml                                  *)
(*                                                                        *)
(*             Xavier Leroy, projet Cristal, INRIA Rocquencourt           *)
(*                                                                        *)
(*   Copyright 1996 Institut National de Recherche en Informatique et     *)
(*     en Automatique.                                                    *)
(*                                                                        *)
(*   All rights reserved.  This file is distributed under the terms of    *)
(*   the GNU Lesser General Public License version 2.1, with the          *)
(*   special exception on linking described in the file LICENSE.          *)
(*                                                                        *)
(**************************************************************************)

(* Environment handling *)

open Cmi_format
open Misc
open Asttypes
open Longident
open Path
open Types

open Local_store

module String = Misc.Stdlib.String

let add_delayed_check_forward = ref (fun _ -> assert false)

type 'a usage_tbl = ('a -> unit) Types.Uid.Tbl.t
(** This table is used to track usage of value declarations.
    A declaration is identified by its uid.
    The callback attached to a declaration is called whenever the value (or
    type, or ...) is used explicitly (lookup_value, ...) or implicitly
    (inclusion test between signatures, cf Includemod.value_descriptions, ...).
*)

let value_declarations  : unit usage_tbl ref = s_table Types.Uid.Tbl.create 16
let type_declarations   : unit usage_tbl ref = s_table Types.Uid.Tbl.create 16
let module_declarations : unit usage_tbl ref = s_table Types.Uid.Tbl.create 16

let uid_to_loc : Location.t Types.Uid.Tbl.t ref =
  s_table Types.Uid.Tbl.create 16

let register_uid uid loc = Types.Uid.Tbl.add !uid_to_loc uid loc

let get_uid_to_loc_tbl () = !uid_to_loc

type constructor_usage = Positive | Pattern | Exported_private | Exported
type constructor_usages =
  {
    mutable cu_positive: bool;
    mutable cu_pattern: bool;
    mutable cu_exported_private: bool;
  }
let add_constructor_usage cu usage =
  match usage with
  | Positive -> cu.cu_positive <- true
  | Pattern -> cu.cu_pattern <- true
  | Exported_private -> cu.cu_exported_private <- true
  | Exported ->
    cu.cu_positive <- true;
    cu.cu_pattern <- true;
    cu.cu_exported_private <- true

let constructor_usages () =
  {cu_positive = false; cu_pattern = false; cu_exported_private = false}

let constructor_usage_complaint ~rebind priv cu
  : Warnings.constructor_usage_warning option =
  match priv, rebind with
  | Asttypes.Private, _ | _, true ->
      if cu.cu_positive || cu.cu_pattern || cu.cu_exported_private then None
      else Some Unused
  | Asttypes.Public, false -> begin
      match cu.cu_positive, cu.cu_pattern, cu.cu_exported_private with
      | true, _, _ -> None
      | false, false, false -> Some Unused
      | false, true, _ -> Some Not_constructed
      | false, false, true -> Some Only_exported_private
    end

let used_constructors : constructor_usage usage_tbl ref =
  s_table Types.Uid.Tbl.create 16

type label_usage =
    Projection | Mutation | Construct | Exported_private | Exported
type label_usages =
    {
     mutable lu_projection: bool;
     mutable lu_mutation: bool;
     mutable lu_construct: bool;
    }
let add_label_usage lu usage =
  match usage with
  | Projection -> lu.lu_projection <- true;
  | Mutation -> lu.lu_mutation <- true
  | Construct -> lu.lu_construct <- true
  | Exported_private ->
    lu.lu_projection <- true
  | Exported ->
    lu.lu_projection <- true;
    lu.lu_mutation <- true;
    lu.lu_construct <- true

let is_mutating_label_usage = function
  | Mutation -> true
  | (Projection | Construct | Exported_private | Exported) -> false

let label_usages () =
  {lu_projection = false; lu_mutation = false; lu_construct = false}

let label_usage_complaint priv mut lu
  : Warnings.field_usage_warning option =
  match priv, mut with
  | Asttypes.Private, _ ->
      if lu.lu_projection then None
      else Some Unused
  | Asttypes.Public, Asttypes.Immutable -> begin
      match lu.lu_projection, lu.lu_construct with
      | true, _ -> None
      | false, false -> Some Unused
      | false, true -> Some Not_read
    end
  | Asttypes.Public, Asttypes.Mutable -> begin
      match lu.lu_projection, lu.lu_mutation, lu.lu_construct with
      | true, true, _ -> None
      | false, false, false -> Some Unused
      | false, _, _ -> Some Not_read
      | true, false, _ -> Some Not_mutated
    end

let used_labels : label_usage usage_tbl ref =
  s_table Types.Uid.Tbl.create 16

(** Map indexed by the name of module components. *)
module NameMap = String.Map

type value_unbound_reason =
  | Val_unbound_instance_variable
  | Val_unbound_self
  | Val_unbound_ancestor
  | Val_unbound_ghost_recursive of Location.t

type module_unbound_reason =
  | Mod_unbound_illegal_recursion

type summary =
    Env_empty
  | Env_value of summary * Ident.t * value_description
  | Env_type of summary * Ident.t * type_declaration
  | Env_extension of summary * Ident.t * extension_constructor
  | Env_module of summary * Ident.t * module_presence * module_declaration
  | Env_modtype of summary * Ident.t * modtype_declaration
  | Env_class of summary * Ident.t * class_declaration
  | Env_cltype of summary * Ident.t * class_type_declaration
  | Env_open of summary * Path.t
  | Env_functor_arg of summary * Ident.t
  | Env_constraints of summary * type_declaration Path.Map.t
  | Env_copy_types of summary
  | Env_persistent of summary * Ident.t
  | Env_value_unbound of summary * string * value_unbound_reason
  | Env_module_unbound of summary * string * module_unbound_reason

let map_summary f = function
    Env_empty -> Env_empty
  | Env_value (s, id, d) -> Env_value (f s, id, d)
  | Env_type (s, id, d) -> Env_type (f s, id, d)
  | Env_extension (s, id, d) -> Env_extension (f s, id, d)
  | Env_module (s, id, p, d) -> Env_module (f s, id, p, d)
  | Env_modtype (s, id, d) -> Env_modtype (f s, id, d)
  | Env_class (s, id, d) -> Env_class (f s, id, d)
  | Env_cltype (s, id, d) -> Env_cltype (f s, id, d)
  | Env_open (s, p) -> Env_open (f s, p)
  | Env_functor_arg (s, id) -> Env_functor_arg (f s, id)
  | Env_constraints (s, m) -> Env_constraints (f s, m)
  | Env_copy_types s -> Env_copy_types (f s)
  | Env_persistent (s, id) -> Env_persistent (f s, id)
  | Env_value_unbound (s, u, r) -> Env_value_unbound (f s, u, r)
  | Env_module_unbound (s, u, r) -> Env_module_unbound (f s, u, r)

type address =
  | Aident of Ident.t
  | Adot of address * int

module TycompTbl =
  struct
    (** This module is used to store components of types (i.e. labels
        and constructors).  We keep a representation of each nested
        "open" and the set of local bindings between each of them. *)

    type 'a t = {
      current: 'a Ident.tbl;
      (** Local bindings since the last open. *)

      opened: 'a opened option;
      (** Symbolic representation of the last (innermost) open, if any. *)
    }

    and 'a opened = {
      components: ('a list) NameMap.t;
      (** Components from the opened module. We keep a list of
          bindings for each name, as in comp_labels and
          comp_constrs. *)

      root: Path.t;
      (** Only used to check removal of open *)

      using: (string -> ('a * 'a) option -> unit) option;
      (** A callback to be applied when a component is used from this
          "open".  This is used to detect unused "opens".  The
          arguments are used to detect shadowing. *)

      next: 'a t;
      (** The table before opening the module. *)
    }

    let empty = { current = Ident.empty; opened = None }

    let add id x tbl =
      {tbl with current = Ident.add id x tbl.current}

    let add_open slot wrap root components next =
      let using =
        match slot with
        | None -> None
        | Some f -> Some (fun s x -> f s (wrap x))
      in
      {
        current = Ident.empty;
        opened = Some {using; components; root; next};
      }

    let remove_last_open rt tbl =
      match tbl.opened with
      | Some {root; next; _} when Path.same rt root ->
          { next with current =
            Ident.fold_all Ident.add tbl.current next.current }
      | _ ->
          assert false

    let rec find_same id tbl =
      try Ident.find_same id tbl.current
      with Not_found as exn ->
        begin match tbl.opened with
        | Some {next; _} -> find_same id next
        | None -> raise exn
        end

    let nothing = fun () -> ()

    let mk_callback rest name desc using =
      match using with
      | None -> nothing
      | Some f ->
          (fun () ->
             match rest with
             | [] -> f name None
             | (hidden, _) :: _ -> f name (Some (desc, hidden)))

    let rec find_all ~mark name tbl =
      List.map (fun (_id, desc) -> desc, nothing)
        (Ident.find_all name tbl.current) @
      match tbl.opened with
      | None -> []
      | Some {using; next; components; root = _} ->
          let rest = find_all ~mark name next in
          let using = if mark then using else None in
          match NameMap.find name components with
          | exception Not_found -> rest
          | opened ->
              List.map
                (fun desc -> desc, mk_callback rest name desc using)
                opened
              @ rest

    let rec fold_name f tbl acc =
      let acc = Ident.fold_name (fun _id d -> f d) tbl.current acc in
      match tbl.opened with
      | Some {using = _; next; components; root = _} ->
          acc
          |> NameMap.fold
            (fun _name -> List.fold_right f)
            components
          |> fold_name f next
      | None ->
          acc

    let rec local_keys tbl acc =
      let acc = Ident.fold_all (fun k _ accu -> k::accu) tbl.current acc in
      match tbl.opened with
      | Some o -> local_keys o.next acc
      | None -> acc

    let diff_keys is_local tbl1 tbl2 =
      let keys2 = local_keys tbl2 [] in
      List.filter
        (fun id ->
           is_local (find_same id tbl2) &&
           try ignore (find_same id tbl1); false
           with Not_found -> true)
        keys2

  end


module IdTbl =
  struct
    (** This module is used to store all kinds of components except
        (labels and constructors) in environments.  We keep a
        representation of each nested "open" and the set of local
        bindings between each of them. *)


    type ('a, 'b) t = {
      current: 'a Ident.tbl;
      (** Local bindings since the last open *)

      layer: ('a, 'b) layer;
      (** Symbolic representation of the last (innermost) open, if any. *)
    }

    and ('a, 'b) layer =
      | Open of {
          root: Path.t;
          (** The path of the opened module, to be prefixed in front of
              its local names to produce a valid path in the current
              environment. *)

          components: 'b NameMap.t;
          (** Components from the opened module. *)

          using: (string -> ('a * 'a) option -> unit) option;
          (** A callback to be applied when a component is used from this
              "open".  This is used to detect unused "opens".  The
              arguments are used to detect shadowing. *)

          next: ('a, 'b) t;
          (** The table before opening the module. *)
        }

      | Map of {
          f: ('a -> 'a);
          next: ('a, 'b) t;
        }

      | Nothing

    let empty = { current = Ident.empty; layer = Nothing }

    let add id x tbl =
      {tbl with current = Ident.add id x tbl.current}

    let remove id tbl =
      {tbl with current = Ident.remove id tbl.current}

    let add_open slot wrap root components next =
      let using =
        match slot with
        | None -> None
        | Some f -> Some (fun s x -> f s (wrap x))
      in
      {
        current = Ident.empty;
        layer = Open {using; root; components; next};
      }

    let remove_last_open rt tbl =
      match tbl.layer with
      | Open {root; next; _} when Path.same rt root ->
          { next with current =
            Ident.fold_all Ident.add tbl.current next.current }
      | _ ->
          assert false

    let map f next =
      {
        current = Ident.empty;
        layer = Map {f; next}
      }

    let rec find_same id tbl =
      try Ident.find_same id tbl.current
      with Not_found as exn ->
        begin match tbl.layer with
        | Open {next; _} -> find_same id next
        | Map {f; next} -> f (find_same id next)
        | Nothing -> raise exn
        end

    let rec find_name wrap ~mark name tbl =
      try
        let (id, desc) = Ident.find_name name tbl.current in
        Pident id, desc
      with Not_found as exn ->
        begin match tbl.layer with
        | Open {using; root; next; components} ->
            begin try
              let descr = wrap (NameMap.find name components) in
              let res = Pdot (root, name), descr in
              if mark then begin match using with
              | None -> ()
              | Some f -> begin
                  match find_name wrap ~mark:false name next with
                  | exception Not_found -> f name None
                  | _, descr' -> f name (Some (descr', descr))
                end
              end;
              res
            with Not_found ->
              find_name wrap ~mark name next
            end
        | Map {f; next} ->
            let (p, desc) =  find_name wrap ~mark name next in
            p, f desc
        | Nothing ->
            raise exn
        end

    let rec find_all wrap name tbl =
      List.map
        (fun (id, desc) -> Pident id, desc)
        (Ident.find_all name tbl.current) @
      match tbl.layer with
      | Nothing -> []
      | Open {root; using = _; next; components} ->
          begin try
            let desc = wrap (NameMap.find name components) in
            (Pdot (root, name), desc) :: find_all wrap name next
          with Not_found ->
            find_all wrap name next
          end
      | Map {f; next} ->
          List.map (fun (p, desc) -> (p, f desc))
            (find_all wrap name next)

    let rec fold_name wrap f tbl acc =
      let acc =
        Ident.fold_name
          (fun id d -> f (Ident.name id) (Pident id, d))
          tbl.current acc
      in
      match tbl.layer with
      | Open {root; using = _; next; components} ->
          acc
          |> NameMap.fold
            (fun name desc -> f name (Pdot (root, name), wrap desc))
            components
          |> fold_name wrap f next
      | Nothing ->
          acc
      | Map {f=g; next} ->
          acc
          |> fold_name wrap
               (fun name (path, desc) -> f name (path, g desc))
               next

    let rec local_keys tbl acc =
      let acc = Ident.fold_all (fun k _ accu -> k::accu) tbl.current acc in
      match tbl.layer with
      | Open {next; _ } | Map {next; _} -> local_keys next acc
      | Nothing -> acc


    let rec iter wrap f tbl =
      Ident.iter (fun id desc -> f id (Pident id, desc)) tbl.current;
      match tbl.layer with
      | Open {root; using = _; next; components} ->
          NameMap.iter
            (fun s x ->
               let root_scope = Path.scope root in
              f (Ident.create_scoped ~scope:root_scope s)
                (Pdot (root, s), wrap x))
            components;
          iter wrap f next
      | Map {f=g; next} ->
          iter wrap (fun id (path, desc) -> f id (path, g desc)) next
      | Nothing -> ()

    let diff_keys tbl1 tbl2 =
      let keys2 = local_keys tbl2 [] in
      List.filter
        (fun id ->
           try ignore (find_same id tbl1); false
           with Not_found -> true)
        keys2


  end

type type_descr_kind =
  (label_description, constructor_description) type_kind

type type_descriptions = type_descr_kind

let in_signature_flag = 0x01

type t = {
  values: (value_entry, value_data) IdTbl.t;
  constrs: constructor_data TycompTbl.t;
  labels: label_data TycompTbl.t;
  types: (type_data, type_data) IdTbl.t;
  modules: (module_entry, module_data) IdTbl.t;
  modtypes: (modtype_data, modtype_data) IdTbl.t;
  classes: (class_data, class_data) IdTbl.t;
  cltypes: (cltype_data, cltype_data) IdTbl.t;
  functor_args: unit Ident.tbl;
  summary: summary;
  local_constraints: type_declaration Path.Map.t;
  flags: int;
}

and module_components =
  {
    alerts: alerts;
    uid: Uid.t;
    comps:
      (components_maker,
       (module_components_repr, module_components_failure) result)
        Lazy_backtrack.t;
  }

and components_maker = {
  cm_env: t;
  cm_prefixing_subst: Subst.t;
  cm_path: Path.t;
  cm_addr: address_lazy;
  cm_mty: Subst.Lazy.modtype;
  cm_shape: Shape.t;
}

and module_components_repr =
    Structure_comps of structure_components
  | Functor_comps of functor_components

and module_components_failure =
  | No_components_abstract
  | No_components_alias of Path.t

and structure_components = {
  mutable comp_values: value_data NameMap.t;
  mutable comp_constrs: constructor_data list NameMap.t;
  mutable comp_labels: label_data list NameMap.t;
  mutable comp_types: type_data NameMap.t;
  mutable comp_modules: module_data NameMap.t;
  mutable comp_modtypes: modtype_data NameMap.t;
  mutable comp_classes: class_data NameMap.t;
  mutable comp_cltypes: cltype_data NameMap.t;
}

and functor_components = {
  fcomp_arg: functor_parameter;
  (* Formal parameter and argument signature *)
  fcomp_res: module_type;               (* Result signature *)
  fcomp_shape: Shape.t;
  fcomp_cache: (Path.t, module_components) Hashtbl.t;  (* For memoization *)
  fcomp_subst_cache: (Path.t, module_type) Hashtbl.t
}

and address_unforced =
  | Projection of { parent : address_lazy; pos : int; }
  | ModAlias of { env : t; path : Path.t; }

and address_lazy = (address_unforced, address) Lazy_backtrack.t

and value_data =
  { vda_description : value_description;
    vda_address : address_lazy;
    vda_shape : Shape.t }

and value_entry =
  | Val_bound of value_data
  | Val_unbound of value_unbound_reason

and constructor_data =
  { cda_description : constructor_description;
    cda_address : address_lazy option;
    cda_shape: Shape.t; }

and label_data = label_description

and type_data =
  { tda_declaration : type_declaration;
    tda_descriptions : type_descriptions;
    tda_shape : Shape.t; }

and module_data =
  { mda_declaration : Subst.Lazy.module_decl;
    mda_components : module_components;
    mda_address : address_lazy;
    mda_shape: Shape.t; }

and module_entry =
  | Mod_local of module_data
  | Mod_persistent
  | Mod_unbound of module_unbound_reason

and modtype_data =
  { mtda_declaration : Subst.Lazy.modtype_declaration;
    mtda_shape : Shape.t; }

and class_data =
  { clda_declaration : class_declaration;
    clda_address : address_lazy;
    clda_shape : Shape.t }

and cltype_data =
  { cltda_declaration : class_type_declaration;
    cltda_shape : Shape.t }

let empty_structure =
  Structure_comps {
    comp_values = NameMap.empty;
    comp_constrs = NameMap.empty;
    comp_labels = NameMap.empty;
    comp_types = NameMap.empty;
    comp_modules = NameMap.empty; comp_modtypes = NameMap.empty;
    comp_classes = NameMap.empty;
    comp_cltypes = NameMap.empty }

type unbound_value_hint =
  | No_hint
  | Missing_rec of Location.t

type lookup_error =
  | Unbound_value of Longident.t * unbound_value_hint
  | Unbound_type of Longident.t
  | Unbound_constructor of Longident.t
  | Unbound_label of Longident.t
  | Unbound_module of Longident.t
  | Unbound_class of Longident.t
  | Unbound_modtype of Longident.t
  | Unbound_cltype of Longident.t
  | Unbound_instance_variable of string
  | Not_an_instance_variable of string
  | Masked_instance_variable of Longident.t
  | Masked_self_variable of Longident.t
  | Masked_ancestor_variable of Longident.t
  | Structure_used_as_functor of Longident.t
  | Abstract_used_as_functor of Longident.t
  | Functor_used_as_structure of Longident.t
  | Abstract_used_as_structure of Longident.t
  | Generative_used_as_applicative of Longident.t
  | Illegal_reference_to_recursive_module
  | Cannot_scrape_alias of Longident.t * Path.t

type error =
  | Missing_module of Location.t * Path.t * Path.t
  | Illegal_value_name of Location.t * string
  | Lookup_error of Location.t * t * lookup_error

exception Error of error

let error err = raise (Error err)

let lookup_error loc env err =
  error (Lookup_error(loc, env, err))

let same_constr = ref (fun _ _ _ -> assert false)

let check_well_formed_module = ref (fun _ -> assert false)

(* Helper to decide whether to report an identifier shadowing
   by some 'open'. For labels and constructors, we do not report
   if the two elements are from the same re-exported declaration.

   Later, one could also interpret some attributes on value and
   type declarations to silence the shadowing warnings. *)

let check_shadowing env = function
  | `Constructor (Some (cda1, cda2))
    when not (!same_constr env
                cda1.cda_description.cstr_res
                cda2.cda_description.cstr_res) ->
      Some "constructor"
  | `Label (Some (l1, l2))
    when not (!same_constr env l1.lbl_res l2.lbl_res) ->
      Some "label"
  | `Value (Some _) -> Some "value"
  | `Type (Some _) -> Some "type"
  | `Module (Some _) | `Component (Some _) -> Some "module"
  | `Module_type (Some _) -> Some "module type"
  | `Class (Some _) -> Some "class"
  | `Class_type (Some _) -> Some "class type"
  | `Constructor _ | `Label _
  | `Value None | `Type None | `Module None | `Module_type None
  | `Class None | `Class_type None | `Component None ->
      None

let empty = {
  values = IdTbl.empty; constrs = TycompTbl.empty;
  labels = TycompTbl.empty; types = IdTbl.empty;
  modules = IdTbl.empty; modtypes = IdTbl.empty;
  classes = IdTbl.empty; cltypes = IdTbl.empty;
  summary = Env_empty; local_constraints = Path.Map.empty;
  flags = 0;
  functor_args = Ident.empty;
 }

let in_signature b env =
  let flags =
    if b then env.flags lor in_signature_flag
    else env.flags land (lnot in_signature_flag)
  in
  {env with flags}

let is_in_signature env = env.flags land in_signature_flag <> 0

let has_local_constraints env =
  not (Path.Map.is_empty env.local_constraints)

let is_ident = function
    Pident _ -> true
  | Pdot _ | Papply _ -> false

let is_ext cda =
  match cda.cda_description with
  | {cstr_tag = Cstr_extension _} -> true
  | _ -> false

let is_local_ext cda =
  match cda.cda_description with
  | {cstr_tag = Cstr_extension(p, _)} -> is_ident p
  | _ -> false

let diff env1 env2 =
  IdTbl.diff_keys env1.values env2.values @
  TycompTbl.diff_keys is_local_ext env1.constrs env2.constrs @
  IdTbl.diff_keys env1.modules env2.modules @
  IdTbl.diff_keys env1.classes env2.classes

(* Functions for use in "wrap" parameters in IdTbl *)
let wrap_identity x = x
let wrap_value vda = Val_bound vda
let wrap_module mda = Mod_local mda

(* Forward declarations *)

let components_of_module_maker' =
  ref ((fun _ -> assert false) :
          components_maker ->
            (module_components_repr, module_components_failure) result)

let components_of_functor_appl' =
  ref ((fun ~loc:_ ~f_path:_ ~f_comp:_ ~arg:_ _env -> assert false) :
          loc:Location.t -> f_path:Path.t -> f_comp:functor_components ->
            arg:Path.t -> t -> module_components)
let check_functor_application =
  (* to be filled by Includemod *)
  ref ((fun ~errors:_ ~loc:_
         ~lid_whole_app:_  ~f0_path:_ ~args:_
         ~arg_path:_ ~arg_mty:_ ~param_mty:_
         _env
         -> assert false) :
         errors:bool -> loc:Location.t ->
       lid_whole_app:Longident.t ->
       f0_path:Path.t -> args:(Path.t * Types.module_type) list ->
       arg_path:Path.t -> arg_mty:module_type -> param_mty:module_type ->
       t -> unit)
let strengthen =
  (* to be filled with Mtype.strengthen *)
  ref ((fun ~aliasable:_ _env _mty _path -> assert false) :
         aliasable:bool -> t -> Subst.Lazy.modtype ->
         Path.t -> Subst.Lazy.modtype)

let md md_type =
  {md_type; md_attributes=[]; md_loc=Location.none
  ;md_uid = Uid.internal_not_actually_unique}

(* Print addresses *)

let rec print_address ppf = function
  | Aident id -> Format.fprintf ppf "%s" (Ident.name id)
  | Adot(a, pos) -> Format.fprintf ppf "%a.[%i]" print_address a pos

(* The name of the compilation unit currently compiled.
   "" if outside a compilation unit. *)
module Current_unit_name : sig
  val get : unit -> modname
  val set : modname -> unit
  val is : modname -> bool
  val is_ident : Ident.t -> bool
  val is_path : Path.t -> bool
end = struct
  let current_unit =
    ref ""
  let get () =
    !current_unit
  let set name =
    current_unit := name
  let is name =
    !current_unit = name
  let is_ident id =
    Ident.persistent id && is (Ident.name id)
  let is_path = function
  | Pident id -> is_ident id
  | Pdot _ | Papply _ -> false
end

let set_unit_name = Current_unit_name.set
let get_unit_name = Current_unit_name.get

let find_same_module id tbl =
  match IdTbl.find_same id tbl with
  | x -> x
  | exception Not_found
    when Ident.persistent id && not (Current_unit_name.is_ident id) ->
      Mod_persistent

let find_name_module ~mark name tbl =
  match IdTbl.find_name wrap_module ~mark name tbl with
  | x -> x
  | exception Not_found when not (Current_unit_name.is name) ->
      let path = Pident(Ident.create_persistent name) in
      path, Mod_persistent

let add_persistent_structure id env =
  if not (Ident.persistent id) then invalid_arg "Env.add_persistent_structure";
  if Current_unit_name.is_ident id then env
  else begin
    let material =
      (* This addition only observably changes the environment if it shadows a
         non-persistent module already in the environment.
         (See PR#9345) *)
      match
        IdTbl.find_name wrap_module ~mark:false (Ident.name id) env.modules
      with
      | exception Not_found | _, Mod_persistent -> false
      | _ -> true
    in
    let summary =
      if material then Env_persistent (env.summary, id)
      else env.summary
    in
    let modules =
      (* With [-no-alias-deps], non-material additions should not
         affect the environment at all. We should only observe the
         existence of a cmi when accessing components of the module.
         (See #9991). *)
      if material || not !Clflags.transparent_modules then
        IdTbl.add id Mod_persistent env.modules
      else
        env.modules
    in
    { env with modules; summary }
  end

let components_of_module ~alerts ~uid env ps path addr mty shape =
  {
    alerts;
    uid;
    comps = Lazy_backtrack.create {
      cm_env = env;
      cm_prefixing_subst = ps;
      cm_path = path;
      cm_addr = addr;
      cm_mty = mty;
      cm_shape = shape;
    }
  }

let sign_of_cmi ~freshen { Persistent_env.Persistent_signature.cmi; _ } =
  let name = cmi.cmi_name in
  let sign = cmi.cmi_sign in
  let flags = cmi.cmi_flags in
  let id = Ident.create_persistent name in
  let path = Pident id in
  let alerts =
    List.fold_left (fun acc -> function Alerts s -> s | _ -> acc)
      Misc.Stdlib.String.Map.empty
      flags
  in
  let md =
    { md_type =  Mty_signature sign;
      md_loc = Location.none;
      md_attributes = [];
      md_uid = Uid.of_compilation_unit_id id;
    }
  in
  let mda_address = Lazy_backtrack.create_forced (Aident id) in
  let mda_declaration =
    Subst.(Lazy.module_decl Make_local identity (Lazy.of_module_decl md))
  in
  let mda_shape = Shape.for_persistent_unit name in
  let mda_components =
    let mty = Subst.Lazy.of_modtype (Mty_signature sign) in
    let mty =
      if freshen then
        Subst.Lazy.modtype (Subst.Rescope (Path.scope path))
          Subst.identity mty
      else mty
    in
    components_of_module ~alerts ~uid:md.md_uid
      empty Subst.identity
      path mda_address mty mda_shape
  in
  {
    mda_declaration;
    mda_components;
    mda_address;
    mda_shape;
  }

let read_sign_of_cmi = sign_of_cmi ~freshen:true

let save_sign_of_cmi = sign_of_cmi ~freshen:false

let persistent_env : module_data Persistent_env.t ref =
  s_table Persistent_env.empty ()

let without_cmis f x =
  Persistent_env.without_cmis !persistent_env f x

let imports () = Persistent_env.imports !persistent_env

let import_crcs ~source crcs =
  Persistent_env.import_crcs !persistent_env ~source crcs

let read_pers_mod modname filename =
  Persistent_env.read !persistent_env read_sign_of_cmi modname filename

let find_pers_mod name =
  Persistent_env.find !persistent_env read_sign_of_cmi name

let check_pers_mod ~loc name =
  Persistent_env.check !persistent_env read_sign_of_cmi ~loc name

let crc_of_unit name =
  Persistent_env.crc_of_unit !persistent_env read_sign_of_cmi name

let is_imported_opaque modname =
  Persistent_env.is_imported_opaque !persistent_env modname

let register_import_as_opaque modname =
  Persistent_env.register_import_as_opaque !persistent_env modname

let reset_declaration_caches () =
  Types.Uid.Tbl.clear !value_declarations;
  Types.Uid.Tbl.clear !type_declarations;
  Types.Uid.Tbl.clear !module_declarations;
  Types.Uid.Tbl.clear !used_constructors;
  Types.Uid.Tbl.clear !used_labels;
  Types.Uid.Tbl.clear !uid_to_loc;
  ()

let reset_cache () =
  Current_unit_name.set "";
  Persistent_env.clear !persistent_env;
  reset_declaration_caches ();
  ()

let reset_cache_toplevel () =
  Persistent_env.clear_missing !persistent_env;
  reset_declaration_caches ();
  ()

(* get_components *)

let get_components_res c =
  match Persistent_env.can_load_cmis !persistent_env with
  | Persistent_env.Can_load_cmis ->
    Lazy_backtrack.force !components_of_module_maker' c.comps
  | Persistent_env.Cannot_load_cmis log ->
    Lazy_backtrack.force_logged log !components_of_module_maker' c.comps

let get_components c =
  match get_components_res c with
  | Error _ -> empty_structure
  | Ok c -> c

(* Module type of functor application *)

let modtype_of_functor_appl fcomp p1 p2 =
  match fcomp.fcomp_res with
  | Mty_alias _ as mty -> mty
  | mty ->
      try
        Hashtbl.find fcomp.fcomp_subst_cache p2
      with Not_found ->
        let scope = Path.scope (Papply(p1, p2)) in
        let mty =
          let subst =
            match fcomp.fcomp_arg with
            | Unit
            | Named (None, _) -> Subst.identity
            | Named (Some param, _) -> Subst.add_module param p2 Subst.identity
          in
          Subst.modtype (Rescope scope) subst mty
        in
        Hashtbl.add fcomp.fcomp_subst_cache p2 mty;
        mty

let check_functor_appl
    ~errors ~loc ~lid_whole_app ~f0_path ~args
    ~f_comp
    ~arg_path ~arg_mty ~param_mty
    env =
  if not (Hashtbl.mem f_comp.fcomp_cache arg_path) then
    !check_functor_application
      ~errors ~loc ~lid_whole_app ~f0_path ~args
      ~arg_path ~arg_mty ~param_mty
      env

(* Lookup by identifier *)

let find_ident_module id env =
  match find_same_module id env.modules with
  | Mod_local data -> data
  | Mod_unbound _ -> raise Not_found
  | Mod_persistent -> find_pers_mod (Ident.name id)

let rec find_module_components path env =
  match path with
  | Pident id -> (find_ident_module id env).mda_components
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      (NameMap.find s sc.comp_modules).mda_components
  | Papply(f_path, arg) ->
      let f_comp = find_functor_components f_path env in
      let loc = Location.(in_file !input_name) in
      !components_of_functor_appl' ~loc ~f_path ~f_comp ~arg env

and find_structure_components path env =
  match get_components (find_module_components path env) with
  | Structure_comps c -> c
  | Functor_comps _ -> raise Not_found

and find_functor_components path env =
  match get_components (find_module_components path env) with
  | Functor_comps f -> f
  | Structure_comps _ -> raise Not_found

let find_module ~alias path env =
  match path with
  | Pident id ->
      let data = find_ident_module id env in
      Subst.Lazy.force_module_decl data.mda_declaration
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      let data = NameMap.find s sc.comp_modules in
      Subst.Lazy.force_module_decl data.mda_declaration
  | Papply(p1, p2) ->
      let fc = find_functor_components p1 env in
      if alias then md (fc.fcomp_res)
      else md (modtype_of_functor_appl fc p1 p2)

let find_module_lazy ~alias path env =
  match path with
  | Pident id ->
      let data = find_ident_module id env in
      data.mda_declaration
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      let data = NameMap.find s sc.comp_modules in
      data.mda_declaration
  | Papply(p1, p2) ->
      let fc = find_functor_components p1 env in
      let md =
        if alias then md (fc.fcomp_res)
        else md (modtype_of_functor_appl fc p1 p2)
      in
      Subst.Lazy.of_module_decl md

let find_strengthened_module ~aliasable path env =
  let md = find_module_lazy ~alias:true path env in
  let mty = !strengthen ~aliasable env md.mdl_type path in
  Subst.Lazy.force_modtype mty

let find_value_full path env =
  match path with
  | Pident id -> begin
      match IdTbl.find_same id env.values with
      | Val_bound data -> data
      | Val_unbound _ -> raise Not_found
    end
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      NameMap.find s sc.comp_values
  | Papply _ -> raise Not_found

let find_type_full path env =
  match path with
  | Pident id -> IdTbl.find_same id env.types
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      NameMap.find s sc.comp_types
  | Papply _ -> raise Not_found

let find_modtype_lazy path env =
  match path with
  | Pident id -> (IdTbl.find_same id env.modtypes).mtda_declaration
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      (NameMap.find s sc.comp_modtypes).mtda_declaration
  | Papply _ -> raise Not_found

let find_modtype path env =
  Subst.Lazy.force_modtype_decl (find_modtype_lazy path env)

let find_class_full path env =
  match path with
  | Pident id -> IdTbl.find_same id env.classes
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      NameMap.find s sc.comp_classes
  | Papply _ -> raise Not_found

let find_cltype path env =
  match path with
  | Pident id -> (IdTbl.find_same id env.cltypes).cltda_declaration
  | Pdot(p, s) ->
      let sc = find_structure_components p env in
      (NameMap.find s sc.comp_cltypes).cltda_declaration
  | Papply _ -> raise Not_found

let find_value path env =
  (find_value_full path env).vda_description

let find_class path env =
  (find_class_full path env).clda_declaration

let find_ident_constructor id env =
  (TycompTbl.find_same id env.constrs).cda_description

let find_ident_label id env =
  TycompTbl.find_same id env.labels

let type_of_cstr path = function
  | {cstr_inlined = Some decl; _} ->
      let labels =
        List.map snd (Datarepr.labels_of_type path decl)
      in
      begin match decl.type_kind with
      | Type_record (_, repr) ->
        {
          tda_declaration = decl;
          tda_descriptions = Type_record (labels, repr);
          tda_shape = Shape.leaf decl.type_uid;
        }
      | _ -> assert false
      end
  | _ -> assert false

let find_type_data path env =
  match Path.constructor_typath path with
  | Regular p -> begin
      match Path.Map.find p env.local_constraints with
      | decl ->
          {
            tda_declaration = decl;
            tda_descriptions = Type_abstract;
            tda_shape = Shape.leaf decl.type_uid;
          }
      | exception Not_found -> find_type_full p env
    end
  | Cstr (ty_path, s) ->
      (* This case corresponds to an inlined record *)
      let tda =
        try find_type_full ty_path env
        with Not_found -> assert false
      in
      let cstr =
        begin match tda.tda_descriptions with
        | Type_variant (cstrs, _) -> begin
            try
              List.find (fun cstr -> cstr.cstr_name = s) cstrs
            with Not_found -> assert false
          end
        | Type_record _ | Type_abstract | Type_open -> assert false
        end
      in
      type_of_cstr path cstr
  | LocalExt id ->
      let cstr =
        try (TycompTbl.find_same id env.constrs).cda_description
        with Not_found -> assert false
      in
      type_of_cstr path cstr
  | Ext (mod_path, s) ->
      let comps =
        try find_structure_components mod_path env
        with Not_found -> assert false
      in
      let cstrs =
        try NameMap.find s comps.comp_constrs
        with Not_found -> assert false
      in
      let exts = List.filter is_ext cstrs in
      match exts with
      | [cda] -> type_of_cstr path cda.cda_description
      | _ -> assert false

let find_type p env =
  (find_type_data p env).tda_declaration
let find_type_descrs p env =
  (find_type_data p env).tda_descriptions

let rec find_module_address path env =
  match path with
  | Pident id -> get_address (find_ident_module id env).mda_address
  | Pdot(p, s) ->
      let c = find_structure_components p env in
      get_address (NameMap.find s c.comp_modules).mda_address
  | Papply _ -> raise Not_found

and force_address = function
  | Projection { parent; pos } -> Adot(get_address parent, pos)
  | ModAlias { env; path } -> find_module_address path env

and get_address a =
  Lazy_backtrack.force force_address a

let find_value_address path env =
  get_address (find_value_full path env).vda_address

let find_class_address path env =
  get_address (find_class_full path env).clda_address

let rec get_constrs_address = function
  | [] -> raise Not_found
  | cda :: rest ->
    match cda.cda_address with
    | None -> get_constrs_address rest
    | Some a -> get_address a

let find_constructor_address path env =
  match path with
  | Pident id -> begin
      let cda = TycompTbl.find_same id env.constrs in
      match cda.cda_address with
      | None -> raise Not_found
      | Some addr -> get_address addr
    end
  | Pdot(p, s) ->
      let c = find_structure_components p env in
      get_constrs_address (NameMap.find s c.comp_constrs)
  | Papply _ ->
      raise Not_found

let find_hash_type path env =
  match path with
  | Pident id ->
      let name = "#" ^ Ident.name id in
      let _, tda =
        IdTbl.find_name wrap_identity ~mark:false name env.types
      in
      tda.tda_declaration
  | Pdot(p, s) ->
      let c = find_structure_components p env in
      let name = "#" ^ s in
      let tda = NameMap.find name c.comp_types in
      tda.tda_declaration
  | Papply _ ->
      raise Not_found

let find_shape env (ns : Shape.Sig_component_kind.t) id =
  match ns with
  | Type ->
      (IdTbl.find_same id env.types).tda_shape
  | Extension_constructor ->
      (TycompTbl.find_same id env.constrs).cda_shape
  | Value ->
      begin match IdTbl.find_same id env.values with
      | Val_bound x -> x.vda_shape
      | Val_unbound _ -> raise Not_found
      end
  | Module ->
      begin match IdTbl.find_same id env.modules with
      | Mod_local { mda_shape; _ } -> mda_shape
      | Mod_persistent -> Shape.for_persistent_unit (Ident.name id)
      | Mod_unbound _ ->
          (* Only present temporarily while approximating the environment for
             recursive modules.
             [find_shape] is only ever called after the environment gets
             properly populated. *)
          assert false
      | exception Not_found
        when Ident.persistent id && not (Current_unit_name.is_ident id) ->
          Shape.for_persistent_unit (Ident.name id)
      end
  | Module_type ->
      (IdTbl.find_same id env.modtypes).mtda_shape
  | Class ->
      (IdTbl.find_same id env.classes).clda_shape
  | Class_type ->
      (IdTbl.find_same id env.cltypes).cltda_shape

let shape_of_path ~namespace env =
  Shape.of_path ~namespace ~find_shape:(find_shape env)

let shape_or_leaf uid = function
  | None -> Shape.leaf uid
  | Some shape -> shape

let required_globals = s_ref []
let reset_required_globals () = required_globals := []
let get_required_globals () = !required_globals
let add_required_global id =
  if Ident.global id && not !Clflags.transparent_modules
  && not (List.exists (Ident.same id) !required_globals)
  then required_globals := id :: !required_globals

let rec normalize_module_path lax env = function
  | Pident id as path when lax && Ident.persistent id ->
      path (* fast path (avoids lookup) *)
  | Pdot (p, s) as path ->
      let p' = normalize_module_path lax env p in
      if p == p' then expand_module_path lax env path
      else expand_module_path lax env (Pdot(p', s))
  | Papply (p1, p2) as path ->
      let p1' = normalize_module_path lax env p1 in
      let p2' = normalize_module_path true env p2 in
      if p1 == p1' && p2 == p2' then expand_module_path lax env path
      else expand_module_path lax env (Papply(p1', p2'))
  | Pident _ as path ->
      expand_module_path lax env path

and expand_module_path lax env path =
  try match find_module_lazy ~alias:true path env with
    {mdl_type=MtyL_alias path1} ->
      let path' = normalize_module_path lax env path1 in
      if lax || !Clflags.transparent_modules then path' else
      let id = Path.head path in
      if Ident.global id && not (Ident.same id (Path.head path'))
      then add_required_global id;
      path'
  | _ -> path
  with Not_found when lax
  || (match path with Pident id -> not (Ident.persistent id) | _ -> true) ->
      path

let normalize_module_path oloc env path =
  try normalize_module_path (oloc = None) env path
  with Not_found ->
    match oloc with None -> assert false
    | Some loc ->
        error (Missing_module(loc, path,
                              normalize_module_path true env path))

let normalize_path_prefix oloc env path =
  match path with
    Pdot(p, s) ->
      let p2 = normalize_module_path oloc env p in
      if p == p2 then path else Pdot(p2, s)
  | Pident _ ->
      path
  | Papply _ ->
      assert false

let normalize_type_path oloc env path =
  (* Inlined version of Path.is_constructor_typath:
     constructor type paths (i.e. path pointing to an inline
     record argument of a constructpr) are built as a regular
     type path followed by a capitalized constructor name. *)
  match path with
  | Pident _ ->
      path
  | Pdot(p, s) ->
      let p2 =
        if Path.is_uident s && not (Path.is_uident (Path.last p)) then
          (* Cstr M.t.C *)
          normalize_path_prefix oloc env p
        else
          (* Regular M.t, Ext M.C *)
          normalize_module_path oloc env p
      in
      if p == p2 then path else Pdot (p2, s)
  | Papply _ ->
      assert false

let rec normalize_modtype_path env path =
  let path = normalize_path_prefix None env path in
  expand_modtype_path env path

and expand_modtype_path env path =
  match (find_modtype_lazy path env).mtdl_type with
  | Some (MtyL_ident path) -> normalize_modtype_path env path
  | _ | exception Not_found -> path

let find_module path env =
  find_module ~alias:false path env

let find_module_lazy path env =
  find_module_lazy ~alias:false path env

(* Find the manifest type associated to a type when appropriate:
   - the type should be public or should have a private row,
   - the type should have an associated manifest type. *)
let find_type_expansion path env =
  let decl = find_type path env in
  match decl.type_manifest with
  | Some body when decl.type_private = Public
              || decl.type_kind <> Type_abstract
              || Btype.has_constr_row body ->
      (decl.type_params, body, decl.type_expansion_scope)
  (* The manifest type of Private abstract data types without
     private row are still considered unknown to the type system.
     Hence, this case is caught by the following clause that also handles
     purely abstract data types without manifest type definition. *)
  | _ -> raise Not_found

(* Find the manifest type information associated to a type, i.e.
   the necessary information for the compiler's type-based optimisations.
   In particular, the manifest type associated to a private abstract type
   is revealed for the sake of compiler's type-based optimisations. *)
let find_type_expansion_opt path env =
  let decl = find_type path env in
  match decl.type_manifest with
  (* The manifest type of Private abstract data types can still get
     an approximation using their manifest type. *)
  | Some body ->
      (decl.type_params, body, decl.type_expansion_scope)
  | _ -> raise Not_found

let find_modtype_expansion_lazy path env =
  match (find_modtype_lazy path env).mtdl_type with
  | None -> raise Not_found
  | Some mty -> mty

let find_modtype_expansion path env =
  Subst.Lazy.force_modtype (find_modtype_expansion_lazy path env)

let rec is_functor_arg path env =
  match path with
    Pident id ->
      begin try Ident.find_same id env.functor_args; true
      with Not_found -> false
      end
  | Pdot (p, _s) -> is_functor_arg p env
  | Papply _ -> true

(* Copying types associated with values *)

let make_copy_of_types env0 =
  let memo = Hashtbl.create 16 in
  let copy t =
    try
      Hashtbl.find memo (get_id t)
    with Not_found ->
      let t2 = Subst.type_expr Subst.identity t in
      Hashtbl.add memo (get_id t) t2;
      t2
  in
  let f = function
    | Val_unbound _ as entry -> entry
    | Val_bound vda ->
        let desc = vda.vda_description in
        let desc = { desc with val_type = copy desc.val_type } in
        Val_bound { vda with vda_description = desc }
  in
  let values =
    IdTbl.map f env0.values
  in
  (fun env ->
     (*if env.values != env0.values then fatal_error "Env.make_copy_of_types";*)
     {env with values; summary = Env_copy_types env.summary}
  )

(* Iter on an environment (ignoring the body of functors and
   not yet evaluated structures) *)

type iter_cont = unit -> unit
let iter_env_cont = ref []

let rec scrape_alias_for_visit env mty =
  let open Subst.Lazy in
  match mty with
  | MtyL_alias path -> begin
      match path with
      | Pident id
        when Ident.persistent id
          && not (Persistent_env.looked_up !persistent_env (Ident.name id)) ->
          false
      | path -> (* PR#6600: find_module may raise Not_found *)
          try
            scrape_alias_for_visit env (find_module_lazy path env).mdl_type
          with Not_found -> false
    end
  | _ -> true

let iter_env wrap proj1 proj2 f env () =
  IdTbl.iter wrap (fun id x -> f (Pident id) x) (proj1 env);
  let rec iter_components path path' mcomps =
    let cont () =
      let visit =
        match Lazy_backtrack.get_arg mcomps.comps with
        | None -> true
        | Some { cm_mty; _ } ->
            scrape_alias_for_visit env cm_mty
      in
      if not visit then () else
      match get_components mcomps with
        Structure_comps comps ->
          NameMap.iter
            (fun s d -> f (Pdot (path, s)) (Pdot (path', s), d))
            (proj2 comps);
          NameMap.iter
            (fun s mda ->
              iter_components
                (Pdot (path, s)) (Pdot (path', s)) mda.mda_components)
            comps.comp_modules
      | Functor_comps _ -> ()
    in iter_env_cont := (path, cont) :: !iter_env_cont
  in
  IdTbl.iter wrap_module
    (fun id (path, entry) ->
       match entry with
       | Mod_unbound _ -> ()
       | Mod_local data ->
           iter_components (Pident id) path data.mda_components
       | Mod_persistent ->
           let modname = Ident.name id in
           match Persistent_env.find_in_cache !persistent_env modname with
           | None -> ()
           | Some data ->
               iter_components (Pident id) path data.mda_components)
    env.modules

let run_iter_cont l =
  iter_env_cont := [];
  List.iter (fun c -> c ()) l;
  let cont = List.rev !iter_env_cont in
  iter_env_cont := [];
  cont

let iter_types f =
  iter_env wrap_identity (fun env -> env.types) (fun sc -> sc.comp_types)
    (fun p1 (p2, tda) -> f p1 (p2, tda.tda_declaration))

let same_types env1 env2 =
  env1.types == env2.types && env1.modules == env2.modules

let used_persistent () =
  Persistent_env.fold !persistent_env
    (fun s _m r -> String.Set.add s r)
    String.Set.empty

let find_all_comps wrap proj s (p, mda) =
  match get_components mda.mda_components with
    Functor_comps _ -> []
  | Structure_comps comps ->
      try
        let c = NameMap.find s (proj comps) in
        [Pdot(p,s), wrap c]
      with Not_found -> []

let rec find_shadowed_comps path env =
  match path with
  | Pident id ->
      List.filter_map
        (fun (p, data) ->
           match data with
           | Mod_local x -> Some (p, x)
           | Mod_unbound _ | Mod_persistent -> None)
        (IdTbl.find_all wrap_module (Ident.name id) env.modules)
  | Pdot (p, s) ->
      let l = find_shadowed_comps p env in
      let l' =
        List.map
          (find_all_comps wrap_identity
             (fun comps -> comps.comp_modules) s) l
      in
      List.flatten l'
  | Papply _ -> []

let find_shadowed wrap proj1 proj2 path env =
  match path with
    Pident id ->
      IdTbl.find_all wrap (Ident.name id) (proj1 env)
  | Pdot (p, s) ->
      let l = find_shadowed_comps p env in
      let l' = List.map (find_all_comps wrap proj2 s) l in
      List.flatten l'
  | Papply _ -> []

let find_shadowed_types path env =
  List.map fst
    (find_shadowed wrap_identity
       (fun env -> env.types) (fun comps -> comps.comp_types) path env)

(* Expand manifest module type names at the top of the given module type *)

let rec scrape_alias env ?path mty =
  let open Subst.Lazy in
  match mty, path with
    MtyL_ident p, _ ->
      begin try
        scrape_alias env (find_modtype_expansion_lazy p env) ?path
      with Not_found ->
        mty
      end
  | MtyL_alias path, _ ->
      begin try
        scrape_alias env ((find_module_lazy path env).mdl_type) ~path
      with Not_found ->
        (*Location.prerr_warning Location.none
          (Warnings.No_cmi_file (Path.name path));*)
        mty
      end
  | mty, Some path ->
      !strengthen ~aliasable:true env mty path
  | _ -> mty

(* Given a signature and a root path, prefix all idents in the signature
   by the root path and build the corresponding substitution. *)

let prefix_idents root prefixing_sub sg =
  let open Subst.Lazy in
  let rec prefix_idents root items_and_paths prefixing_sub =
    function
    | [] -> (List.rev items_and_paths, prefixing_sub)
    | SigL_value(id, _, _) as item :: rem ->
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((item, p) :: items_and_paths) prefixing_sub rem
    | SigL_type(id, td, rs, vis) :: rem ->
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((SigL_type(id, td, rs, vis), p) :: items_and_paths)
        (Subst.add_type id p prefixing_sub)
        rem
    | SigL_typext(id, ec, es, vis) :: rem ->
      let p = Pdot(root, Ident.name id) in
      (* we extend the substitution in case of an inlined record *)
      prefix_idents root
        ((SigL_typext(id, ec, es, vis), p) :: items_and_paths)
        (Subst.add_type id p prefixing_sub)
        rem
    | SigL_module(id, pres, md, rs, vis) :: rem ->
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((SigL_module(id, pres, md, rs, vis), p) :: items_and_paths)
        (Subst.add_module id p prefixing_sub)
        rem
    | SigL_modtype(id, mtd, vis) :: rem ->
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((SigL_modtype(id, mtd, vis), p) :: items_and_paths)
        (Subst.add_modtype id (Mty_ident p) prefixing_sub)
        rem
    | SigL_class(id, cd, rs, vis) :: rem ->
      (* pretend this is a type, cf. PR#6650 *)
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((SigL_class(id, cd, rs, vis), p) :: items_and_paths)
        (Subst.add_type id p prefixing_sub)
        rem
    | SigL_class_type(id, ctd, rs, vis) :: rem ->
      let p = Pdot(root, Ident.name id) in
      prefix_idents root
        ((SigL_class_type(id, ctd, rs, vis), p) :: items_and_paths)
        (Subst.add_type id p prefixing_sub)
        rem
  in
  let sg = Subst.Lazy.force_signature_once sg in
  prefix_idents root [] prefixing_sub sg

(* Compute structure descriptions *)

let add_to_tbl id decl tbl =
  let decls = try NameMap.find id tbl with Not_found -> [] in
  NameMap.add id (decl :: decls) tbl

let value_declaration_address (_ : t) id decl =
  match decl.val_kind with
  | Val_prim _ -> Lazy_backtrack.create_failed Not_found
  | _ -> Lazy_backtrack.create_forced (Aident id)

let extension_declaration_address (_ : t) id (_ : extension_constructor) =
  Lazy_backtrack.create_forced (Aident id)

let class_declaration_address (_ : t) id (_ : class_declaration) =
  Lazy_backtrack.create_forced (Aident id)

let module_declaration_address env id presence md =
  match presence with
  | Mp_absent -> begin
      let open Subst.Lazy in
      match md.mdl_type with
      | MtyL_alias path -> Lazy_backtrack.create (ModAlias {env; path})
      | _ -> assert false
    end
  | Mp_present ->
      Lazy_backtrack.create_forced (Aident id)

let is_identchar c =
  (* This should be kept in sync with the [identchar_latin1] character class
     in [lexer.mll] *)
  match c with
  | 'A'..'Z' | 'a'..'z' | '_' | '\192'..'\214'
  | '\216'..'\246' | '\248'..'\255' | '\'' | '0'..'9' ->
    true
  | _ ->
    false

let rec components_of_module_maker
          {cm_env; cm_prefixing_subst;
           cm_path; cm_addr; cm_mty; cm_shape} : _ result =
  match scrape_alias cm_env cm_mty with
    MtyL_signature sg ->
      let c =
        { comp_values = NameMap.empty;
          comp_constrs = NameMap.empty;
          comp_labels = NameMap.empty; comp_types = NameMap.empty;
          comp_modules = NameMap.empty; comp_modtypes = NameMap.empty;
          comp_classes = NameMap.empty; comp_cltypes = NameMap.empty }
      in
      let items_and_paths, sub =
        prefix_idents cm_path cm_prefixing_subst sg
      in
      let env = ref cm_env in
      let pos = ref 0 in
      let next_address () =
        let addr : address_unforced =
          Projection { parent = cm_addr; pos = !pos }
        in
        incr pos;
        Lazy_backtrack.create addr
      in
      List.iter (fun ((item : Subst.Lazy.signature_item), path) ->
        match item with
          SigL_value(id, decl, _) ->
            let decl' = Subst.value_description sub decl in
            let addr =
              match decl.val_kind with
              | Val_prim _ -> Lazy_backtrack.create_failed Not_found
              | _ -> next_address ()
            in
            let vda_shape = Shape.proj cm_shape (Shape.Item.value id) in
            let vda =
              { vda_description = decl'; vda_address = addr; vda_shape }
            in
            c.comp_values <- NameMap.add (Ident.name id) vda c.comp_values;
        | SigL_type(id, decl, _, _) ->
            let final_decl = Subst.type_declaration sub decl in
            Btype.set_static_row_name final_decl
              (Subst.type_path sub (Path.Pident id));
            let descrs =
              match decl.type_kind with
              | Type_variant (_,repr) ->
                  let cstrs = List.map snd
                    (Datarepr.constructors_of_type path final_decl
                        ~current_unit:(get_unit_name ()))
                  in
                  List.iter
                    (fun descr ->
                      let cda_shape = Shape.leaf descr.cstr_uid in
                      let cda = {
                        cda_description = descr;
                        cda_address = None;
                        cda_shape }
                      in
                      c.comp_constrs <-
                        add_to_tbl descr.cstr_name cda c.comp_constrs
                    ) cstrs;
                 Type_variant (cstrs, repr)
              | Type_record (_, repr) ->
                  let lbls = List.map snd
                    (Datarepr.labels_of_type path final_decl)
                  in
                  List.iter
                    (fun descr ->
                      c.comp_labels <-
                        add_to_tbl descr.lbl_name descr c.comp_labels)
                    lbls;
                  Type_record (lbls, repr)
              | Type_abstract -> Type_abstract
              | Type_open -> Type_open
            in
            let shape = Shape.proj cm_shape (Shape.Item.type_ id) in
            let tda =
              { tda_declaration = final_decl;
                tda_descriptions = descrs;
                tda_shape = shape; }
            in
            c.comp_types <- NameMap.add (Ident.name id) tda c.comp_types;
            env := store_type_infos ~tda_shape:shape id decl !env
        | SigL_typext(id, ext, _, _) ->
            let ext' = Subst.extension_constructor sub ext in
            let descr =
              Datarepr.extension_descr ~current_unit:(get_unit_name ()) path
                ext'
            in
            let addr = next_address () in
            let cda_shape =
              Shape.proj cm_shape (Shape.Item.extension_constructor id)
            in
            let cda =
              { cda_description = descr; cda_address = Some addr; cda_shape }
            in
            c.comp_constrs <- add_to_tbl (Ident.name id) cda c.comp_constrs
        | SigL_module(id, pres, md, _, _) ->
            let md' =
              (* The prefixed items get the same scope as [cm_path], which is
                 the prefix. *)
              Subst.Lazy.module_decl
                (Subst.Rescope (Path.scope cm_path)) sub md
            in
            let addr =
              match pres with
              | Mp_absent -> begin
                  match md.mdl_type with
                  | MtyL_alias path ->
                      Lazy_backtrack.create (ModAlias {env = !env; path})
                  | _ -> assert false
                end
              | Mp_present -> next_address ()
            in
            let alerts =
              Builtin_attributes.alerts_of_attrs md.mdl_attributes
            in
            let shape = Shape.proj cm_shape (Shape.Item.module_ id) in
            let comps =
              components_of_module ~alerts ~uid:md.mdl_uid !env
                sub path addr md.mdl_type shape
            in
            let mda =
              { mda_declaration = md';
                mda_components = comps;
                mda_address = addr;
                mda_shape = shape; }
            in
            c.comp_modules <-
              NameMap.add (Ident.name id) mda c.comp_modules;
            env :=
              store_module ~update_summary:false ~check:None
                id addr pres md shape !env
        | SigL_modtype(id, decl, _) ->
            let final_decl =
              (* The prefixed items get the same scope as [cm_path], which is
                 the prefix. *)
              Subst.Lazy.modtype_decl (Rescope (Path.scope cm_path))
                sub decl
            in
            let shape = Shape.proj cm_shape (Shape.Item.module_type id) in
            let mtda =
              { mtda_declaration = final_decl;
                mtda_shape = shape; }
            in
            c.comp_modtypes <-
              NameMap.add (Ident.name id) mtda c.comp_modtypes;
            env := store_modtype ~update_summary:false id decl shape !env
        | SigL_class(id, decl, _, _) ->
            let decl' = Subst.class_declaration sub decl in
            let addr = next_address () in
            let shape = Shape.proj cm_shape (Shape.Item.class_ id) in
            let clda =
              { clda_declaration = decl';
                clda_address = addr;
                clda_shape = shape; }
            in
            c.comp_classes <- NameMap.add (Ident.name id) clda c.comp_classes
        | SigL_class_type(id, decl, _, _) ->
            let decl' = Subst.cltype_declaration sub decl in
            let shape = Shape.proj cm_shape (Shape.Item.class_type id) in
            let cltda = { cltda_declaration = decl'; cltda_shape = shape } in
            c.comp_cltypes <-
              NameMap.add (Ident.name id) cltda c.comp_cltypes)
        items_and_paths;
        Ok (Structure_comps c)
  | MtyL_functor(arg, ty_res) ->
      let sub = cm_prefixing_subst in
      let scoping = Subst.Rescope (Path.scope cm_path) in
      let open Subst.Lazy in
        Ok (Functor_comps {
          (* fcomp_arg and fcomp_res must be prefixed eagerly, because
             they are interpreted in the outer environment *)
          fcomp_arg =
            (match arg with
            | Unit -> Unit
            | Named (param, ty_arg) ->
              Named (param, force_modtype (modtype scoping sub ty_arg)));
          fcomp_res = force_modtype (modtype scoping sub ty_res);
          fcomp_shape = cm_shape;
          fcomp_cache = Hashtbl.create 17;
          fcomp_subst_cache = Hashtbl.create 17 })
  | MtyL_ident _ -> Error No_components_abstract
  | MtyL_alias p -> Error (No_components_alias p)

(* Insertion of bindings by identifier + path *)

and check_usage loc id uid warn tbl =
  if not loc.Location.loc_ghost &&
     Uid.for_actual_declaration uid &&
     Warnings.is_active (warn "")
  then begin
    let name = Ident.name id in
    if Types.Uid.Tbl.mem tbl uid then ()
    else let used = ref false in
    Types.Uid.Tbl.add tbl uid (fun () -> used := true);
    if not (name = "" || name.[0] = '_' || name.[0] = '#')
    then
      !add_delayed_check_forward
        (fun () -> if not !used then Location.prerr_warning loc (warn name))
  end;

and check_value_name name loc =
  (* Note: we could also check here general validity of the
     identifier, to protect against bad identifiers forged by -pp or
     -ppx preprocessors. *)
  if String.length name > 0 && not (is_identchar name.[0]) then
    for i = 1 to String.length name - 1 do
      if name.[i] = '#' then
        error (Illegal_value_name(loc, name))
    done

and store_value ?check id addr decl shape env =
  check_value_name (Ident.name id) decl.val_loc;
  Option.iter
    (fun f -> check_usage decl.val_loc id decl.val_uid f !value_declarations)
    check;
  let vda =
    { vda_description = decl;
      vda_address = addr;
      vda_shape = shape }
  in
  { env with
    values = IdTbl.add id (Val_bound vda) env.values;
    summary = Env_value(env.summary, id, decl) }

and store_constructor ~check type_decl type_id cstr_id cstr env =
  if check && not type_decl.type_loc.Location.loc_ghost
     && Warnings.is_active (Warnings.Unused_constructor ("", Unused))
  then begin
    let ty_name = Ident.name type_id in
    let name = cstr.cstr_name in
    let loc = cstr.cstr_loc in
    let k = cstr.cstr_uid in
    let priv = type_decl.type_private in
    if not (Types.Uid.Tbl.mem !used_constructors k) then begin
      let used = constructor_usages () in
      Types.Uid.Tbl.add !used_constructors k
        (add_constructor_usage used);
      if not (ty_name = "" || ty_name.[0] = '_')
      then
        !add_delayed_check_forward
          (fun () ->
            Option.iter
              (fun complaint ->
                 if not (is_in_signature env) then
                   Location.prerr_warning loc
                     (Warnings.Unused_constructor(name, complaint)))
              (constructor_usage_complaint ~rebind:false priv used));
    end;
  end;
  let cda_shape = Shape.leaf cstr.cstr_uid in
  { env with
    constrs =
      TycompTbl.add cstr_id
        { cda_description = cstr; cda_address = None; cda_shape } env.constrs;
  }

and store_label ~check type_decl type_id lbl_id lbl env =
  if check && not type_decl.type_loc.Location.loc_ghost
     && Warnings.is_active (Warnings.Unused_field ("", Unused))
  then begin
    let ty_name = Ident.name type_id in
    let priv = type_decl.type_private in
    let name = lbl.lbl_name in
    let loc = lbl.lbl_loc in
    let mut = lbl.lbl_mut in
    let k = lbl.lbl_uid in
    if not (Types.Uid.Tbl.mem !used_labels k) then
      let used = label_usages () in
      Types.Uid.Tbl.add !used_labels k
        (add_label_usage used);
      if not (ty_name = "" || ty_name.[0] = '_' || name.[0] = '_')
      then !add_delayed_check_forward
          (fun () ->
            Option.iter
              (fun complaint ->
                 if not (is_in_signature env) then
                   Location.prerr_warning
                     loc (Warnings.Unused_field(name, complaint)))
              (label_usage_complaint priv mut used))
  end;
  { env with
    labels = TycompTbl.add lbl_id lbl env.labels;
  }

and store_type ~check id info shape env =
  let loc = info.type_loc in
  if check then
    check_usage loc id info.type_uid
      (fun s -> Warnings.Unused_type_declaration s)
      !type_declarations;
  let descrs, env =
    let path = Pident id in
    match info.type_kind with
    | Type_variant (_,repr) ->
        let constructors = Datarepr.constructors_of_type path info
                            ~current_unit:(get_unit_name ())
        in
        Type_variant (List.map snd constructors, repr),
        List.fold_left
          (fun env (cstr_id, cstr) ->
            store_constructor ~check info id cstr_id cstr env)
          env constructors
    | Type_record (_, repr) ->
        let labels = Datarepr.labels_of_type path info in
        Type_record (List.map snd labels, repr),
        List.fold_left
          (fun env (lbl_id, lbl) ->
            store_label ~check info id lbl_id lbl env)
          env labels
    | Type_abstract -> Type_abstract, env
    | Type_open -> Type_open, env
  in
  let tda =
    { tda_declaration = info;
      tda_descriptions = descrs;
      tda_shape = shape }
  in
  { env with
    types = IdTbl.add id tda env.types;
    summary = Env_type(env.summary, id, info) }

and store_type_infos ~tda_shape id info env =
  (* Simplified version of store_type that doesn't compute and store
     constructor and label infos, but simply record the arity and
     manifest-ness of the type.  Used in components_of_module to
     keep track of type abbreviations (e.g. type t = float) in the
     computation of label representations. *)
  let tda =
    {
      tda_declaration = info;
      tda_descriptions = Type_abstract;
      tda_shape
    }
  in
  { env with
    types = IdTbl.add id tda env.types;
    summary = Env_type(env.summary, id, info) }

and store_extension ~check ~rebind id addr ext shape env =
  let loc = ext.ext_loc in
  let cstr =
    Datarepr.extension_descr ~current_unit:(get_unit_name ()) (Pident id) ext
  in
  let cda =
    { cda_description = cstr;
      cda_address = Some addr;
      cda_shape = shape }
  in
  if check && not loc.Location.loc_ghost &&
    Warnings.is_active (Warnings.Unused_extension ("", false, Unused))
  then begin
    let priv = ext.ext_private in
    let is_exception = Path.same ext.ext_type_path Predef.path_exn in
    let name = cstr.cstr_name in
    let k = cstr.cstr_uid in
    if not (Types.Uid.Tbl.mem !used_constructors k) then begin
      let used = constructor_usages () in
      Types.Uid.Tbl.add !used_constructors k
        (add_constructor_usage used);
      !add_delayed_check_forward
         (fun () ->
           Option.iter
             (fun complaint ->
                if not (is_in_signature env) then
                  Location.prerr_warning loc
                    (Warnings.Unused_extension
                       (name, is_exception, complaint)))
             (constructor_usage_complaint ~rebind priv used))
    end;
  end;
  { env with
    constrs = TycompTbl.add id cda env.constrs;
    summary = Env_extension(env.summary, id, ext) }

and store_module ?(update_summary=true) ~check
                 id addr presence md shape env =
  let open Subst.Lazy in
  let loc = md.mdl_loc in
  Option.iter
    (fun f -> check_usage loc id md.mdl_uid f !module_declarations) check;
  let alerts = Builtin_attributes.alerts_of_attrs md.mdl_attributes in
  let comps =
    components_of_module ~alerts ~uid:md.mdl_uid
      env Subst.identity (Pident id) addr md.mdl_type shape
  in
  let mda =
    { mda_declaration = md;
      mda_components = comps;
      mda_address = addr;
      mda_shape = shape }
  in
  let summary =
    if not update_summary then env.summary
    else Env_module (env.summary, id, presence, force_module_decl md) in
  { env with
    modules = IdTbl.add id (Mod_local mda) env.modules;
    summary }

and store_modtype ?(update_summary=true) id info shape env =
  let mtda = { mtda_declaration = info; mtda_shape = shape } in
  let summary =
    if not update_summary then env.summary
    else Env_modtype (env.summary, id, Subst.Lazy.force_modtype_decl info) in
  { env with
    modtypes = IdTbl.add id mtda env.modtypes;
    summary }

and store_class id addr desc shape env =
  let clda =
    { clda_declaration = desc;
      clda_address = addr;
      clda_shape = shape; }
  in
  { env with
    classes = IdTbl.add id clda env.classes;
    summary = Env_class(env.summary, id, desc) }

and store_cltype id desc shape env =
  let cltda = { cltda_declaration = desc; cltda_shape = shape } in
  { env with
    cltypes = IdTbl.add id cltda env.cltypes;
    summary = Env_cltype(env.summary, id, desc) }

let scrape_alias env mty = scrape_alias env mty

(* Compute the components of a functor application in a path. *)

let components_of_functor_appl ~loc ~f_path ~f_comp ~arg env =
  try
    let c = Hashtbl.find f_comp.fcomp_cache arg in
    c
  with Not_found ->
    let p = Papply(f_path, arg) in
    let sub =
      match f_comp.fcomp_arg with
      | Unit
      | Named (None, _) -> Subst.identity
      | Named (Some param, _) -> Subst.add_module param arg Subst.identity
    in
    (* we have to apply eagerly instead of passing sub to [components_of_module]
       because of the call to [check_well_formed_module]. *)
    let mty = Subst.modtype (Rescope (Path.scope p)) sub f_comp.fcomp_res in
    let addr = Lazy_backtrack.create_failed Not_found in
    !check_well_formed_module env loc
      ("the signature of " ^ Path.name p) mty;
    let shape_arg =
      shape_of_path ~namespace:Shape.Sig_component_kind.Module env arg
    in
    let shape = Shape.app f_comp.fcomp_shape ~arg:shape_arg in
    let comps =
      components_of_module ~alerts:Misc.Stdlib.String.Map.empty
        ~uid:Uid.internal_not_actually_unique
        (*???*)
        env Subst.identity p addr (Subst.Lazy.of_modtype mty) shape
    in
    Hashtbl.add f_comp.fcomp_cache arg comps;
    comps

(* Define forward functions *)

let _ =
  components_of_functor_appl' := components_of_functor_appl;
  components_of_module_maker' := components_of_module_maker

(* Insertion of bindings by identifier *)

let add_functor_arg id env =
  {env with
   functor_args = Ident.add id () env.functor_args;
   summary = Env_functor_arg (env.summary, id)}

let add_value ?check ?shape id desc env =
  let addr = value_declaration_address env id desc in
  let shape = shape_or_leaf desc.val_uid shape in
  store_value ?check id addr desc shape env

let add_type ~check ?shape id info env =
  let shape = shape_or_leaf info.type_uid shape in
  store_type ~check id info shape env

and add_extension ~check ?shape ~rebind id ext env =
  let addr = extension_declaration_address env id ext in
  let shape = shape_or_leaf ext.ext_uid shape in
  store_extension ~check ~rebind id addr ext shape env

and add_module_declaration ?(arg=false) ?shape ~check id presence md env =
  let check =
    if not check then
      None
    else if arg && is_in_signature env then
      Some (fun s -> Warnings.Unused_functor_parameter s)
    else
      Some (fun s -> Warnings.Unused_module s)
  in
  let md = Subst.Lazy.of_module_decl md in
  let addr = module_declaration_address env id presence md in
  let shape = shape_or_leaf md.mdl_uid shape in
  let env = store_module ~check id addr presence md shape env in
  if arg then add_functor_arg id env else env

and add_module_declaration_lazy ~update_summary id presence md env =
  let addr = module_declaration_address env id presence md in
  let shape = Shape.leaf md.Subst.Lazy.mdl_uid in
  let env =
    store_module ~update_summary ~check:None id addr presence md shape env
  in
  env

and add_modtype ?shape id info env =
  let shape = shape_or_leaf info.mtd_uid shape in
  store_modtype id (Subst.Lazy.of_modtype_decl info) shape env

and add_modtype_lazy ~update_summary id info env =
  let shape = Shape.leaf info.Subst.Lazy.mtdl_uid in
  store_modtype ~update_summary id info shape env

and add_class ?shape id ty env =
  let addr = class_declaration_address env id ty in
  let shape = shape_or_leaf ty.cty_uid shape in
  store_class id addr ty shape env

and add_cltype ?shape id ty env =
  let shape = shape_or_leaf ty.clty_uid shape in
  store_cltype id ty shape env

let add_module ?arg ?shape id presence mty env =
  add_module_declaration ~check:false ?arg ?shape id presence (md mty) env

let add_local_type path info env =
  { env with
    local_constraints = Path.Map.add path info env.local_constraints }

(* Non-lazy version of scrape_alias *)
let scrape_alias t mty =
  mty |> Subst.Lazy.of_modtype |> scrape_alias t |> Subst.Lazy.force_modtype

(* Insertion of bindings by name *)

let enter_value ?check name desc env =
  let id = Ident.create_local name in
  let addr = value_declaration_address env id desc in
  let env = store_value ?check id addr desc (Shape.leaf desc.val_uid) env in
  (id, env)

let enter_type ~scope name info env =
  let id = Ident.create_scoped ~scope name in
  let env = store_type ~check:true id info (Shape.leaf info.type_uid) env in
  (id, env)

let enter_extension ~scope ~rebind name ext env =
  let id = Ident.create_scoped ~scope name in
  let addr = extension_declaration_address env id ext in
  let shape = Shape.leaf ext.ext_uid in
  let env = store_extension ~check:true ~rebind id addr ext shape env in
  (id, env)

let enter_module_declaration ~scope ?arg ?shape s presence md env =
  let id = Ident.create_scoped ~scope s in
  (id, add_module_declaration ?arg ?shape ~check:true id presence md env)

let enter_modtype ~scope name mtd env =
  let id = Ident.create_scoped ~scope name in
  let shape = Shape.leaf mtd.mtd_uid in
  let env = store_modtype id (Subst.Lazy.of_modtype_decl mtd) shape env in
  (id, env)

let enter_class ~scope name desc env =
  let id = Ident.create_scoped ~scope name in
  let addr = class_declaration_address env id desc in
  let env = store_class id addr desc (Shape.leaf desc.cty_uid) env in
  (id, env)

let enter_cltype ~scope name desc env =
  let id = Ident.create_scoped ~scope name in
  let env = store_cltype id desc (Shape.leaf desc.clty_uid) env in
  (id, env)

let enter_module ~scope ?arg s presence mty env =
  enter_module_declaration ~scope ?arg s presence (md mty) env

(* Insertion of all components of a signature *)

let add_item (map, mod_shape) comp env =
  let proj_shape item =
    match mod_shape with
    | None -> map, None
    | Some mod_shape ->
        let shape = Shape.proj mod_shape item in
        Shape.Map.add map item shape, Some shape
  in
  match comp with
  | Sig_value(id, decl, _) ->
      let map, shape = proj_shape (Shape.Item.value id) in
      map, add_value ?shape id decl env
  | Sig_type(id, decl, _, _) ->
      let map, shape = proj_shape (Shape.Item.type_ id) in
      map, add_type ~check:false ?shape id decl env
  | Sig_typext(id, ext, _, _) ->
      let map, shape = proj_shape (Shape.Item.extension_constructor id) in
      map, add_extension ~check:false ?shape ~rebind:false id ext env
  | Sig_module(id, presence, md, _, _) ->
      let map, shape = proj_shape (Shape.Item.module_ id) in
      map, add_module_declaration ~check:false ?shape id presence md env
  | Sig_modtype(id, decl, _)  ->
      let map, shape = proj_shape (Shape.Item.module_type id) in
      map, add_modtype ?shape id decl env
  | Sig_class(id, decl, _, _) ->
      let map, shape = proj_shape (Shape.Item.class_ id) in
      map, add_class ?shape id decl env
  | Sig_class_type(id, decl, _, _) ->
      let map, shape = proj_shape (Shape.Item.class_type id) in
      map, add_cltype ?shape id decl env

let rec add_signature (map, mod_shape) sg env =
  match sg with
      [] -> map, env
  | comp :: rem ->
      let map, env = add_item (map, mod_shape) comp env in
      add_signature (map, mod_shape) rem env

let enter_signature_and_shape ~scope ~parent_shape mod_shape sg env =
  let sg = Subst.signature (Rescope scope) Subst.identity sg in
  let shape, env = add_signature (parent_shape, mod_shape) sg env in
  sg, shape, env

let enter_signature ?mod_shape ~scope sg env =
  let sg, _, env =
    enter_signature_and_shape ~scope ~parent_shape:Shape.Map.empty
      mod_shape sg env
  in
  sg, env

let enter_signature_and_shape ~scope ~parent_shape mod_shape sg env =
  enter_signature_and_shape ~scope ~parent_shape (Some mod_shape) sg env

let add_value = add_value ?shape:None
let add_type = add_type ?shape:None
let add_extension = add_extension ?shape:None
let add_class = add_class ?shape:None
let add_cltype = add_cltype ?shape:None
let add_modtype = add_modtype ?shape:None
let add_signature sg env =
  let _, env = add_signature (Shape.Map.empty, None) sg env in
  env

(* Add "unbound" bindings *)

let enter_unbound_value name reason env =
  let id = Ident.create_local name in
  { env with
    values = IdTbl.add id (Val_unbound reason) env.values;
    summary = Env_value_unbound(env.summary, name, reason) }

let enter_unbound_module name reason env =
  let id = Ident.create_local name in
  { env with
    modules = IdTbl.add id (Mod_unbound reason) env.modules;
    summary = Env_module_unbound(env.summary, name, reason) }

(* Open a signature path *)

let add_components slot root env0 comps =
  let add_l w comps env0 =
    TycompTbl.add_open slot w root comps env0
  in
  let add w comps env0 = IdTbl.add_open slot w root comps env0 in
  let constrs =
    add_l (fun x -> `Constructor x) comps.comp_constrs env0.constrs
  in
  let labels =
    add_l (fun x -> `Label x) comps.comp_labels env0.labels
  in
  let values =
    add (fun x -> `Value x) comps.comp_values env0.values
  in
  let types =
    add (fun x -> `Type x) comps.comp_types env0.types
  in
  let modtypes =
    add (fun x -> `Module_type x) comps.comp_modtypes env0.modtypes
  in
  let classes =
    add (fun x -> `Class x) comps.comp_classes env0.classes
  in
  let cltypes =
    add (fun x -> `Class_type x) comps.comp_cltypes env0.cltypes
  in
  let modules =
    add (fun x -> `Module x) comps.comp_modules env0.modules
  in
  { env0 with
    summary = Env_open(env0.summary, root);
    constrs;
    labels;
    values;
    types;
    modtypes;
    classes;
    cltypes;
    modules;
  }

let open_signature slot root env0 : (_,_) result =
  match get_components_res (find_module_components root env0) with
  | Error _ -> Error `Not_found
  | exception Not_found -> Error `Not_found
  | Ok (Functor_comps _) -> Error `Functor
  | Ok (Structure_comps comps) ->
    Ok (add_components slot root env0 comps)

let remove_last_open root env0 =
  let rec filter_summary summary =
    match summary with
      Env_empty -> raise Exit
    | Env_open (s, p) ->
        if Path.same p root then s else raise Exit
    | Env_value _
    | Env_type _
    | Env_extension _
    | Env_module _
    | Env_modtype _
    | Env_class _
    | Env_cltype _
    | Env_functor_arg _
    | Env_constraints _
    | Env_persistent _
    | Env_copy_types _
    | Env_value_unbound _
    | Env_module_unbound _ ->
        map_summary filter_summary summary
  in
  match filter_summary env0.summary with
  | summary ->
      let rem_l tbl = TycompTbl.remove_last_open root tbl
      and rem tbl = IdTbl.remove_last_open root tbl in
      Some { env0 with
             summary;
             constrs = rem_l env0.constrs;
             labels = rem_l env0.labels;
             values = rem env0.values;
             types = rem env0.types;
             modtypes = rem env0.modtypes;
             classes = rem env0.classes;
             cltypes = rem env0.cltypes;
             modules = rem env0.modules; }
  | exception Exit ->
      None

(* Open a signature from a file *)

let open_pers_signature name env =
  match open_signature None (Pident(Ident.create_persistent name)) env with
  | (Ok _ | Error `Not_found as res) -> res
  | Error `Functor -> assert false
        (* a compilation unit cannot refer to a functor *)

let open_signature
    ?(used_slot = ref false)
    ?(loc = Location.none) ?(toplevel = false)
    ovf root env =
  let unused =
    match ovf with
    | Asttypes.Fresh -> Warnings.Unused_open (Path.name root)
    | Asttypes.Override -> Warnings.Unused_open_bang (Path.name root)
  in
  let warn_unused =
    Warnings.is_active unused
  and warn_shadow_id =
    Warnings.is_active (Warnings.Open_shadow_identifier ("", ""))
  and warn_shadow_lc =
    Warnings.is_active (Warnings.Open_shadow_label_constructor ("",""))
  in
  if not toplevel && not loc.Location.loc_ghost
     && (warn_unused || warn_shadow_id || warn_shadow_lc)
  then begin
    let used = used_slot in
    if warn_unused then
      !add_delayed_check_forward
        (fun () ->
           if not !used then begin
             used := true;
             Location.prerr_warning loc unused
           end
        );
    let shadowed = ref [] in
    let slot s b =
      begin match check_shadowing env b with
      | Some kind when
          ovf = Asttypes.Fresh && not (List.mem (kind, s) !shadowed) ->
          shadowed := (kind, s) :: !shadowed;
          let w =
            match kind with
            | "label" | "constructor" ->
                Warnings.Open_shadow_label_constructor (kind, s)
            | _ -> Warnings.Open_shadow_identifier (kind, s)
          in
          Location.prerr_warning loc w
      | _ -> ()
      end;
      used := true
    in
    open_signature (Some slot) root env
  end
  else open_signature None root env

(* Read a signature from a file *)
let read_signature modname filename =
  let mda = read_pers_mod modname filename in
  let md = Subst.Lazy.force_module_decl mda.mda_declaration in
  match md.md_type with
  | Mty_signature sg -> sg
  | Mty_ident _ | Mty_functor _ | Mty_alias _ -> assert false

let is_identchar_latin1 = function
  | 'A'..'Z' | 'a'..'z' | '_' | '\192'..'\214' | '\216'..'\246'
  | '\248'..'\255' | '\'' | '0'..'9' -> true
  | _ -> false

let unit_name_of_filename fn =
  match Filename.extension fn with
  | ".cmi" -> begin
      let unit =
        String.capitalize_ascii (Filename.remove_extension fn)
      in
      if String.for_all is_identchar_latin1 unit then
        Some unit
      else
        None
    end
  | _ -> None

let persistent_structures_of_dir dir =
  Load_path.Dir.files dir
  |> List.to_seq
  |> Seq.filter_map unit_name_of_filename
  |> String.Set.of_seq

(* Save a signature to a file *)
let save_signature_with_transform cmi_transform ~alerts sg modname filename =
  Btype.cleanup_abbrev ();
  Subst.reset_for_saving ();
  let sg = Subst.signature Make_local (Subst.for_saving Subst.identity) sg in
  let cmi =
    Persistent_env.make_cmi !persistent_env modname sg alerts
    |> cmi_transform in
  let pm = save_sign_of_cmi
      { Persistent_env.Persistent_signature.cmi; filename } in
  Persistent_env.save_cmi !persistent_env
    { Persistent_env.Persistent_signature.filename; cmi } pm;
  cmi

let save_signature ~alerts sg modname filename =
  save_signature_with_transform (fun cmi -> cmi)
    ~alerts sg modname filename

let save_signature_with_imports ~alerts sg modname filename imports =
  let with_imports cmi = { cmi with cmi_crcs = imports } in
  save_signature_with_transform with_imports
    ~alerts sg modname filename

(* Make the initial environment *)
let (initial_safe_string, initial_unsafe_string) =
  Predef.build_initial_env
    (add_type ~check:false)
    (add_extension ~check:false ~rebind:false)
    empty

(* Tracking usage *)

let mark_module_used uid =
  match Types.Uid.Tbl.find !module_declarations uid with
  | mark -> mark ()
  | exception Not_found -> ()

let mark_modtype_used _uid = ()

let mark_value_used uid =
  match Types.Uid.Tbl.find !value_declarations uid with
  | mark -> mark ()
  | exception Not_found -> ()

let mark_type_used uid =
  match Types.Uid.Tbl.find !type_declarations uid with
  | mark -> mark ()
  | exception Not_found -> ()

let mark_type_path_used env path =
  match find_type path env with
  | decl -> mark_type_used decl.type_uid
  | exception Not_found -> ()

let mark_constructor_used usage cd =
  match Types.Uid.Tbl.find !used_constructors cd.cd_uid with
  | mark -> mark usage
  | exception Not_found -> ()

let mark_extension_used usage ext =
  match Types.Uid.Tbl.find !used_constructors ext.ext_uid with
  | mark -> mark usage
  | exception Not_found -> ()

let mark_label_used usage ld =
  match Types.Uid.Tbl.find !used_labels ld.ld_uid with
  | mark -> mark usage
  | exception Not_found -> ()

let mark_constructor_description_used usage env cstr =
  let ty_path = Btype.cstr_type_path cstr in
  mark_type_path_used env ty_path;
  match Types.Uid.Tbl.find !used_constructors cstr.cstr_uid with
  | mark -> mark usage
  | exception Not_found -> ()

let mark_label_description_used usage env lbl =
  let ty_path =
    match get_desc lbl.lbl_res with
    | Tconstr(path, _, _) -> path
    | _ -> assert false
  in
  mark_type_path_used env ty_path;
  match Types.Uid.Tbl.find !used_labels lbl.lbl_uid with
  | mark -> mark usage
  | exception Not_found -> ()

let mark_class_used uid =
  match Types.Uid.Tbl.find !type_declarations uid with
  | mark -> mark ()
  | exception Not_found -> ()

let mark_cltype_used uid =
  match Types.Uid.Tbl.find !type_declarations uid with
  | mark -> mark ()
  | exception Not_found -> ()

let set_value_used_callback vd callback =
  Types.Uid.Tbl.add !value_declarations vd.val_uid callback

let set_type_used_callback td callback =
  if Uid.for_actual_declaration td.type_uid then
    let old =
      try Types.Uid.Tbl.find !type_declarations td.type_uid
      with Not_found -> ignore
    in
    Types.Uid.Tbl.replace !type_declarations td.type_uid
      (fun () -> callback old)

(* Lookup by name *)

let may_lookup_error report_errors loc env err =
  if report_errors then lookup_error loc env err
  else raise Not_found

let report_module_unbound ~errors ~loc env reason =
  match reason with
  | Mod_unbound_illegal_recursion ->
      (* see #5965 *)
    may_lookup_error errors loc env Illegal_reference_to_recursive_module

let report_value_unbound ~errors ~loc env reason lid =
  match reason with
  | Val_unbound_instance_variable ->
      may_lookup_error errors loc env (Masked_instance_variable lid)
  | Val_unbound_self ->
      may_lookup_error errors loc env (Masked_self_variable lid)
  | Val_unbound_ancestor ->
      may_lookup_error errors loc env (Masked_ancestor_variable lid)
  | Val_unbound_ghost_recursive rloc ->
      let show_hint =
        (* Only display the "missing rec" hint for non-ghost code *)
        not loc.Location.loc_ghost
        && not rloc.Location.loc_ghost
      in
      let hint =
        if show_hint then Missing_rec rloc else No_hint
      in
      may_lookup_error errors loc env (Unbound_value(lid, hint))

let use_module ~use ~loc path mda =
  if use then begin
    let comps = mda.mda_components in
    mark_module_used comps.uid;
    Misc.Stdlib.String.Map.iter
      (fun kind message ->
         let message = if message = "" then "" else "\n" ^ message in
         Location.alert ~kind loc
           (Printf.sprintf "module %s%s" (Path.name path) message)
      )
      comps.alerts
  end

let use_value ~use ~loc path vda =
  if use then begin
    let desc = vda.vda_description in
    mark_value_used desc.val_uid;
    Builtin_attributes.check_alerts loc desc.val_attributes
      (Path.name path)
  end

let use_type ~use ~loc path tda =
  if use then begin
    let decl = tda.tda_declaration in
    mark_type_used decl.type_uid;
    Builtin_attributes.check_alerts loc decl.type_attributes
      (Path.name path)
  end

let use_modtype ~use ~loc path desc =
  let open Subst.Lazy in
  if use then begin
    mark_modtype_used desc.mtdl_uid;
    Builtin_attributes.check_alerts loc desc.mtdl_attributes
      (Path.name path)
  end

let use_class ~use ~loc path clda =
  if use then begin
    let desc = clda.clda_declaration in
    mark_class_used desc.cty_uid;
    Builtin_attributes.check_alerts loc desc.cty_attributes
      (Path.name path)
  end

let use_cltype ~use ~loc path desc =
  if use then begin
    mark_cltype_used desc.clty_uid;
    Builtin_attributes.check_alerts loc desc.clty_attributes
      (Path.name path)
  end

let use_label ~use ~loc usage env lbl =
  if use then begin
    mark_label_description_used usage env lbl;
    Builtin_attributes.check_alerts loc lbl.lbl_attributes lbl.lbl_name;
    if is_mutating_label_usage usage then
      Builtin_attributes.check_deprecated_mutable loc lbl.lbl_attributes
        lbl.lbl_name
  end

let use_constructor_desc ~use ~loc usage env cstr =
  if use then begin
    mark_constructor_description_used usage env cstr;
    Builtin_attributes.check_alerts loc cstr.cstr_attributes cstr.cstr_name
  end

let use_constructor ~use ~loc usage env cda =
  use_constructor_desc ~use ~loc usage env cda.cda_description

type _ load =
  | Load : module_data load
  | Don't_load : unit load

let lookup_ident_module (type a) (load : a load) ~errors ~use ~loc s env =
  let path, data =
    match find_name_module ~mark:use s env.modules with
    | res -> res
    | exception Not_found ->
        may_lookup_error errors loc env (Unbound_module (Lident s))
  in
  match data with
  | Mod_local mda -> begin
      use_module ~use ~loc path mda;
      match load with
      | Load -> path, (mda : a)
      | Don't_load -> path, (() : a)
    end
  | Mod_unbound reason ->
      report_module_unbound ~errors ~loc env reason
  | Mod_persistent -> begin
      match load with
      | Don't_load ->
          check_pers_mod ~loc s;
          path, (() : a)
      | Load -> begin
          match find_pers_mod s with
          | mda ->
              use_module ~use ~loc path mda;
              path, (mda : a)
          | exception Not_found ->
              may_lookup_error errors loc env (Unbound_module (Lident s))
        end
    end

let lookup_ident_value ~errors ~use ~loc name env =
  match IdTbl.find_name wrap_value ~mark:use name env.values with
  | (path, Val_bound vda) ->
      use_value ~use ~loc path vda;
      path, vda.vda_description
  | (_, Val_unbound reason) ->
      report_value_unbound ~errors ~loc env reason (Lident name)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_value (Lident name, No_hint))

let lookup_ident_type ~errors ~use ~loc s env =
  match IdTbl.find_name wrap_identity ~mark:use s env.types with
  | (path, data) as res ->
      use_type ~use ~loc path data;
      res
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_type (Lident s))

let lookup_ident_modtype ~errors ~use ~loc s env =
  match IdTbl.find_name wrap_identity ~mark:use s env.modtypes with
  | (path, data) ->
      use_modtype ~use ~loc path data.mtda_declaration;
      (path, data.mtda_declaration)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_modtype (Lident s))

let lookup_ident_class ~errors ~use ~loc s env =
  match IdTbl.find_name wrap_identity ~mark:use s env.classes with
  | (path, clda) ->
      use_class ~use ~loc path clda;
      path, clda.clda_declaration
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_class (Lident s))

let lookup_ident_cltype ~errors ~use ~loc s env =
  match IdTbl.find_name wrap_identity ~mark:use s env.cltypes with
  | path, cltda ->
      use_cltype ~use ~loc path cltda.cltda_declaration;
      path, cltda.cltda_declaration
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_cltype (Lident s))

let lookup_all_ident_labels ~errors ~use ~loc usage s env =
  match TycompTbl.find_all ~mark:use s env.labels with
  | [] -> may_lookup_error errors loc env (Unbound_label (Lident s))
  | lbls -> begin
      List.map
        (fun (lbl, use_fn) ->
           let use_fn () =
             use_label ~use ~loc usage env lbl;
             use_fn ()
           in
           (lbl, use_fn))
        lbls
    end

let lookup_all_ident_constructors ~errors ~use ~loc usage s env =
  match TycompTbl.find_all ~mark:use s env.constrs with
  | [] -> may_lookup_error errors loc env (Unbound_constructor (Lident s))
  | cstrs ->
      List.map
        (fun (cda, use_fn) ->
           let use_fn () =
             use_constructor ~use ~loc usage env cda;
             use_fn ()
           in
           (cda.cda_description, use_fn))
        cstrs

let rec lookup_module_components ~errors ~use ~loc lid env =
  match lid with
  | Lident s ->
      let path, data = lookup_ident_module Load ~errors ~use ~loc s env in
      path, data.mda_components
  | Ldot(l, s) ->
      let path, data = lookup_dot_module ~errors ~use ~loc l s env in
      path, data.mda_components
  | Lapply _ as lid ->
      let f_path, f_comp, arg = lookup_apply ~errors ~use ~loc lid env in
      let comps =
        !components_of_functor_appl' ~loc ~f_path ~f_comp ~arg env in
      Papply (f_path, arg), comps

and lookup_structure_components ~errors ~use ~loc lid env =
  let path, comps = lookup_module_components ~errors ~use ~loc lid env in
  match get_components_res comps with
  | Ok (Structure_comps comps) -> path, comps
  | Ok (Functor_comps _) ->
      may_lookup_error errors loc env (Functor_used_as_structure lid)
  | Error No_components_abstract ->
      may_lookup_error errors loc env (Abstract_used_as_structure lid)
  | Error (No_components_alias p) ->
      may_lookup_error errors loc env (Cannot_scrape_alias(lid, p))

and get_functor_components ~errors ~loc lid env comps =
  match get_components_res comps with
  | Ok (Functor_comps fcomps) -> begin
      match fcomps.fcomp_arg with
      | Unit -> (* PR#7611 *)
          may_lookup_error errors loc env (Generative_used_as_applicative lid)
      | Named (_, arg) -> fcomps, arg
    end
  | Ok (Structure_comps _) ->
      may_lookup_error errors loc env (Structure_used_as_functor lid)
  | Error No_components_abstract ->
      may_lookup_error errors loc env (Abstract_used_as_functor lid)
  | Error (No_components_alias p) ->
      may_lookup_error errors loc env (Cannot_scrape_alias(lid, p))

and lookup_all_args ~errors ~use ~loc lid0 env =
  let rec loop_lid_arg args = function
    | Lident _ | Ldot _ as f_lid ->
        (f_lid, args)
    | Lapply (f_lid, arg_lid) ->
        let arg_path, arg_md = lookup_module ~errors ~use ~loc arg_lid env in
        loop_lid_arg ((f_lid,arg_path,arg_md.md_type)::args) f_lid
  in
  loop_lid_arg [] lid0

and lookup_apply ~errors ~use ~loc lid0 env =
  let f0_lid, args0 = lookup_all_args ~errors ~use ~loc lid0 env in
  let args_for_errors = List.map (fun (_,p,mty) -> (p,mty)) args0 in
  let f0_path, f0_comp =
    lookup_module_components ~errors ~use ~loc f0_lid env
  in
  let check_one_apply ~errors ~loc ~f_lid ~f_comp ~arg_path ~arg_mty env =
    let f_comp, param_mty =
      get_functor_components ~errors ~loc f_lid env f_comp
    in
    check_functor_appl
      ~errors ~loc ~lid_whole_app:lid0
      ~f0_path ~args:args_for_errors ~f_comp
      ~arg_path ~arg_mty ~param_mty
      env;
    arg_path, f_comp
  in
  let rec check_apply ~path:f_path ~comp:f_comp = function
    | [] -> invalid_arg "Env.lookup_apply: empty argument list"
    | [ f_lid, arg_path, arg_mty ] ->
        let arg_path, comps =
          check_one_apply ~errors ~loc ~f_lid ~f_comp
            ~arg_path ~arg_mty env
        in
        f_path, comps, arg_path
    | (f_lid, arg_path, arg_mty) :: args ->
        let arg_path, f_comp =
          check_one_apply ~errors ~loc ~f_lid ~f_comp
            ~arg_path ~arg_mty env
        in
        let comp =
          !components_of_functor_appl' ~loc ~f_path ~f_comp ~arg:arg_path env
        in
        let path = Papply (f_path, arg_path) in
        check_apply ~path ~comp args
  in
  check_apply ~path:f0_path ~comp:f0_comp args0

and lookup_module ~errors ~use ~loc lid env =
  match lid with
  | Lident s ->
      let path, data = lookup_ident_module Load ~errors ~use ~loc s env in
      let md = Subst.Lazy.force_module_decl data.mda_declaration in
      path, md
  | Ldot(l, s) ->
      let path, data = lookup_dot_module ~errors ~use ~loc l s env in
      let md = Subst.Lazy.force_module_decl data.mda_declaration in
      path, md
  | Lapply _ as lid ->
      let path_f, comp_f, path_arg = lookup_apply ~errors ~use ~loc lid env in
      let md = md (modtype_of_functor_appl comp_f path_f path_arg) in
      Papply(path_f, path_arg), md

and lookup_dot_module ~errors ~use ~loc l s env =
  let p, comps = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_modules with
  | mda ->
      let path = Pdot(p, s) in
      use_module ~use ~loc path mda;
      (path, mda)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_module (Ldot(l, s)))

let lookup_dot_value ~errors ~use ~loc l s env =
  let (path, comps) =
    lookup_structure_components ~errors ~use ~loc l env
  in
  match NameMap.find s comps.comp_values with
  | vda ->
      let path = Pdot(path, s) in
      use_value ~use ~loc path vda;
      (path, vda.vda_description)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_value (Ldot(l, s), No_hint))

let lookup_dot_type ~errors ~use ~loc l s env =
  let (p, comps) = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_types with
  | tda ->
      let path = Pdot(p, s) in
      use_type ~use ~loc path tda;
      (path, tda)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_type (Ldot(l, s)))

let lookup_dot_modtype ~errors ~use ~loc l s env =
  let (p, comps) = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_modtypes with
  | mta ->
      let path = Pdot(p, s) in
      use_modtype ~use ~loc path mta.mtda_declaration;
      (path, mta.mtda_declaration)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_modtype (Ldot(l, s)))

let lookup_dot_class ~errors ~use ~loc l s env =
  let (p, comps) = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_classes with
  | clda ->
      let path = Pdot(p, s) in
      use_class ~use ~loc path clda;
      (path, clda.clda_declaration)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_class (Ldot(l, s)))

let lookup_dot_cltype ~errors ~use ~loc l s env =
  let (p, comps) = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_cltypes with
  | cltda ->
      let path = Pdot(p, s) in
      use_cltype ~use ~loc path cltda.cltda_declaration;
      (path, cltda.cltda_declaration)
  | exception Not_found ->
      may_lookup_error errors loc env (Unbound_cltype (Ldot(l, s)))

let lookup_all_dot_labels ~errors ~use ~loc usage l s env =
  let (_, comps) = lookup_structure_components ~errors ~use ~loc l env in
  match NameMap.find s comps.comp_labels with
  | [] | exception Not_found ->
      may_lookup_error errors loc env (Unbound_label (Ldot(l, s)))
  | lbls ->
      List.map
        (fun lbl ->
           let use_fun () = use_label ~use ~loc usage env lbl in
           (lbl, use_fun))
        lbls

let lookup_all_dot_constructors ~errors ~use ~loc usage l s env =
  match l with
  | Longident.Lident "*predef*" ->
      (* Hack to support compilation of default arguments *)
      lookup_all_ident_constructors
        ~errors ~use ~loc usage s initial_safe_string
  | _ ->
      let (_, comps) = lookup_structure_components ~errors ~use ~loc l env in
      match NameMap.find s comps.comp_constrs with
      | [] | exception Not_found ->
          may_lookup_error errors loc env (Unbound_constructor (Ldot(l, s)))
      | cstrs ->
          List.map
            (fun cda ->
               let use_fun () = use_constructor ~use ~loc usage env cda in
               (cda.cda_description, use_fun))
            cstrs

(* General forms of the lookup functions *)

let lookup_module_path ~errors ~use ~loc ~load lid env : Path.t =
  match lid with
  | Lident s ->
      if !Clflags.transparent_modules && not load then
        fst (lookup_ident_module Don't_load ~errors ~use ~loc s env)
      else
        fst (lookup_ident_module Load ~errors ~use ~loc s env)
  | Ldot(l, s) -> fst (lookup_dot_module ~errors ~use ~loc l s env)
  | Lapply _ as lid ->
      let path_f, _comp_f, path_arg = lookup_apply ~errors ~use ~loc lid env in
      Papply(path_f, path_arg)

let lookup_value ~errors ~use ~loc lid env =
  match lid with
  | Lident s -> lookup_ident_value ~errors ~use ~loc s env
  | Ldot(l, s) -> lookup_dot_value ~errors ~use ~loc l s env
  | Lapply _ -> assert false

let lookup_type_full ~errors ~use ~loc lid env =
  match lid with
  | Lident s -> lookup_ident_type ~errors ~use ~loc s env
  | Ldot(l, s) -> lookup_dot_type ~errors ~use ~loc l s env
  | Lapply _ -> assert false

let lookup_type ~errors ~use ~loc lid env =
  let (path, tda) = lookup_type_full ~errors ~use ~loc lid env in
  path, tda.tda_declaration

let lookup_modtype_lazy ~errors ~use ~loc lid env =
  match lid with
  | Lident s -> lookup_ident_modtype ~errors ~use ~loc s env
  | Ldot(l, s) -> lookup_dot_modtype ~errors ~use ~loc l s env
  | Lapply _ -> assert false

let lookup_modtype ~errors ~use ~loc lid env =
  let (path, mt) = lookup_modtype_lazy ~errors ~use ~loc lid env in
  path, Subst.Lazy.force_modtype_decl mt

let lookup_class ~errors ~use ~loc lid env =
  match lid with
  | Lident s -> lookup_ident_class ~errors ~use ~loc s env
  | Ldot(l, s) -> lookup_dot_class ~errors ~use ~loc l s env
  | Lapply _ -> assert false

let lookup_cltype ~errors ~use ~loc lid env =
  match lid with
  | Lident s -> lookup_ident_cltype ~errors ~use ~loc s env
  | Ldot(l, s) -> lookup_dot_cltype ~errors ~use ~loc l s env
  | Lapply _ -> assert false

let lookup_all_labels ~errors ~use ~loc usage lid env =
  match lid with
  | Lident s -> lookup_all_ident_labels ~errors ~use ~loc usage s env
  | Ldot(l, s) -> lookup_all_dot_labels ~errors ~use ~loc usage l s env
  | Lapply _ -> assert false

let lookup_label ~errors ~use ~loc usage lid env =
  match lookup_all_labels ~errors ~use ~loc usage lid env with
  | [] -> assert false
  | (desc, use) :: _ -> use (); desc

let lookup_all_labels_from_type ~use ~loc usage ty_path env =
  match find_type_descrs ty_path env with
  | exception Not_found -> []
  | Type_variant _ | Type_abstract | Type_open -> []
  | Type_record (lbls, _) ->
      List.map
        (fun lbl ->
           let use_fun () = use_label ~use ~loc usage env lbl in
           (lbl, use_fun))
        lbls

let lookup_all_constructors ~errors ~use ~loc usage lid env =
  match lid with
  | Lident s -> lookup_all_ident_constructors ~errors ~use ~loc usage s env
  | Ldot(l, s) -> lookup_all_dot_constructors ~errors ~use ~loc usage l s env
  | Lapply _ -> assert false

let lookup_constructor ~errors ~use ~loc usage lid env =
  match lookup_all_constructors ~errors ~use ~loc usage lid env with
  | [] -> assert false
  | (desc, use) :: _ -> use (); desc

let lookup_all_constructors_from_type ~use ~loc usage ty_path env =
  match find_type_descrs ty_path env with
  | exception Not_found -> []
  | Type_record _ | Type_abstract | Type_open -> []
  | Type_variant (cstrs, _) ->
      List.map
        (fun cstr ->
           let use_fun () =
             use_constructor_desc ~use ~loc usage env cstr
           in
           (cstr, use_fun))
        cstrs

(* Lookup functions that do not mark the item as used or
   warn if it has alerts, and raise [Not_found] rather
   than report errors *)

let find_module_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_module ~errors:false ~use:false ~loc lid env

let find_value_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_value ~errors:false ~use:false ~loc lid env

let find_type_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_type ~errors:false ~use:false ~loc lid env

let find_modtype_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_modtype ~errors:false ~use:false ~loc lid env

let find_class_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_class ~errors:false ~use:false ~loc lid env

let find_cltype_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_cltype ~errors:false ~use:false ~loc lid env

let find_constructor_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_constructor ~errors:false ~use:false ~loc Positive lid env

let find_label_by_name lid env =
  let loc = Location.(in_file !input_name) in
  lookup_label ~errors:false ~use:false ~loc Projection lid env

(* Ordinary lookup functions *)

let lookup_module_path ?(use=true) ~loc ~load lid env =
  lookup_module_path ~errors:true ~use ~loc ~load lid env

let lookup_module ?(use=true) ~loc lid env =
  lookup_module ~errors:true ~use ~loc lid env

let lookup_value ?(use=true) ~loc lid env =
  check_value_name (Longident.last lid) loc;
  lookup_value ~errors:true ~use ~loc lid env

let lookup_type ?(use=true) ~loc lid env =
  lookup_type ~errors:true ~use ~loc lid env

let lookup_modtype ?(use=true) ~loc lid env =
  lookup_modtype ~errors:true ~use ~loc lid env

let lookup_modtype_path ?(use=true) ~loc lid env =
  fst (lookup_modtype_lazy ~errors:true ~use ~loc lid env)

let lookup_class ?(use=true) ~loc lid env =
  lookup_class ~errors:true ~use ~loc lid env

let lookup_cltype ?(use=true) ~loc lid env =
  lookup_cltype ~errors:true ~use ~loc lid env

let lookup_all_constructors ?(use=true) ~loc usage lid env =
  match lookup_all_constructors ~errors:true ~use ~loc usage lid env with
  | exception Error(Lookup_error(loc', env', err)) ->
      (Error(loc', env', err) : _ result)
  | cstrs -> Ok cstrs

let lookup_constructor ?(use=true) ~loc lid env =
  lookup_constructor ~errors:true ~use ~loc lid env

let lookup_all_constructors_from_type ?(use=true) ~loc usage ty_path env =
  lookup_all_constructors_from_type ~use ~loc usage ty_path env

let lookup_all_labels ?(use=true) ~loc usage lid env =
  match lookup_all_labels ~errors:true ~use ~loc usage lid env with
  | exception Error(Lookup_error(loc', env', err)) ->
      (Error(loc', env', err) : _ result)
  | lbls -> Ok lbls

let lookup_label ?(use=true) ~loc lid env =
  lookup_label ~errors:true ~use ~loc lid env

let lookup_all_labels_from_type ?(use=true) ~loc usage ty_path env =
  lookup_all_labels_from_type ~use ~loc usage ty_path env

let lookup_instance_variable ?(use=true) ~loc name env =
  match IdTbl.find_name wrap_value ~mark:use name env.values with
  | (path, Val_bound vda) -> begin
      let desc = vda.vda_description in
      match desc.val_kind with
      | Val_ivar(mut, cl_num) ->
          use_value ~use ~loc path vda;
          path, mut, cl_num, desc.val_type
      | _ ->
          lookup_error loc env (Not_an_instance_variable name)
    end
  | (_, Val_unbound Val_unbound_instance_variable) ->
      lookup_error loc env (Masked_instance_variable (Lident name))
  | (_, Val_unbound Val_unbound_self) ->
      lookup_error loc env (Not_an_instance_variable name)
  | (_, Val_unbound Val_unbound_ancestor) ->
      lookup_error loc env (Not_an_instance_variable name)
  | (_, Val_unbound Val_unbound_ghost_recursive _) ->
      lookup_error loc env (Unbound_instance_variable name)
  | exception Not_found ->
      lookup_error loc env (Unbound_instance_variable name)

(* Checking if a name is bound *)

let bound_module name env =
  match IdTbl.find_name wrap_module ~mark:false name env.modules with
  | _ -> true
  | exception Not_found ->
      if Current_unit_name.is name then false
      else begin
        match find_pers_mod name with
        | _ -> true
        | exception Not_found -> false
      end

let bound wrap proj name env =
  match IdTbl.find_name wrap ~mark:false name (proj env) with
  | _ -> true
  | exception Not_found -> false

let bound_value name env =
  bound wrap_value (fun env -> env.values) name env

let bound_type name env =
  bound wrap_identity (fun env -> env.types) name env

let bound_modtype name env =
  bound wrap_identity (fun env -> env.modtypes) name env

let bound_class name env =
  bound wrap_identity (fun env -> env.classes) name env

let bound_cltype name env =
  bound wrap_identity (fun env -> env.cltypes) name env

(* Folding on environments *)

let find_all wrap proj1 proj2 f lid env acc =
  match lid with
  | None ->
      IdTbl.fold_name wrap
        (fun name (p, data) acc -> f name p data acc)
        (proj1 env) acc
  | Some l ->
      let p, desc =
        lookup_module_components
          ~errors:false ~use:false ~loc:Location.none l env
      in
      begin match get_components desc with
      | Structure_comps c ->
          NameMap.fold
            (fun s data acc -> f s (Pdot (p, s)) (wrap data) acc)
            (proj2 c) acc
      | Functor_comps _ ->
          acc
      end

let find_all_simple_list proj1 proj2 f lid env acc =
  match lid with
  | None ->
      TycompTbl.fold_name
        (fun data acc -> f data acc)
        (proj1 env) acc
  | Some l ->
      let (_p, desc) =
        lookup_module_components
          ~errors:false ~use:false ~loc:Location.none l env
      in
      begin match get_components desc with
      | Structure_comps c ->
          NameMap.fold
            (fun _s comps acc ->
               match comps with
               | [] -> acc
               | data :: _ -> f data acc)
            (proj2 c) acc
      | Functor_comps _ ->
          acc
      end

let fold_modules f lid env acc =
  match lid with
  | None ->
      IdTbl.fold_name wrap_module
        (fun name (p, entry) acc ->
           match entry with
           | Mod_unbound _ -> acc
           | Mod_local mda ->
               let md =
                 Subst.Lazy.force_module_decl mda.mda_declaration
               in
               f name p md acc
           | Mod_persistent ->
               match Persistent_env.find_in_cache !persistent_env name with
               | None -> acc
               | Some mda ->
                   let md =
                     Subst.Lazy.force_module_decl mda.mda_declaration
                   in
                   f name p md acc)
        env.modules
        acc
  | Some l ->
      let p, desc =
        lookup_module_components
          ~errors:false ~use:false ~loc:Location.none l env
      in
      begin match get_components desc with
      | Structure_comps c ->
          NameMap.fold
            (fun s mda acc ->
               let md =
                 Subst.Lazy.force_module_decl mda.mda_declaration
               in
               f s (Pdot (p, s)) md acc)
            c.comp_modules
            acc
      | Functor_comps _ ->
          acc
      end

let fold_values f =
  find_all wrap_value (fun env -> env.values) (fun sc -> sc.comp_values)
    (fun k p ve acc ->
       match ve with
       | Val_unbound _ -> acc
       | Val_bound vda -> f k p vda.vda_description acc)
and fold_constructors f =
  find_all_simple_list (fun env -> env.constrs) (fun sc -> sc.comp_constrs)
    (fun cda acc -> f cda.cda_description acc)
and fold_labels f =
  find_all_simple_list (fun env -> env.labels) (fun sc -> sc.comp_labels) f
and fold_types f =
  find_all wrap_identity
    (fun env -> env.types) (fun sc -> sc.comp_types)
    (fun k p tda acc -> f k p tda.tda_declaration acc)
and fold_modtypes f =
  let f l path data acc = f l path (Subst.Lazy.force_modtype_decl data) acc in
  find_all wrap_identity
    (fun env -> env.modtypes) (fun sc -> sc.comp_modtypes)
    (fun k p mta acc -> f k p mta.mtda_declaration acc)
and fold_classes f =
  find_all wrap_identity (fun env -> env.classes) (fun sc -> sc.comp_classes)
    (fun k p clda acc -> f k p clda.clda_declaration acc)
and fold_cltypes f =
  find_all wrap_identity
    (fun env -> env.cltypes) (fun sc -> sc.comp_cltypes)
    (fun k p cltda acc -> f k p cltda.cltda_declaration acc)

let filter_non_loaded_persistent f env =
  let to_remove =
    IdTbl.fold_name wrap_module
      (fun name (_, entry) acc ->
         match entry with
         | Mod_local _ -> acc
         | Mod_unbound _ -> acc
         | Mod_persistent ->
             match Persistent_env.find_in_cache !persistent_env name with
             | Some _ -> acc
             | None ->
                 if f (Ident.create_persistent name) then
                   acc
                 else
                   String.Set.add name acc)
      env.modules
      String.Set.empty
  in
  let remove_ids tbl ids =
    String.Set.fold
      (fun name tbl -> IdTbl.remove (Ident.create_persistent name) tbl)
      ids
      tbl
  in
  let rec filter_summary summary ids =
    if String.Set.is_empty ids then
      summary
    else
      match summary with
        Env_persistent (s, id) when String.Set.mem (Ident.name id) ids ->
          filter_summary s (String.Set.remove (Ident.name id) ids)
      | Env_empty
      | Env_value _
      | Env_type _
      | Env_extension _
      | Env_module _
      | Env_modtype _
      | Env_class _
      | Env_cltype _
      | Env_open _
      | Env_functor_arg _
      | Env_constraints _
      | Env_copy_types _
      | Env_persistent _
      | Env_value_unbound _
      | Env_module_unbound _ ->
          map_summary (fun s -> filter_summary s ids) summary
  in
  { env with
    modules = remove_ids env.modules to_remove;
    summary = filter_summary env.summary to_remove;
  }

(* Return the environment summary *)

let summary env =
  if Path.Map.is_empty env.local_constraints then env.summary
  else Env_constraints (env.summary, env.local_constraints)

let last_env = s_ref empty
let last_reduced_env = s_ref empty

let keep_only_summary env =
  if !last_env == env then !last_reduced_env
  else begin
    let new_env =
      {
       empty with
       summary = env.summary;
       local_constraints = env.local_constraints;
       flags = env.flags;
      }
    in
    last_env := env;
    last_reduced_env := new_env;
    new_env
  end


let env_of_only_summary env_from_summary env =
  let new_env = env_from_summary env.summary Subst.identity in
  { new_env with
    local_constraints = env.local_constraints;
    flags = env.flags;
  }

(* Error report *)

open Format

(* Forward declarations *)

let print_longident =
  ref ((fun _ _ -> assert false) : formatter -> Longident.t -> unit)

let print_path =
  ref ((fun _ _ -> assert false) : formatter -> Path.t -> unit)

let spellcheck ppf extract env lid =
  let choices ~path name = Misc.spellcheck (extract path env) name in
  match lid with
    | Longident.Lapply _ -> ()
    | Longident.Lident s ->
       Misc.did_you_mean ppf (fun () -> choices ~path:None s)
    | Longident.Ldot (r, s) ->
       Misc.did_you_mean ppf (fun () -> choices ~path:(Some r) s)

let spellcheck_name ppf extract env name =
  Misc.did_you_mean ppf
    (fun () -> Misc.spellcheck (extract env) name)

let extract_values path env =
  fold_values (fun name _ _ acc -> name :: acc) path env []
let extract_types path env =
  fold_types (fun name _ _ acc -> name :: acc) path env []
let extract_modules path env =
  fold_modules (fun name _ _ acc -> name :: acc) path env []
let extract_constructors path env =
  fold_constructors (fun desc acc -> desc.cstr_name :: acc) path env []
let extract_labels path env =
  fold_labels (fun desc acc -> desc.lbl_name :: acc) path env []
let extract_classes path env =
  fold_classes (fun name _ _ acc -> name :: acc) path env []
let extract_modtypes path env =
  fold_modtypes (fun name _ _ acc -> name :: acc) path env []
let extract_cltypes path env =
  fold_cltypes (fun name _ _ acc -> name :: acc) path env []
let extract_instance_variables env =
  fold_values
    (fun name _ descr acc ->
       match descr.val_kind with
       | Val_ivar _ -> name :: acc
       | _ -> acc) None env []

let report_lookup_error _loc env ppf = function
  | Unbound_value(lid, hint) -> begin
      fprintf ppf "Unbound value %a" !print_longident lid;
      spellcheck ppf extract_values env lid;
      match hint with
      | No_hint -> ()
      | Missing_rec def_loc ->
          let (_, line, _) =
            Location.get_pos_info def_loc.Location.loc_start
          in
          fprintf ppf
            "@.@[%s@ %s %i@]"
            "Hint: If this is a recursive definition,"
            "you should add the 'rec' keyword on line"
            line
    end
  | Unbound_type lid ->
      fprintf ppf "Unbound type constructor %a" !print_longident lid;
      spellcheck ppf extract_types env lid;
  | Unbound_module lid -> begin
      fprintf ppf "Unbound module %a" !print_longident lid;
       match find_modtype_by_name lid env with
      | exception Not_found -> spellcheck ppf extract_modules env lid;
      | _ ->
         fprintf ppf
           "@.@[%s %a, %s@]"
           "Hint: There is a module type named"
           !print_longident lid
           "but module types are not modules"
    end
  | Unbound_constructor lid ->
      fprintf ppf "Unbound constructor %a" !print_longident lid;
      spellcheck ppf extract_constructors env lid;
  | Unbound_label lid ->
      fprintf ppf "Unbound record field %a" !print_longident lid;
      spellcheck ppf extract_labels env lid;
  | Unbound_class lid -> begin
      fprintf ppf "Unbound class %a" !print_longident lid;
      match find_cltype_by_name lid env with
      | exception Not_found -> spellcheck ppf extract_classes env lid;
      | _ ->
         fprintf ppf
           "@.@[%s %a, %s@]"
           "Hint: There is a class type named"
           !print_longident lid
           "but classes are not class types"
    end
  | Unbound_modtype lid -> begin
      fprintf ppf "Unbound module type %a" !print_longident lid;
      match find_module_by_name lid env with
      | exception Not_found -> spellcheck ppf extract_modtypes env lid;
      | _ ->
         fprintf ppf
           "@.@[%s %a, %s@]"
           "Hint: There is a module named"
           !print_longident lid
           "but modules are not module types"
    end
  | Unbound_cltype lid ->
      fprintf ppf "Unbound class type %a" !print_longident lid;
      spellcheck ppf extract_cltypes env lid;
  | Unbound_instance_variable s ->
      fprintf ppf "Unbound instance variable %s" s;
      spellcheck_name ppf extract_instance_variables env s;
  | Not_an_instance_variable s ->
      fprintf ppf "The value %s is not an instance variable" s;
      spellcheck_name ppf extract_instance_variables env s;
  | Masked_instance_variable lid ->
      fprintf ppf
        "The instance variable %a@ \
         cannot be accessed from the definition of another instance variable"
        !print_longident lid
  | Masked_self_variable lid ->
      fprintf ppf
        "The self variable %a@ \
         cannot be accessed from the definition of an instance variable"
        !print_longident lid
  | Masked_ancestor_variable lid ->
      fprintf ppf
        "The ancestor variable %a@ \
         cannot be accessed from the definition of an instance variable"
        !print_longident lid
  | Illegal_reference_to_recursive_module ->
     fprintf ppf "Illegal recursive module reference"
  | Structure_used_as_functor lid ->
      fprintf ppf "@[The module %a is a structure, it cannot be applied@]"
        !print_longident lid
  | Abstract_used_as_functor lid ->
      fprintf ppf "@[The module %a is abstract, it cannot be applied@]"
        !print_longident lid
  | Functor_used_as_structure lid ->
      fprintf ppf "@[The module %a is a functor, \
                   it cannot have any components@]" !print_longident lid
  | Abstract_used_as_structure lid ->
      fprintf ppf "@[The module %a is abstract, \
                   it cannot have any components@]" !print_longident lid
  | Generative_used_as_applicative lid ->
      fprintf ppf "@[The functor %a is generative,@ it@ cannot@ be@ \
                   applied@ in@ type@ expressions@]" !print_longident lid
  | Cannot_scrape_alias(lid, p) ->
      let cause =
        if Current_unit_name.is_path p then "is the current compilation unit"
        else "is missing"
      in
      fprintf ppf
        "The module %a is an alias for module %a, which %s"
        !print_longident lid !print_path p cause

let report_error ppf = function
  | Missing_module(_, path1, path2) ->
      fprintf ppf "@[@[<hov>";
      if Path.same path1 path2 then
        fprintf ppf "Internal path@ %s@ is dangling." (Path.name path1)
      else
        fprintf ppf "Internal path@ %s@ expands to@ %s@ which is dangling."
          (Path.name path1) (Path.name path2);
      fprintf ppf "@]@ @[%s@ %s@ %s.@]@]"
        "The compiled interface for module" (Ident.name (Path.head path2))
        "was not found"
  | Illegal_value_name(_loc, name) ->
      fprintf ppf "'%s' is not a valid value identifier."
        name
  | Lookup_error(loc, t, err) -> report_lookup_error loc t ppf err

let () =
  Location.register_error_of_exn
    (function
      | Error err ->
          let loc =
            match err with
            | Missing_module (loc, _, _)
            | Illegal_value_name (loc, _)
            | Lookup_error(loc, _, _) -> loc
          in
          let error_of_printer =
            if loc = Location.none
            then Location.error_of_printer_file
            else Location.error_of_printer ~loc ?sub:None
          in
          Some (error_of_printer report_error err)
      | _ ->
          None
    )