Source file Typing.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
open AST
open ASTUtils
open Infix
open StaticEnv
module TypingRule = Instrumentation.TypingRule
module SES = SideEffect.SES
module TimeFrame = SideEffect.TimeFrame
let ( |: ) = Instrumentation.TypingNoInstr.use_with
let fatal_from ~loc = Error.fatal_from loc
let undefined_identifier ~loc x = fatal_from ~loc (Error.UndefinedIdentifier x)
let invalid_expr e = fatal_from ~loc:e (Error.InvalidExpr e)
let add_pos_from ~loc = add_pos_from loc
let conflicting_side_effects_error ~loc (s1, s2) =
fatal_from ~loc Error.(ConflictingSideEffects (s1, s2))
let ses_non_conflicting_union ~loc =
SES.non_conflicting_union ~fail:(conflicting_side_effects_error ~loc)
let ses_non_conflicting_unions ~loc =
SES.non_conflicting_unions ~fail:(conflicting_side_effects_error ~loc)
let conflict ~loc expected provided =
fatal_from ~loc (Error.ConflictingTypes (expected, provided))
let plus = binop PLUS
let t_bits_bitwidth e = T_Bits (e, [])
let rec list_mapi2 f i l1 l2 =
match (l1, l2) with
| [], [] -> []
| a1 :: l1, a2 :: l2 ->
let r = f i a1 a2 in
r :: list_mapi2 f (i + 1) l1 l2
| _, _ -> invalid_arg "List.map2"
let rec list_mapi3 f i l1 l2 l3 =
match (l1, l2, l3) with
| [], [], [] -> []
| a1 :: l1, a2 :: l2, a3 :: l3 ->
let r = f i a1 a2 a3 in
r :: list_mapi3 f (i + 1) l1 l2 l3
| _, _, _ -> invalid_arg "List.mapi3"
let sum = function [] -> !$0 | [ x ] -> x | h :: t -> List.fold_left plus h t
let slices_width env =
let minus = binop MINUS in
let slice_width = function
| Slice_Single _ -> one_expr
| Slice_Star (_, e) | Slice_Length (_, e) -> e
| Slice_Range (e1, e2) -> plus one_expr (minus e1 e2)
in
fun li -> List.map slice_width li |> sum |> StaticModel.try_normalize env
let width_plus env acc w = plus acc w |> StaticModel.try_normalize env
let rename_ty_eqs : env -> (AST.identifier * AST.expr) list -> AST.ty -> AST.ty
=
let subst_expr_normalize env eqs e =
subst_expr eqs e |> StaticModel.try_normalize env
in
let subst_constraint env eqs = function
| Constraint_Exact e -> Constraint_Exact (subst_expr_normalize env eqs e)
| Constraint_Range (e1, e2) ->
Constraint_Range
(subst_expr_normalize env eqs e1, subst_expr_normalize env eqs e2)
in
let subst_constraints env eqs = List.map (subst_constraint env eqs) in
let rec rename env eqs ty =
let here desc = add_pos_from ~loc:ty desc in
match ty.desc with
| T_Bits (e, fields) ->
T_Bits (subst_expr_normalize env eqs e, fields) |> here
| T_Int (WellConstrained constraints) ->
let constraints = subst_constraints env eqs constraints in
T_Int (WellConstrained constraints) |> here
| T_Int (Parameterized (_uid, name)) ->
let e = E_Var name |> here |> subst_expr_normalize env eqs in
T_Int (WellConstrained [ Constraint_Exact e ]) |> here
| T_Tuple tys -> T_Tuple (List.map (rename env eqs) tys) |> here
| _ -> ty
in
rename |: TypingRule.RenameTyEqs
let annotate_literal env = function
| L_Int _ as v -> integer_exact' (literal v)
| L_Bool _ -> T_Bool
| L_Real _ -> T_Real
| L_String _ -> T_String
| L_BitVector bv -> Bitvector.length bv |> expr_of_int |> t_bits_bitwidth
| L_Label label -> (
try IMap.find label env.global.declared_types |> fst |> desc
with Not_found -> assert false)
(** [set_filter_map f set] is the list of [y] such that [f x = Some y] for all
elements [x] of [set]. *)
let set_filter_map f set =
let folder e acc = match f e with None -> acc | Some x -> x :: acc in
ISet.fold folder set []
type strictness = Silence | Warn | TypeCheck | TypeCheckNoWarn
module type ANNOTATE_CONFIG = sig
val check : strictness
val output_format : Error.output_format
val print_typed : bool
val use_field_getter_extension : bool
end
module type S = sig
val type_check_ast : AST.t -> AST.t * global
val type_check_ast_in_env : global -> AST.t -> AST.t * global
end
module Property (C : ANNOTATE_CONFIG) = struct
module EP = Error.ErrorPrinter (C)
exception TypingAssumptionFailed
type ('a, 'b) property = 'a -> 'b
type prop = (unit, unit) property
let strictness_string =
match C.check with
| TypeCheck -> "type-checking-strict"
| TypeCheckNoWarn -> "type-checking-strict-no-warn"
| Warn -> "type-checking-warn"
| Silence -> "type-inference"
let check : prop -> prop =
match C.check with
| TypeCheckNoWarn | TypeCheck -> fun f () -> f ()
| Warn -> (
fun f () -> try f () with Error.ASLException e -> EP.eprintln e)
| Silence -> fun _f () -> ()
let best_effort' : ('a, 'a) property -> ('a, 'a) property =
match C.check with
| TypeCheckNoWarn | TypeCheck -> fun f x -> f x
| Warn -> (
fun f x ->
try f x
with Error.ASLException e ->
EP.eprintln e;
x)
| Silence -> ( fun f x -> try f x with Error.ASLException _ -> x)
let warn_from =
match C.check with
| TypeCheckNoWarn | Silence -> fun ~loc:_ _ -> ()
| TypeCheck | Warn -> EP.warn_from
let best_effort : 'a -> ('a, 'a) property -> 'a = fun x f -> best_effort' f x
let[@inline] ( let+ ) m f = check m () |> f
let either (p1 : ('a, 'b) property) (p2 : ('a, 'b) property) x =
try p1 x with TypingAssumptionFailed | Error.ASLException _ -> p2 x
let assumption_failed () = raise TypingAssumptionFailed [@@inline]
let ok () = () [@@inline]
let check_true b fail () = if b then () else fail () [@@inline]
let check_all2 li1 li2 f () = List.iter2 (fun x1 x2 -> f x1 x2 ()) li1 li2
end
module FunctionRenaming (C : ANNOTATE_CONFIG) = struct
open Property (C)
let has_arg_clash env caller callee =
List.compare_lengths caller callee == 0
&& List.for_all2
(fun t_caller (_, t_callee) ->
Types.type_clashes env t_caller t_callee)
caller callee
|: TypingRule.HasArgClash
let has_subprogram_type_clash s1 s2 =
match (s1, s2) with
| ST_Getter, ST_Setter
| ST_Setter, ST_Getter
| ST_EmptyGetter, ST_EmptySetter
| ST_EmptySetter, ST_EmptyGetter ->
false
| _ -> true
let deduce_eqs env =
let folder prev_eqs caller (_name, callee) =
match callee.desc with
| T_Bits ({ desc = E_Var x; _ }, _) -> (
match (Types.get_structure env caller).desc with
| T_Bits (e_caller, _) -> (x, e_caller) :: prev_eqs
| _ ->
assert false)
| _ -> prev_eqs
in
List.fold_left2 folder []
let add_new_func ~loc env name formals subpgm_type =
match IMap.find_opt name env.global.overloaded_subprograms with
| None ->
let new_env = set_renamings name (ISet.singleton name) env in
(new_env, name)
| Some other_names ->
let new_name = name ^ "-" ^ string_of_int (ISet.cardinal other_names) in
let clash =
let formal_types = List.map snd formals in
(not (ISet.is_empty other_names))
&& ISet.exists
(fun name' ->
let other_func_sig, _ses =
IMap.find name' env.global.subprograms
in
has_subprogram_type_clash subpgm_type
other_func_sig.subprogram_type
&& has_arg_clash env formal_types other_func_sig.args)
other_names
in
let+ () =
fun () ->
if clash then
let () =
if false then
Format.eprintf
"Function %s@[(%a)@] is declared multiple times.@." name
Format.(
pp_print_list
~pp_sep:(fun f () -> fprintf f ",@ ")
PP.pp_typed_identifier)
formals
in
fatal_from ~loc (Error.AlreadyDeclaredIdentifier name)
in
let new_env = set_renamings name (ISet.add new_name other_names) env in
(new_env, new_name) |: TypingRule.AddNewFunc
let subprogram_for_name ~loc env version name caller_arg_types =
let () =
if false then Format.eprintf "Trying to rename call to %S@." name
in
let renaming_set =
try IMap.find name env.global.overloaded_subprograms
with Not_found -> undefined_identifier ~loc name
in
let get_func_sig name' =
match IMap.find_opt name' env.global.subprograms with
| Some (func_sig, ses)
when has_arg_clash env caller_arg_types func_sig.args ->
Some (name', func_sig, ses)
| _ -> None
in
let matching_renamings = set_filter_map get_func_sig renaming_set in
match matching_renamings with
| [ (name', func_sig, ses) ] -> (
match version with
| V0 ->
(deduce_eqs env caller_arg_types func_sig.args, name', func_sig, ses)
| V1 -> ([], name', func_sig, ses) |: TypingRule.SubprogramForName)
| [] -> fatal_from ~loc (Error.NoCallCandidate (name, caller_arg_types))
| _ :: _ ->
fatal_from ~loc (Error.TooManyCallCandidates (name, caller_arg_types))
let try_subprogram_for_name =
match C.check with
| TypeCheckNoWarn | TypeCheck -> subprogram_for_name
| Warn | Silence -> (
fun ~loc env version name caller_arg_types ->
try subprogram_for_name ~loc env version name caller_arg_types
with Error.ASLException _ as error -> (
try
match IMap.find_opt name env.global.subprograms with
| None -> undefined_identifier ~loc ("function " ^ name)
| Some (func_sig, ses) ->
if false then
Format.eprintf "@[<2>%a:@ No extra arguments for %s@]@."
PP.pp_pos loc name;
([], name, func_sig, ses)
with Error.ASLException _ -> raise error))
end
module Annotate (C : ANNOTATE_CONFIG) : S = struct
open Property (C)
module Fn = FunctionRenaming (C)
module SOp = StaticOperations.Make (struct
let fail = assumption_failed
let warn_from = warn_from
end)
let ldk_is_immutable = function
| LDK_Constant | LDK_Let -> true
| LDK_Var -> false
let gdk_is_immutable = function
| GDK_Config | GDK_Constant | GDK_Let -> true
| GDK_Var -> false
let should_reduce_to_call env name st =
match IMap.find_opt name env.global.overloaded_subprograms with
| None -> false
| Some set ->
ISet.exists
(fun name' ->
match IMap.find_opt name' env.global.subprograms with
| None -> assert false
| Some (func_sig, _ses) -> func_sig.subprogram_type = st)
set
|: TypingRule.ShouldReduceToCall
let disjoint_slices_to_positions ~loc env slices =
let module DI = Diet.Int in
let exception NonStatic in
let eval env e =
match StaticModel.reduce_to_z_opt env e with
| Some z -> Z.to_int z
| None -> raise NonStatic
in
let interval_of_slice env slice =
let make_interval x y =
if x > y then fatal_from ~loc @@ Error.(BadSlice slice)
else DI.Interval.make x y
in
match slice with
| Slice_Single e ->
let x = eval env e in
make_interval x x |: TypingRule.BitfieldSliceToPositions
| Slice_Range (e1, e2) ->
let x = eval env e2 and y = eval env e1 in
make_interval x y |: TypingRule.BitfieldSliceToPositions
| Slice_Length (e1, e2) ->
let x = eval env e1 and y = eval env e2 in
make_interval x (x + y - 1) |: TypingRule.BitfieldSliceToPositions
| Slice_Star (e1, e2) ->
let x = eval env e1 and y = eval env e2 in
make_interval (x * y) ((x * (y + 1)) - 1)
|: TypingRule.BitfieldSliceToPositions
in
let bitfield_slice_to_positions ~loc env diet slice =
try
let interval = interval_of_slice env slice in
let new_diet = DI.add interval DI.empty in
if DI.is_empty (Diet.Int.inter new_diet diet) then DI.add interval diet
else fatal_from ~loc Error.(OverlappingSlices (slices, Static))
with NonStatic -> diet
in
List.fold_left (bitfield_slice_to_positions ~loc env) Diet.Int.empty slices
|: TypingRule.DisjointSlicesToPositions
let check_disjoint_slices ~loc env slices =
if List.length slices <= 1 then ok
else fun () ->
let _ = disjoint_slices_to_positions ~loc env slices in
() |: TypingRule.CheckDisjointSlices
exception NoSingleField
(** [to_singles env slices] is a list of [Slice_Single] slices
for each bit position of each bitfield slice in [slices]. *)
let to_singles env =
let eval e =
match StaticInterpreter.static_eval env e with
| L_Int z -> Z.to_int z
| _ -> raise NoSingleField
in
let one slice acc =
match slice with
| Slice_Single e -> e :: acc
| Slice_Length (e1, e2) ->
let i1 = eval e1 and i2 = eval e2 in
let rec do_rec n =
if n >= i2 then acc
else
let e =
E_Literal (L_Int (Z.of_int (i1 + n))) |> add_dummy_annotation
in
e :: do_rec (n + 1)
in
do_rec 0
| Slice_Range (e1, e2) ->
let i1 = eval e1 and i2 = eval e2 in
let rec do_rec i =
if i > i1 then acc
else
let e = E_Literal (L_Int (Z.of_int i)) |> add_dummy_annotation in
e :: do_rec (i + 1)
in
do_rec i2
| Slice_Star _ -> raise NoSingleField
in
fun slices -> List.fold_right one slices []
(** Retrieves the slices associated with the given bitfield
without recursing into nested bitfields. *)
let slices_of_bitfield = function
| BitField_Simple (_, slices)
| BitField_Nested (_, slices, _)
| BitField_Type (_, slices, _) ->
slices
(** Retrieves the slice of [Slice_Single] slices for each position
of the bitfield [field], if it is found in [bf]. *)
let field_to_single env bf field =
match find_bitfield_opt field bf with
| Some bitfield -> to_singles env (slices_of_bitfield bitfield)
| None -> raise NoSingleField
(** Checks that all bitfields listed in [fields] are delcared in the
bitvector type [ty]. If so, retrieves a list of [Slice_Single] slices for
each bit position of each bitfield slice of each bitfield in [fields].
[name] is passed along, if the result is not [None] for convenience of
use.
It is an ASLRef extension, guarded by [C.use_field_getter_extension].
*)
let should_fields_reduce_to_call env name ty fields =
assert C.use_field_getter_extension;
match (Types.make_anonymous env ty).desc with
| T_Bits (_, bf) -> (
try Some (name, list_concat_map (field_to_single env bf) fields)
with NoSingleField -> None)
| _ -> None
let get_bitvector_width' env t =
match (Types.get_structure env t).desc with
| T_Bits (n, _) -> n
| _ -> assumption_failed ()
let get_bitvector_width ~loc env t =
try get_bitvector_width' env t |: TypingRule.GetBitvectorWidth
with TypingAssumptionFailed -> conflict ~loc [ default_t_bits ] t
let get_bitvector_const_width ~loc env t =
let e_width = get_bitvector_width ~loc env t in
match StaticInterpreter.static_eval env e_width with
| L_Int z -> Z.to_int z |: TypingRule.GetBitvectorConstWidth
| _ -> assert false
(** [check_type_satisfies t1 t2] if [t1 <: t2]. *)
let check_type_satisfies ~loc env t1 t2 () =
let () =
if false then
Format.eprintf "@[<hv 2>Checking %a@ <: %a@]@." PP.pp_ty t1 PP.pp_ty t2
in
if Types.type_satisfies env t1 t2 then () else conflict ~loc [ t2.desc ] t1
(** [check_structure_boolean env t1] checks that [t1] has the structure of a boolean. *)
let check_structure_boolean ~loc env t1 () =
match (Types.get_structure env t1).desc with
| T_Bool -> ()
| _ -> conflict ~loc [ T_Bool ] t1
let check_structure_bits ~loc env t () =
match (Types.get_structure env t).desc with
| T_Bits _ -> ()
| _ -> conflict ~loc [ default_t_bits ] t
let check_structure_integer ~loc env t () =
let () =
if false then
Format.eprintf "Checking that %a is an integer.@." PP.pp_ty t
in
match (Types.make_anonymous env t).desc with
| T_Int _ -> ()
| _ -> conflict ~loc [ integer' ] t
let check_constrained_integer ~loc env t () =
match (Types.make_anonymous env t).desc with
| T_Int UnConstrained ->
fatal_from ~loc Error.(ConstrainedIntegerExpected t)
| T_Int (WellConstrained _ | Parameterized _) -> ()
| _ -> conflict ~loc [ integer' ] t
let check_structure_exception ~loc env t () =
let t_struct = Types.get_structure env t in
match t_struct.desc with
| T_Exception _ -> ()
| _ -> conflict ~loc [ T_Exception [] ] t_struct
let check_symbolically_evaluable expr_for_error ses () =
if SES.is_symbolically_evaluable ses then
() |: TypingRule.CheckSymbolicallyEvaluable
else
fatal_from ~loc:expr_for_error
(Error.ImpureExpression (expr_for_error, ses))
let check_is_deterministic expr_for_error ses () =
if SES.is_deterministic ses then ()
else
fatal_from ~loc:expr_for_error
(Error.ImpureExpression (expr_for_error, ses))
let check_is_pure expr_for_error ses () =
if SES.is_pure ses then ()
else
fatal_from ~loc:expr_for_error
(Error.ImpureExpression (expr_for_error, SES.remove_pure ses))
let leq_config_time ses =
TimeFrame.is_before (SES.max_time_frame ses) TimeFrame.Config
let check_leq_config_time ~loc (_, e, ses_e) () =
if leq_config_time ses_e then ()
else fatal_from ~loc Error.(ConfigTimeBroken (e, ses_e))
let leq_constant_time ses =
TimeFrame.is_before (SES.max_time_frame ses) TimeFrame.Constant
let check_leq_constant_time ~loc (_, e, ses_e) () =
if leq_constant_time ses_e then ()
else fatal_from ~loc Error.(ConstantTimeBroken (e, ses_e))
let check_is_time_frame =
let open TimeFrame in
function
| TimeFrame.Constant -> check_leq_constant_time
| TimeFrame.Config -> check_leq_config_time
| TimeFrame.Execution -> fun ~loc:_ _ -> ok
let check_bits_equal_width' env t1 t2 () =
let n = get_bitvector_width' env t1 and m = get_bitvector_width' env t2 in
if bitwidth_equal (StaticModel.equal_in_env env) n m then ()
else assumption_failed ()
let check_bits_equal_width ~loc env t1 t2 () =
try check_bits_equal_width' env t1 t2 ()
with TypingAssumptionFailed ->
fatal_from ~loc (Error.UnreconciliableTypes (t1, t2))
let binop_is_ordered = function
| BAND | BOR | IMPL -> true
| AND | BEQ | DIV | DIVRM | EOR | EQ_OP | GT | GEQ | LT | LEQ | MOD | MINUS
| MUL | NEQ | OR | PLUS | POW | RDIV | SHL | SHR | BV_CONCAT ->
false
let type_of_array_length ~loc = function
| ArrayLength_Enum (s, _) -> T_Named s |> add_pos_from ~loc
| ArrayLength_Expr _ -> integer |: TypingRule.TypeOfArrayLength
let rec apply_binop_types ~loc env op t1 t2 : ty =
let () =
if false then
Format.eprintf "Checking binop %s between %a and %a@."
(PP.binop_to_string op) PP.pp_ty t1 PP.pp_ty t2
in
let here x = add_pos_from ~loc x in
(match (op, (t1.desc, t2.desc)) with
| _, (T_Named _, _) | _, (_, T_Named _) ->
let t1_anon = Types.make_anonymous env t1
and t2_anon = Types.make_anonymous env t2 in
apply_binop_types ~loc env op t1_anon t2_anon
| (BAND | BOR | BEQ | IMPL), (T_Bool, T_Bool) -> T_Bool |> here
| (AND | OR | EOR | PLUS | MINUS), (T_Bits (w1, _), T_Bits (w2, _))
when bitwidth_equal (StaticModel.equal_in_env env) w1 w2 ->
T_Bits (w1, []) |> here
| BV_CONCAT, (T_Bits (w1, _), T_Bits (w2, _)) ->
T_Bits (width_plus env w1 w2, []) |> here
| (PLUS | MINUS), (T_Bits (w, _), T_Int _) -> T_Bits (w, []) |> here
| (LEQ | GEQ | GT | LT), (T_Int _, T_Int _ | T_Real, T_Real)
| ( (EQ_OP | NEQ),
(T_Int _, T_Int _ | T_Bool, T_Bool | T_Real, T_Real | T_String, T_String)
) ->
T_Bool |> here
| (EQ_OP | NEQ), (T_Bits (w1, _), T_Bits (w2, _))
when bitwidth_equal (StaticModel.equal_in_env env) w1 w2 ->
T_Bool |> here
| (EQ_OP | NEQ), (T_Enum li1, T_Enum li2)
when list_equal String.equal li1 li2 ->
T_Bool |> here
| ( (MUL | DIV | DIVRM | MOD | SHL | SHR | POW | PLUS | MINUS),
(T_Int c1, T_Int c2) ) -> (
match (c1, c2) with
| PendingConstrained, _ | _, PendingConstrained -> assert false
| UnConstrained, _ | _, UnConstrained -> T_Int UnConstrained |> here
| Parameterized _, _ | _, Parameterized _ ->
let t1_well_constrained = Types.to_well_constrained t1
and t2_well_constrained = Types.to_well_constrained t2 in
apply_binop_types ~loc env op t1_well_constrained
t2_well_constrained
| WellConstrained cs1, WellConstrained cs2 -> (
best_effort integer @@ fun _ ->
try
let cs = SOp.annotate_constraint_binop ~loc env op cs1 cs2 in
T_Int (WellConstrained cs) |> here
with TypingAssumptionFailed ->
fatal_from ~loc (Error.BadTypesForBinop (op, t1, t2))))
| (PLUS | MINUS | MUL), (T_Real, T_Real)
| POW, (T_Real, T_Int _)
| RDIV, (T_Real, T_Real) ->
T_Real |> here
| _ -> fatal_from ~loc (Error.BadTypesForBinop (op, t1, t2)))
|: TypingRule.ApplyBinopTypes
let apply_unop_type ~loc env op t =
let here desc = add_pos_from ~loc desc in
match op with
| BNOT ->
let+ () = check_type_satisfies ~loc env t boolean in
T_Bool |> here
| NEG -> (
let+ () =
either
(check_type_satisfies ~loc env t integer)
(check_type_satisfies ~loc env t real)
in
let t_struct = Types.get_well_constrained_structure env t in
match t_struct.desc with
| T_Int UnConstrained -> T_Int UnConstrained |> here
| T_Int (WellConstrained cs) ->
let neg e = unop NEG e in
let constraint_minus = function
| Constraint_Exact e -> Constraint_Exact (neg e)
| Constraint_Range (top, bot) ->
Constraint_Range (neg bot, neg top)
in
T_Int (WellConstrained (List.map constraint_minus cs)) |> here
| T_Int (Parameterized _) ->
assert false
| _ -> t)
| NOT ->
let+ () = check_structure_bits ~loc env t in
t |: TypingRule.ApplyUnopType
let rec check_atc ~fail env t1 t2 =
if Types.type_equal env t1 t2 then ok
else
match (t1.desc, t2.desc) with
| T_Int _, T_Int _ | T_Bits _, T_Bits _ -> ok
| T_Tuple l1, T_Tuple l2 when List.compare_lengths l1 l2 = 0 ->
check_all2 l1 l2 (check_atc ~fail env)
| T_Named _, _ | _, T_Named _ -> assert false
| _ -> fail |: TypingRule.CheckATC
let check_var_not_in_env ~loc env x () =
if is_undefined x env then () |: TypingRule.CheckVarNotInEnv
else fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
let check_var_not_in_genv ~loc genv x () =
if is_global_undefined x genv then () |: TypingRule.CheckVarNotInGEnv
else fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
let get_variable_enum' env e =
match e.desc with
| E_Var x -> (
match IMap.find_opt x env.global.declared_types with
| Some (t, _) -> (
match (Types.make_anonymous env t).desc with
| T_Enum labels -> Some (x, labels)
| _ -> None)
| None -> None)
| _ -> None
let check_diet_in_width ~loc slices width diet () =
let min_pos = Diet.Int.min_elt diet and max_pos = Diet.Int.max_elt diet in
if 0 <= min_pos && max_pos < width then
() |: TypingRule.CheckPositionsInWidth
else fatal_from ~loc (BadSlices (Error.Static, slices, width))
let check_slices_in_width ~loc env width slices () =
let diet = disjoint_slices_to_positions ~loc env slices in
check_diet_in_width ~loc slices width diet ()
|: TypingRule.CheckSlicesInWidth
(** A module for checking that all bitfields of a given bitvector type
that share the same name and exist in the same scope (terms defined
below) also define the same slice of the bitvector type.
*)
module CheckCommonBitfieldsAlign : sig
val check :
loc:'a annotated -> StaticEnv.env -> bitfield list -> int -> unit
end = struct
type range = int * int
(** [(j, i)] is the list of integers from [j] down to [i], inclusive,
matching the slice notation [j:i].
Invariant: [j >= i].
*)
type absolute_bitfield = {
name : identifier;
abs_scope : identifier list;
abs_slices : range list;
}
(** An absolute bitfield [abs_f] corresponds to a bitfield [f].
It consists of the following fields:
- [name] the name of the bitfield as declared;
- [abs_scope] is the list of names of ancestor bitfields, starting from the top; and
- [abs_slices] is a list of ranges that represent the sequence of indices,
corresponding to the slices defined for [f],
relative to the bitvector type that declares [f].
For example in
[
type Nested_Type of bits(3) {
[2:1] f1 {
[0] f2
}
};
]
we have the follwing absolute fields:
[
{name="f1"; abs_cope=[]; abs_slices=[2:1]}
{name="f2"; abs_cope=["f1"]; abs_slices=[1:1]}
]
*)
let safe_range (hi, lo) =
let () = assert (hi >= lo) in
(hi, lo)
let pp_abs_name fmt abs_name =
let abs_name_minus_top =
match abs_name with
| h :: t ->
let () = assert (String.equal h "") in
t
| _ -> assert false
in
Format.pp_print_list
~pp_sep:(fun fmt () -> Format.fprintf fmt ".")
(fun fmt id -> Format.fprintf fmt "%s" id)
fmt abs_name_minus_top
let pp_abs_slice fmt (hi, lo) =
if hi == lo then Format.fprintf fmt "%i" hi
else Format.fprintf fmt "%i:%i" hi lo
let pp_abs_slices ranges =
Format.pp_print_list
~pp_sep:(fun fmt () -> Format.fprintf fmt ", ")
pp_abs_slice ranges
let pp_absolute_bitfield fmt { name; abs_scope; abs_slices } =
Format.fprintf fmt "[%a] %a" pp_abs_slices abs_slices pp_abs_name
(List.append abs_scope [ name ])
let range_equal (range1 : range) (range2 : range) =
let hi1, lo1 = range1 in
let hi2, lo2 = range2 in
lo1 == lo2 && hi1 == hi2
let do_ranges_intersect (hi1, lo1) (hi2, lo2) =
(lo1 >= lo2 && lo1 <= hi2) || (hi1 <= hi2 && hi1 >= lo2)
(** Returns the range resulting from intersecting [range1] and [range2],
assuming they intersect.
*)
let intersect_ranges ((hi1, lo1) as range1) ((hi2, lo2) as range2) =
let () = assert (do_ranges_intersect range1 range2) in
safe_range (min hi1 hi2, max lo1 lo2)
let shift_range (hi, lo) amount = (hi + amount, lo + amount)
let ranges_equal ranges1 ranges2 = list_equal range_equal ranges1 ranges2
(** Returns the range [(i+w-1, i)], corresponding to
[slice = Slice_Length (i, , w)].
*)
let slice_to_range env slice : range =
match slice with
| Slice_Length (i, w) ->
let z_i = StaticInterpreter.static_eval_to_int env i in
let z_w = StaticInterpreter.static_eval_to_int env w in
safe_range (z_i + z_w - 1, z_i)
| _ ->
assert false
let merge_ranges_if_adjacent (hi1, lo1) (hi2, lo2) =
if lo1 == hi2 + 1 then Some (safe_range (hi1, lo2)) else None
(** Merges all adjacent ranges.
Example 1: {[(10, 4); (3, 2); (1, 0)]} is coalesced into {[(10,0)]}.
Example 2: for {[(1, 0); (3, 2)]} there is no coalescing
and the result is the input - {[(1, 0); (3, 2)]}.
*)
let coalesce_ranges ranges =
list_coalesce_right merge_ranges_if_adjacent ranges
(** Viewing [ranges] as one long list of integers --- the flat list,
the result associates each range of [ranges] with a range
corresponding to its respective indices in the flat list.
Example 1: if {ranges=[(6, 3); (2, 1)]}, the result is
{[(5, 2); (1, 0)]}
*)
let ranges_to_relative_ranges ranges =
let relative_ranges, _ =
List.fold_right
(fun cur_range (res_ranges, last_idx) ->
let cur_hi, cur_lo = cur_range in
let cur_range_len = cur_hi - cur_lo + 1 in
let relative_range = shift_range (cur_range_len - 1, 0) last_idx in
(relative_range :: res_ranges, last_idx + cur_range_len))
ranges ([], 0)
in
relative_ranges
(** [absolute_indices] represents a list of indices into the containing
vector, given by ranges. We can think of the "flat list" as the
concatenation of the individual lists for each range.
For example the flat list for [(20, 16); (13, 12); (9, 6)]
is [20, 19, 18, 17, 16, 13, 12, 9, 8, 7, 6].
[slice] is a list of ranges where each range consists of indices into
the flat list.
The result is a list of sub-ranges formed by selecting from each
range in [absolute_indices] the integers indicated by [slice], and
filtering out empty ranges.
To compute the result, we use the notion of relative ranges,
which associate to each range in [absolute_indices] the range of its
indices in the flat list. For example, the relative ranges for
[(20, 16); (13, 12); (9, 6)] are [(10, 6); (5, 4); (3, 0)].
Example 1: if {absolute_indices = [(20, 16); (13, 12); (9, 6)]}
and {slice = (4, 2)} then the result is {[(12, 12); (9, 8)]}.
To see this, consider the flat list for [absolute_indices], which is
[20, 19, 18, 17, 16, 13, 12, 9, 8, 7, 6].
The integers of the flat list at positions [4, 3, 2] correspond
to [12, 9, 8]. The integer [12] comes from the range {(13, 12)}
and the integers [9, 8] come from the range {(9, 8)}.
Therefore, the result is {[(12, 12); (9, 8)]}.
Example 2: if {absolute_indices = [(21,18); (9,4)]} and {slice=(7,6)}
the flat list is [21, 20, 19, 18, 9, 8, 7, 6, 5, 4]
the relative ranges are {[(9,6); (5,0)]}
and the result is {[(19, 18)]}.
*)
let select_indices_by_slice absolute_indices slice =
let relative_ranges = ranges_to_relative_ranges absolute_indices in
List.fold_right2
(fun cur_range cur_relative acc_ranges ->
if do_ranges_intersect slice cur_relative then
let common_range = intersect_ranges slice cur_relative in
let _, cur_relative_lo = cur_relative in
let _, cur_lo = cur_range in
let sliced_range =
shift_range common_range (-cur_relative_lo + cur_lo)
in
sliced_range :: acc_ranges
else
acc_ranges)
absolute_indices relative_ranges []
(** Viewing [absolute_indices] as one long list of integers ---
the flat list, the result is the list of integers selected from the flat
list via the indices represented by the ranges in [slices].
The result list is represented by the smallest list of ranges.
Example 1: if {absolute_indices = [(12,9); (7,2)]} and
{slices = [(5, 2)]}, the flat list is [12, 10, 9, 7, 6, 5, 4, 3, 2]
the selected elements of ranges are then [7, 6, 5, 4],
which can be represented by the single range {(7, 4)}.
*)
let select_indices_by_slices ~absolute_indices ~slices =
list_concat_map (select_indices_by_slice absolute_indices) slices
|> coalesce_ranges
(** [either_prefix list1 list2] is true if either [list1] is a prefix of [list2] or
[list2] is a prefix of [list1].
*)
let rec either_prefix list1 list2 =
match (list1, list2) with
| [], _ | _, [] -> true
| h1 :: t1, h2 :: t2 -> String.equal h1 h2 && either_prefix t1 t2
let exist_in_same_scope abs_f1 abs_f2 =
either_prefix abs_f1.abs_scope abs_f2.abs_scope
(** {iter_ordered_pairs f [e_1;...;e_k]} applies [f e_i e_j]
to every [1 <= i < j <= k].
*)
let rec iter_ordered_pairs f l =
match l with
| [] | [ _ ] -> ()
| h :: t ->
let () = List.iter (fun e_t -> f h e_t) t in
iter_ordered_pairs f t
(** Returns the list of absolute bitfields for the bitfield [bf]
and all bitfields transitively nested unde it,
given that [absolute_parent] is the absolute bitfield
for the bitfield where [bf] is declared.
*)
let rec bitfield_to_absolute env bf absolute_parent =
let { name; abs_scope = parent_scope; abs_slices = parent_abs_slices } =
absolute_parent
in
let bf_name = bitfield_get_name bf in
let bf_abs_scope = List.append parent_scope [ name ] in
let bf_slices_as_ranges =
List.map (slice_to_range env) (bitfield_get_slices bf)
in
let bf_abs_slices =
select_indices_by_slices ~absolute_indices:parent_abs_slices
~slices:bf_slices_as_ranges
in
let bf_absolute =
{ name = bf_name; abs_scope = bf_abs_scope; abs_slices = bf_abs_slices }
in
let bf_nested = bitfield_get_nested bf in
bf_absolute :: bitfields_to_absolute env bf_nested bf_absolute
(** Returns the list of absolute bitfields corresponding to [bitfields],
given that [absolute_parent] is the absolute bitfield
where [bitfields] are declared.
The order of the absolute fields is unimportant.
*)
and bitfields_to_absolute env bitfields absolute_parent =
list_concat_map
(fun bf -> bitfield_to_absolute env bf absolute_parent)
bitfields
(** Tests whether absolute bitfields [f1] and [f2] are aligned.
If the two fields don't share a name or don't exist in the same
scope, the result is true.
*)
let absolute_bitfields_align f1 f2 =
if String.equal f1.name f2.name && exist_in_same_scope f1 f2 then
let { abs_slices = indices1 } = f1 in
let { abs_slices = indices2 } = f2 in
ranges_equal indices1 indices2
else true
let check ~loc env bitfields width =
let top_absolute =
{
name = "";
abs_scope = [];
abs_slices = [ safe_range (width - 1, 0) ];
}
in
let absolute_bitfields =
bitfields_to_absolute env bitfields top_absolute
in
let () =
if false then
List.iter
(fun f ->
Format.eprintf "absolute field %a@." pp_absolute_bitfield f)
absolute_bitfields
in
iter_ordered_pairs
(fun f1 f2 ->
let () =
if false then
Format.eprintf
"checking %a and %a | same scope: %b | same name: %b | equal \
slices: %b@."
pp_absolute_bitfield f1 pp_absolute_bitfield f2
(exist_in_same_scope f1 f2)
(String.equal f1.name f2.name)
(ranges_equal f1.abs_slices f2.abs_slices)
in
if not (absolute_bitfields_align f1 f2) then
let abs_name1 = f1.abs_scope @ [ f1.name ] in
let abs_name2 = f2.abs_scope @ [ f2.name ] in
let abs_name1_str = Format.asprintf "%a" pp_abs_name abs_name1 in
let abs_name2_str = Format.asprintf "%a" pp_abs_name abs_name2 in
let indices1_str =
Format.asprintf "[%a]" pp_abs_slices f1.abs_slices
in
let indices2_str =
Format.asprintf "[%a]" pp_abs_slices f2.abs_slices
in
fatal_from ~loc
(Error.BitfieldsDontAlign
{
field1_absname = abs_name1_str;
field2_absname = abs_name2_str;
field1_absslices = indices1_str;
field2_absslices = indices2_str;
}))
absolute_bitfields
let test_do_ranges_intersect () =
assert (do_ranges_intersect (4, 2) (3, 0));
assert (do_ranges_intersect (4, 2) (5, 4));
assert (do_ranges_intersect (4, 2) (10, 6) == false)
let test_coalesce_ranges () =
assert (
ranges_equal (coalesce_ranges [ (10, 4); (3, 2); (1, 0) ]) [ (10, 0) ]);
assert (
ranges_equal (coalesce_ranges [ (1, 0); (3, 2) ]) [ (1, 0); (3, 2) ]);
assert (
ranges_equal
(coalesce_ranges [ (21, 11); (10, 5); (3, 2); (1, 0) ])
[ (21, 5); (3, 0) ]);
assert (
ranges_equal
(coalesce_ranges [ (21, 11); (10, 5); (3, 2) ])
[ (21, 5); (3, 2) ])
let test_ranges_to_relative_ranges () =
let ranges = [ (6, 3); (2, 1) ] in
let relative_ranges = ranges_to_relative_ranges ranges in
let () = assert (ranges_equal relative_ranges [ (5, 2); (1, 0) ]) in
let ranges = [ shift_range (6, 3) 500; shift_range (2, 1) 1000 ] in
let relative_ranges = ranges_to_relative_ranges ranges in
assert (ranges_equal relative_ranges [ (5, 2); (1, 0) ])
let test_select_by_slice () =
let ranges = [ (20, 16); (13, 12); (9, 6) ] in
let slice = (4, 2) in
let selected = select_indices_by_slice ranges slice in
let () = assert (ranges_equal selected [ (12, 12); (9, 8) ]) in
let ranges = [ (21, 18); (9, 4) ] in
let slice = (7, 6) in
let selected = select_indices_by_slice ranges slice in
assert (ranges_equal selected [ (19, 18) ])
let check_common_bitfields_align_unit_tests _ =
Format.printf "Running unit tests for CheckCommonBitfieldsAlign@.";
test_do_ranges_intersect ();
test_coalesce_ranges ();
test_ranges_to_relative_ranges ();
test_select_by_slice ()
let () = if false then check_common_bitfields_align_unit_tests ()
end
(** Check for a standard library declaration name{n}(bits(n), ...) or
name{m,n}(bits(n), ...). *)
let can_omit_stdlib_param func_sig =
func_sig.builtin
&&
let declared_param =
match func_sig.parameters with
| [ (n, _) ] | [ _; (n, _) ] -> Some n
| _ -> None
and declared_first_arg_width =
match func_sig.args with
| (_, { desc = T_Bits ({ desc = E_Var n' }, _) }) :: _ -> Some n'
| _ -> None
in
match (declared_param, declared_first_arg_width) with
| Some n, Some n' -> String.equal n n'
| _ -> false
(** Special treatment to infer the single input parameter [N] of a
stdlib/primitive function with a first argument of type [bits(N)]. *)
let insert_stdlib_param ~loc env func_sig ~params ~arg_types =
if
can_omit_stdlib_param func_sig
&& List.compare_lengths params func_sig.parameters < 0
&& not (list_is_empty arg_types)
then
let width = get_bitvector_width ~loc env (List.hd arg_types) in
let param_type = integer_exact' width |> add_pos_from ~loc:width in
let ses_param =
SES.empty
in
params @ [ (param_type, width, ses_param) ]
else params
let rec annotate_bitfield ~loc env width bitfield : bitfield * SES.t =
match bitfield with
| BitField_Simple (name, slices) ->
let slices1, ses_slices = annotate_slices ~loc env slices in
let+ () = check_slices_in_width ~loc env width slices1 in
(BitField_Simple (name, slices1), ses_slices) |: TypingRule.TBitField
| BitField_Nested (name, slices, bitfields') ->
let slices1, ses_slices = annotate_slices ~loc env slices in
let diet = disjoint_slices_to_positions ~loc env slices1 in
let+ () = check_diet_in_width ~loc slices1 width diet in
let width' = Diet.Int.cardinal diet |> expr_of_int in
let new_bitfields, ses_bitfields =
annotate_bitfields ~loc env width' bitfields'
in
let ses = SES.union ses_slices ses_bitfields in
(BitField_Nested (name, slices1, new_bitfields), ses)
|: TypingRule.TBitField
| BitField_Type (name, slices, ty) ->
let ty', ses_ty = annotate_type ~loc env ty in
let slices1, ses_slices = annotate_slices ~loc env slices in
let diet = disjoint_slices_to_positions ~loc env slices1 in
let+ () = check_diet_in_width ~loc slices1 width diet in
let width' = Diet.Int.cardinal diet |> expr_of_int in
let+ () =
t_bits_bitwidth width' |> add_dummy_annotation
|> check_bits_equal_width ~loc env ty
in
let ses = SES.union ses_ty ses_slices in
(BitField_Type (name, slices1, ty'), ses) |: TypingRule.TBitField
and annotate_bitfields ~loc env e_width bitfields =
let+ () =
match get_first_duplicate (List.map bitfield_get_name bitfields) with
| None -> ok
| Some x -> fun () -> fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
in
let width =
let v = StaticInterpreter.static_eval env e_width in
match v with L_Int i -> Z.to_int i | _ -> assert false
in
let new_bitfields, sess =
list_map_split (annotate_bitfield ~loc env width) bitfields
in
let ses = ses_non_conflicting_unions ~loc sess in
(new_bitfields, ses) |: TypingRule.TBitFields
and annotate_type ?(decl = false) ~(loc : 'a annotated) env ty : ty * SES.t =
let () =
if false then
Format.eprintf "Annotating@ %a@ in env:@ %a@." PP.pp_ty ty pp_env env
in
let here t = add_pos_from ~loc:ty t in
best_effort (ty, SES.empty) @@ fun _ ->
match ty.desc with
| T_String -> (ty, SES.empty) |: TypingRule.TString
| T_Real -> (ty, SES.empty) |: TypingRule.TReal
| T_Bool -> (ty, SES.empty) |: TypingRule.TBool
| T_Named x ->
let ses =
let time_frame =
match IMap.find_opt x env.global.declared_types with
| Some (_, t) -> t
| None -> undefined_identifier ~loc x
and immutable = true in
SES.reads_global x time_frame immutable
in
(ty, ses) |: TypingRule.TNamed
| T_Int constraints ->
(match constraints with
| PendingConstrained ->
fatal_from ~loc Error.UnexpectedPendingConstrained
| WellConstrained [] -> fatal_from ~loc Error.EmptyConstraints
| WellConstrained constraints ->
let new_constraints, sess =
list_map_split (annotate_constraint ~loc env) constraints
in
let ses = SES.unions sess in
(T_Int (WellConstrained new_constraints) |> here, ses)
| Parameterized (_, name) ->
(ty, SES.reads_local name TimeFrame.Constant true)
| UnConstrained -> (ty, SES.empty))
|: TypingRule.TInt
| T_Bits (e_width, bitfields) ->
let t_width, e_width', ses_width = annotate_expr env e_width in
let+ () = check_symbolically_evaluable e_width ses_width in
let+ () = check_constrained_integer ~loc:e_width env t_width in
let bitfields', ses_bitfields =
if bitfields = [] then (bitfields, SES.empty)
else
let annotated_bitfields, ses_bitfields =
annotate_bitfields ~loc env e_width' bitfields
in
let () =
let width =
match StaticInterpreter.static_eval env e_width' with
| L_Int i -> Z.to_int i
| _ -> assert false
in
CheckCommonBitfieldsAlign.check ~loc:ty env annotated_bitfields
width
|: TypingRule.CheckCommonBitfieldsAlign
in
(annotated_bitfields, ses_bitfields)
in
let ses = SES.union ses_width ses_bitfields in
(T_Bits (e_width', bitfields') |> here, ses) |: TypingRule.TBits
| T_Tuple tys ->
let tys', sess = list_map_split (annotate_type ~loc env) tys in
let ses = SES.unions sess in
(T_Tuple tys' |> here, ses) |: TypingRule.TTuple
| T_Array (index, t) ->
let t', ses_t = annotate_type ~loc env t
and index', ses_index =
match index with
| ArrayLength_Expr e -> (
match get_variable_enum' env e with
| Some (s, labels) -> (ArrayLength_Enum (s, labels), SES.empty)
| None ->
let e', ses = annotate_symbolic_integer ~loc env e in
(ArrayLength_Expr e', ses))
| ArrayLength_Enum (_, _) ->
assert
false
in
let ses = SES.union ses_t ses_index in
(T_Array (index', t') |> here, ses) |: TypingRule.TArray
| (T_Record fields | T_Exception fields) when decl -> (
let+ () =
match get_first_duplicate (List.map fst fields) with
| None -> ok
| Some x ->
fun () -> fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
in
let fields', sess =
list_map_split
(fun (x, ty) ->
let ty', ses = annotate_type ~loc env ty in
((x, ty'), ses))
fields
in
let ses = SES.unions sess in
match ty.desc with
| T_Record _ ->
(T_Record fields' |> here, ses) |: TypingRule.TStructuredDecl
| T_Exception _ ->
(T_Exception fields' |> here, ses) |: TypingRule.TStructuredDecl
| _ -> assert false
)
| T_Enum li when decl ->
let+ () =
match get_first_duplicate li with
| None -> ok
| Some x ->
fun () -> fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
in
let+ () =
fun () ->
List.iter (fun s -> check_var_not_in_genv ~loc env.global s ()) li
in
(ty, SES.empty) |: TypingRule.TEnumDecl
| T_Enum _ | T_Record _ | T_Exception _ ->
if decl then assert false
else
fatal_from ~loc
(Error.NotYetImplemented
" Cannot use non anonymous form of enumerations, record, or \
exception here.")
|: TypingRule.TNonDecl
and annotate_symbolically_evaluable_expr env e =
let t, e', ses = annotate_expr env e in
let+ () = check_symbolically_evaluable e ses in
(t, e', ses)
and annotate_symbolic_integer ~(loc : 'a annotated) env e =
let t, e', ses = annotate_symbolically_evaluable_expr env e in
let+ () = check_structure_integer ~loc env t in
(StaticModel.try_normalize env e', ses)
and annotate_symbolic_constrained_integer ~(loc : 'a annotated) env e =
let t, e', ses = annotate_symbolically_evaluable_expr env e in
let+ () = check_constrained_integer ~loc env t in
(StaticModel.try_normalize env e', ses)
and annotate_constraint ~loc env = function
| Constraint_Exact e ->
let e', ses = annotate_symbolic_constrained_integer ~loc env e in
(Constraint_Exact e', ses)
| Constraint_Range (e1, e2) ->
let e1', ses1 = annotate_symbolic_constrained_integer ~loc env e1
and e2', ses2 = annotate_symbolic_constrained_integer ~loc env e2 in
let ses = SES.union ses1 ses2 in
(Constraint_Range (e1', e2'), ses)
and annotate_slices env ~loc =
let rec annotate_slice s =
let () =
if false then
Format.eprintf "Annotating slice %a@." PP.pp_slice_list [ s ]
in
match s with
| Slice_Single i ->
annotate_slice (Slice_Length (i, one_expr)) |: TypingRule.Slice
| Slice_Length (offset, length) ->
let t_offset, offset', ses_offset = annotate_expr env offset
and length', ses_length =
annotate_symbolic_constrained_integer ~loc env length
in
let+ () = check_structure_integer ~loc:offset env t_offset in
let ses = SES.union ses_length ses_offset in
(Slice_Length (offset', length'), ses |: TypingRule.Slice)
| Slice_Range (j, i) ->
let pre_length = binop MINUS j i |> binop PLUS !$1 in
annotate_slice (Slice_Length (i, pre_length)) |: TypingRule.Slice
| Slice_Star (factor, pre_length) ->
let pre_offset = binop MUL factor pre_length in
annotate_slice (Slice_Length (pre_offset, pre_length))
|: TypingRule.Slice
in
fun slices ->
let slices, sess = list_map_split annotate_slice slices in
let ses = ses_non_conflicting_unions ~loc sess in
(slices, ses)
and annotate_pattern ~loc env t p =
let here = add_pos_from ~loc:p in
match p.desc with
| Pattern_All -> (p, SES.empty) |: TypingRule.PAll
| Pattern_Any li ->
let new_li, sess = list_map_split (annotate_pattern ~loc env t) li in
let ses =
SES.unions sess
in
(Pattern_Any new_li |> here, ses) |: TypingRule.PAny
| Pattern_Not q ->
let new_q, ses = annotate_pattern ~loc env t q in
(Pattern_Not new_q |> here, ses) |: TypingRule.PNot
| Pattern_Single e ->
let t_e, e', ses = annotate_expr env e in
let+ () = check_symbolically_evaluable e ses in
let+ () =
fun () ->
let t_struct = Types.make_anonymous env t
and t_e_struct = Types.make_anonymous env t_e in
match (t_struct.desc, t_e_struct.desc) with
| T_Bool, T_Bool
| T_Real, T_Real
| T_Int _, T_Int _
| T_String, T_String ->
()
| T_Bits _, T_Bits _ ->
check_bits_equal_width ~loc env t_struct t_e_struct ()
| T_Enum li1, T_Enum li2 when list_equal String.equal li1 li2 -> ()
| _ -> fatal_from ~loc (Error.BadPattern (p, t))
in
(Pattern_Single e' |> here, ses) |: TypingRule.PSingle
| Pattern_Geq e ->
let t_e, e', ses = annotate_expr env e in
let+ () = check_symbolically_evaluable e ses in
let+ () =
fun () ->
let t_struct = Types.get_structure env t
and t_e_struct = Types.get_structure env t_e in
match (t_struct.desc, t_e_struct.desc) with
| T_Real, T_Real | T_Int _, T_Int _ -> ()
| _ -> fatal_from ~loc (Error.BadPattern (p, t))
in
(Pattern_Geq e' |> here, ses) |: TypingRule.PGeq
| Pattern_Leq e ->
let t_e, e', ses = annotate_expr env e in
let+ () = check_symbolically_evaluable e ses in
let+ () =
fun () ->
let t_anon = Types.make_anonymous env t
and t_e_anon = Types.make_anonymous env t_e in
match (t_anon.desc, t_e_anon.desc) with
| T_Real, T_Real | T_Int _, T_Int _ -> ()
| _ -> fatal_from ~loc (Error.BadPattern (p, t))
in
(Pattern_Leq e' |> here, ses) |: TypingRule.PLeq
| Pattern_Range (e1, e2) ->
let t_e1, e1', ses1 = annotate_symbolically_evaluable_expr env e1
and t_e2, e2', ses2 = annotate_symbolically_evaluable_expr env e2 in
let ses =
SES.union ses1 ses2
in
let+ () =
fun () ->
let t_anon = Types.make_anonymous env t
and t_e1_anon = Types.make_anonymous env t_e1
and t_e2_anon = Types.make_anonymous env t_e2 in
match (t_anon.desc, t_e1_anon.desc, t_e2_anon.desc) with
| T_Real, T_Real, T_Real | T_Int _, T_Int _, T_Int _ -> ()
| _ -> fatal_from ~loc (Error.BadPattern (p, t))
in
(Pattern_Range (e1', e2') |> here, ses) |: TypingRule.PRange
| Pattern_Mask m ->
let+ () = check_structure_bits ~loc env t in
let+ () =
let n = !$(Bitvector.mask_length m) in
let t_m = T_Bits (n, []) |> add_pos_from ~loc in
check_type_satisfies ~loc env t t_m
in
(p, SES.empty) |: TypingRule.PMask
| Pattern_Tuple li -> (
let t_struct = Types.get_structure env t in
match t_struct.desc with
| T_Tuple ts when List.compare_lengths li ts != 0 ->
fatal_from ~loc
(Error.BadArity
( Static,
"pattern matching on tuples",
List.length li,
List.length ts ))
| T_Tuple ts ->
let new_li, sess =
List.map2 (annotate_pattern ~loc env) ts li |> List.split
in
let ses =
SES.unions
sess
in
(Pattern_Tuple new_li |> here, ses) |: TypingRule.PTuple
| _ -> conflict ~loc [ T_Tuple [] ] t
)
and annotate_call ~loc env (call_info : call) =
let () =
if false then
Format.eprintf "Annotating call to %S (%s) at %a.@." call_info.name
(Serialize.subprogram_type_to_string call_info.call_type)
PP.pp_pos loc
in
let args = List.map (annotate_expr env) call_info.args in
match (loc.version, call_info.params) with
| V0, [] ->
let () = assert (List.length call_info.params = 0) in
annotate_call_v0 ~loc env call_info.name args call_info.call_type
| (V1 | V0), _ ->
let params = List.map (annotate_expr env) call_info.params in
annotate_call_v1 ~loc env call_info.name ~params ~args
~call_type:call_info.call_type
|: TypingRule.AnnotateCall
and annotate_call_v1 ~loc env name ~params ~args ~call_type =
let arg_types, args, sess_args = list_split3 args in
let ses_args = ses_non_conflicting_unions ~loc sess_args in
let _, name, func_sig, ses_call =
Fn.try_subprogram_for_name ~loc env V1 name arg_types
in
let ses = SES.union ses_args ses_call in
let+ () =
check_true
(func_sig.subprogram_type = call_type
|| (func_sig.subprogram_type = ST_Getter && call_type = ST_Function))
@@ fun () -> fatal_from ~loc (MismatchedReturnValue name)
in
let params = insert_stdlib_param ~loc env func_sig ~params ~arg_types in
let () =
if List.compare_lengths func_sig.parameters params != 0 then
fatal_from ~loc
@@ Error.BadParameterArity
( Static,
V1,
name,
List.length func_sig.parameters,
List.length params )
else if List.compare_lengths func_sig.args args != 0 then
fatal_from ~loc
@@ Error.BadArity
(Static, name, List.length func_sig.args, List.length args)
in
let () =
List.iter2
(fun (name, ty_declared_opt) (ty_actual, e_actual, ses_actual) ->
let+ () = check_symbolically_evaluable e_actual ses_actual in
let+ () = check_constrained_integer ~loc env ty_actual in
match ty_declared_opt with
| None ->
assert false
| Some { desc = T_Int (Parameterized (_, name')) }
when String.equal name name' ->
()
| Some ty_declared ->
let+ () = check_type_satisfies ~loc env ty_actual ty_declared in
())
func_sig.parameters params
in
let eqs =
List.map2
(fun (name, _) (_, e, _) -> (name, e))
func_sig.parameters params
in
let () =
List.iter2
(fun (_, declared_ty) actual_ty ->
let expected_ty = rename_ty_eqs env eqs declared_ty in
let+ () = check_type_satisfies ~loc env actual_ty expected_ty in
())
func_sig.args arg_types
in
let return_type =
match (call_type, func_sig.return_type) with
| (ST_Function | ST_Getter), Some ty -> Some (rename_ty_eqs env eqs ty)
| (ST_Procedure | ST_Setter), None -> None
| _ -> fatal_from ~loc @@ Error.MismatchedReturnValue name
in
( {
name;
args;
params = List.map (fun (_, e, _) -> e) params;
call_type = func_sig.subprogram_type;
},
return_type,
ses )
and annotate_call_v0 ~loc env name caller_args_typed call_type =
let caller_arg_types, args1, sess = list_split3 caller_args_typed in
let ses1 = ses_non_conflicting_unions ~loc sess in
let eqs1, name1, callee, ses2 =
Fn.try_subprogram_for_name ~loc env V0 name caller_arg_types
in
let ses3 = SES.union ses1 ses2 in
let () =
if false then
Format.eprintf "@[Found candidate decl:@ @[%a@]@]@." PP.pp_t
[ D_Func callee |> add_dummy_annotation ]
in
let+ () =
check_true (callee.subprogram_type = call_type) @@ fun () ->
fatal_from ~loc (MismatchedReturnValue name)
in
let () =
if false then
let open Format in
eprintf "Parameters for this call: %a@."
(pp_print_list ~pp_sep:pp_print_space (fun f (name, e) ->
fprintf f "%S<--%a" name (pp_print_option PP.pp_ty) e))
callee.parameters
in
let () =
if false then
match eqs1 with
| [] -> ()
| _ ->
Format.eprintf "@[<2>%a: Adding@ @[{%a}@]@ to call of %s@."
PP.pp_pos loc
(Format.pp_print_list
~pp_sep:(fun f () -> Format.fprintf f ";@ ")
(fun f (n, e) ->
Format.fprintf f "@[%s@ <- %a@]" n PP.pp_expr e))
eqs1 name
in
let () =
if List.compare_lengths callee.args args1 != 0 then
fatal_from ~loc
@@ Error.BadArity
(Static, name, List.length callee.args, List.length args1)
in
let eqs2 =
let folder acc (_x, ty) (t_e, _e, _ses) =
match ty.desc with
| T_Bits ({ desc = E_Var param_name; _ }, _) -> (
match (Types.make_anonymous env t_e).desc with
| T_Bits (param_actual_e, _) -> (
match List.assoc_opt param_name acc with
| Some param_actual_e2
when StaticModel.equal_in_env env param_actual_e
param_actual_e2 ->
acc
| Some _
| None
->
(param_name, param_actual_e) :: acc)
| _ -> acc)
| _ -> acc
in
match C.check with
| TypeCheckNoWarn | TypeCheck -> eqs1
| Warn | Silence ->
List.fold_left2 folder eqs1 callee.args caller_args_typed
in
let eqs3 =
List.fold_left2
(fun eqs (callee_x, _) (caller_ty, caller_e, caller_ses) ->
if
List.exists
(fun (p_name, _ty) -> String.equal callee_x p_name)
callee.parameters
then
let+ () = check_symbolically_evaluable caller_e caller_ses in
let+ () = check_constrained_integer ~loc env caller_ty in
(callee_x, caller_e) :: eqs
else eqs)
eqs2 callee.args caller_args_typed
in
let () =
if false then
let open Format in
eprintf "@[<hov 2>Eqs for this call are: %a@]@."
(pp_print_list ~pp_sep:pp_print_space (fun f (name, e) ->
fprintf f "%S<--%a" name PP.pp_expr e))
eqs3
in
let () =
List.iter2
(fun (callee_arg_name, callee_arg) caller_arg ->
let callee_arg1 = rename_ty_eqs env eqs3 callee_arg in
let () =
if false then
Format.eprintf "Checking calling arg %s from %a to %a@."
callee_arg_name PP.pp_ty caller_arg PP.pp_ty callee_arg1
in
let+ () = check_type_satisfies ~loc env caller_arg callee_arg1 in
())
callee.args caller_arg_types
in
let () =
if false && not (String.equal name name1) then
Format.eprintf "Renaming call from %s to %s@ at %a.@." name name1
PP.pp_pos loc
in
let () =
List.iter
(function
| _, None -> ()
| s, Some { desc = T_Int (Parameterized (_, s')); _ }
when String.equal s' s ->
()
| callee_param_name, Some callee_param_t ->
let callee_param_t_renamed =
rename_ty_eqs env eqs3 callee_param_t
in
let caller_param_e =
match List.assoc_opt callee_param_name eqs3 with
| None ->
assert false
| Some e -> e
in
let caller_param_t, _, _ =
annotate_symbolically_evaluable_expr env caller_param_e
in
let () =
if false then
Format.eprintf
"Checking calling param %s from %a to %a (i.e. %a)@."
callee_param_name PP.pp_ty caller_param_t PP.pp_ty
callee_param_t PP.pp_ty callee_param_t_renamed
in
let+ () =
check_type_satisfies ~loc env caller_param_t
callee_param_t_renamed
in
())
callee.parameters
in
let ret_ty_opt =
match (call_type, callee.return_type) with
| (ST_Function | ST_Getter | ST_EmptyGetter), Some ty ->
Some (rename_ty_eqs env eqs3 ty)
| (ST_Setter | ST_EmptySetter | ST_Procedure), None -> None
| _ -> fatal_from ~loc @@ Error.MismatchedReturnValue name
in
let () = if false then Format.eprintf "Annotated call to %S.@." name1 in
let params =
List.filter_map
(fun (name, _) -> List.assoc_opt name eqs3)
callee.parameters
in
let+ () =
check_true (List.length params = List.length callee.parameters)
@@ fun () ->
fatal_from ~loc
(Error.BadParameterArity
(Static, V0, name, List.length callee.parameters, List.length params))
in
( { name = name1; args = args1; params; call_type = callee.subprogram_type },
ret_ty_opt,
ses3 )
and annotate_expr env (e : expr) : ty * expr * SES.t =
let () = if false then Format.eprintf "@[Annotating %a@]@." PP.pp_expr e in
let here x = add_pos_from ~loc:e x and loc = to_pos e in
match e.desc with
| E_Literal v ->
(annotate_literal env v |> here, e, SES.empty) |: TypingRule.ELit
| E_ATC (e', ty) ->
let t, e'', ses_e = annotate_expr env e' in
let t_struct = Types.get_structure env t in
let ty', ses_ty = annotate_type ~loc env ty in
let ty_struct = Types.get_structure env ty' in
let+ () =
check_atc env t_struct ty_struct ~fail:(fun () ->
fatal_from ~loc (BadATC (t, ty)))
in
let ses = SES.union ses_ty @@ SES.add_assertion ses_e in
(if Types.subtype_satisfies env t_struct ty_struct then (ty', e'', ses_e)
else (ty', E_ATC (e'', ty_struct) |> here, ses))
|: TypingRule.ATC
| E_Var x -> (
let () = if false then Format.eprintf "Looking at %S.@." x in
if e.version = V0 && should_reduce_to_call env x ST_EmptyGetter then
let () =
if false then
Format.eprintf "@[Reducing getter %S@ at %a@]@." x PP.pp_pos e
in
let call_type = ST_EmptyGetter in
let call, ty, ses =
annotate_call ~loc:(to_pos e) env
{ name = x; params = []; args = []; call_type }
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call call |> here, ses)
else
let () =
if false then
Format.eprintf "@[Choosing not to reduce var %S@ at @[%a@]@]@." x
PP.pp_pos e
in
try
match IMap.find x env.local.storage_types with
| ty, LDK_Constant when Storage.mem x env.local.constant_values ->
let v = Storage.find x env.local.constant_values in
(ty, E_Literal v |> here, SES.empty) |: TypingRule.EVar
| ty, ldk ->
let ses =
SES.reads_local x (TimeFrame.of_ldk ldk)
(ldk_is_immutable ldk)
in
(ty, e, ses) |: TypingRule.EVar
with Not_found -> (
try
match IMap.find x env.global.storage_types with
| ty, GDK_Constant when Storage.mem x env.global.constant_values
->
let v = Storage.find x env.global.constant_values in
(ty, E_Literal v |> here, SES.empty) |: TypingRule.EVar
| ty, gdk ->
let ses =
SES.reads_global x (TimeFrame.of_gdk gdk)
(gdk_is_immutable gdk)
in
(ty, e, ses) |: TypingRule.EVar
with Not_found ->
let () =
if false then
Format.eprintf "@[Cannot find %s in env@ %a.@]@." x pp_env env
in
undefined_identifier ~loc:e x |: TypingRule.EVar))
| E_Binop (op, e1, e2) ->
let t1, e1', ses1 = annotate_expr env e1 in
let t2, e2', ses2 = annotate_expr env e2 in
let t = apply_binop_types ~loc env op t1 t2 in
let ses =
if binop_is_ordered op then SES.union ses1 ses2
else ses_non_conflicting_union ~loc ses1 ses2
in
(t, E_Binop (op, e1', e2') |> here, ses) |: TypingRule.Binop
| E_Unop (op, e') ->
let t'', e'', ses = annotate_expr env e' in
let t = apply_unop_type ~loc env op t'' in
(t, E_Unop (op, e'') |> here, ses) |: TypingRule.Unop
| E_Call call ->
let call, ret_ty_opt, ses = annotate_call ~loc:(to_pos e) env call in
let t = match ret_ty_opt with Some ty -> ty | None -> assert false in
(t, E_Call call |> here, ses) |: TypingRule.ECall
| E_Cond (e_cond, e_true, e_false) ->
let t_cond, e_cond', ses_cond = annotate_expr env e_cond in
let+ () = check_structure_boolean ~loc env t_cond in
let t_true, e_true', ses_true = annotate_expr env e_true
and t_false, e_false', ses_false = annotate_expr env e_false in
let t =
best_effort t_true (fun _ ->
match Types.lowest_common_ancestor env t_true t_false with
| None ->
fatal_from ~loc (Error.UnreconciliableTypes (t_true, t_false))
| Some t -> t)
in
let ses = SES.union3 ses_cond ses_true ses_false in
(t, E_Cond (e_cond', e_true', e_false') |> here, ses)
|: TypingRule.ECond
| E_Tuple [ e ] -> annotate_expr env e
| E_Tuple li ->
let ts, es, sess = List.map (annotate_expr env) li |> list_split3 in
let ses = ses_non_conflicting_unions ~loc sess in
(T_Tuple ts |> here, E_Tuple es |> here, ses) |: TypingRule.ETuple
| E_Array _ -> fatal_from ~loc UnrespectedParserInvariant
| E_Record (ty, fields) ->
let+ () =
check_true (Types.is_named ty) (fun () ->
failwith "Typing error: should be a named type")
in
best_effort (ty, e, SES.empty) @@ fun _ ->
let field_types =
match (Types.make_anonymous env ty).desc with
| T_Exception fields | T_Record fields -> fields
| _ -> conflict ~loc [ T_Record [] ] ty
in
let () =
if
List.for_all
(fun (name, _) -> List.mem_assoc name fields)
field_types
then ()
else fatal_from ~loc (Error.MissingField (List.map fst fields, ty))
in
let+ () =
match get_first_duplicate (List.map fst fields) with
| None -> ok
| Some x ->
fun () -> fatal_from ~loc (Error.AlreadyDeclaredIdentifier x)
in
let annotate_field_init (name, e') =
let t', e'', ses = annotate_expr env e' in
let t_spec' =
match List.assoc_opt name field_types with
| None -> fatal_from ~loc (Error.BadField (name, ty))
| Some t_spec' -> t_spec'
in
let+ () = check_type_satisfies ~loc env t' t_spec' in
((name, e''), ses) |: TypingRule.AnnotateFieldInit
in
let fields', sess = list_map_split annotate_field_init fields in
let ses = ses_non_conflicting_unions ~loc sess in
(ty, E_Record (ty, fields') |> here, ses) |: TypingRule.ERecord
| E_Arbitrary ty ->
let ty1, ses_ty = annotate_type ~loc env ty in
let ty2 = Types.get_structure env ty1 in
let ses = SES.add_non_determinism ses_ty in
(ty1, E_Arbitrary ty2 |> here, ses) |: TypingRule.EArbitrary
| E_Slice (e', slices) -> (
match e'.desc with
| E_Var name
when e'.version = V0
&& should_reduce_to_call env name ST_Getter
&& List.for_all slice_is_single slices ->
let args =
try List.map slice_as_single slices
with Invalid_argument _ -> assert false
in
let call, ty, ses =
annotate_call ~loc:(to_pos e) env
{ name; params = []; args; call_type = ST_Getter }
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call call |> here, ses)
| _ -> (
let t_e', e'', ses1 = annotate_expr env e' in
let struct_t_e' = Types.make_anonymous env t_e' in
match struct_t_e'.desc with
| T_Int _ | T_Bits _ ->
let+ () =
check_true (not (list_is_empty slices)) @@ fun () ->
fatal_from ~loc Error.EmptySlice
in
let slices', ses2 =
best_effort (slices, SES.empty) (fun _ ->
annotate_slices env slices ~loc)
in
let w = slices_width env slices' in
let ses = SES.union ses1 ses2 in
(T_Bits (w, []) |> here, E_Slice (e'', slices') |> here, ses)
|: TypingRule.ESlice
| T_Array (size, ty') when e'.version = V0 -> (
match slices with
| [ Slice_Single e_index ] ->
annotate_get_array ~loc env (size, ty') (e'', ses1, e_index)
| _ -> conflict ~loc [ integer'; default_t_bits ] t_e')
| _ ->
conflict ~loc [ integer'; default_t_bits ] t_e'
|: TypingRule.ESliceError
))
| E_GetField (e1, field_name) -> (
let reduced =
if e1.version = V0 && C.use_field_getter_extension then
reduce_getfields_to_slices env e1 [ field_name ]
else None
in
match reduced with
| Some (name, args) ->
let call, ty, ses =
annotate_call ~loc:(to_pos e) env
{ name; params = []; args; call_type = ST_Getter }
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call call |> here, ses)
| None -> (
let t_e2, e2, ses1 = annotate_expr env e1 in
match (Types.make_anonymous env t_e2).desc with
| T_Exception fields | T_Record fields -> (
match List.assoc_opt field_name fields with
| None ->
fatal_from ~loc (Error.BadField (field_name, t_e2))
|: TypingRule.EGetBadRecordField
| Some t ->
(t, E_GetField (e2, field_name) |> here, ses1)
|: TypingRule.EGetRecordField
)
| T_Bits (_, bitfields) -> (
match find_bitfield_opt field_name bitfields with
| None ->
fatal_from ~loc (Error.BadField (field_name, t_e2))
|: TypingRule.EGetBadBitField
| Some (BitField_Simple (_field, slices)) ->
let e3 = E_Slice (e1, slices) |> here in
annotate_expr env e3 |: TypingRule.EGetBitField
| Some (BitField_Nested (_field, slices, bitfields')) ->
let e3 = E_Slice (e1, slices) |> here in
let t_e4, new_e, ses_new = annotate_expr env e3 in
let t_e5 =
match t_e4.desc with
| T_Bits (width, _bitfields) ->
T_Bits (width, bitfields') |> add_pos_from ~loc:t_e2
| _ -> assert false
in
(t_e5, new_e, ses_new) |: TypingRule.EGetBitFieldNested
| Some (BitField_Type (_field, slices, t)) ->
let e3 = E_Slice (e1, slices) |> here in
let t_e4, new_e, ses_new = annotate_expr env e3 in
let+ () = check_type_satisfies ~loc env t_e4 t in
(t, new_e, ses_new) |: TypingRule.EGetBitFieldTyped
)
| T_Tuple tys ->
let index =
try Scanf.sscanf field_name "item%u" Fun.id
with Scanf.Scan_failure _ | Failure _ | End_of_file ->
fatal_from ~loc (Error.BadField (field_name, t_e2))
in
if 0 <= index && index < List.length tys then
( List.nth tys index,
E_GetItem (e2, index) |> add_pos_from ~loc:e,
ses1 )
else
fatal_from ~loc (Error.BadField (field_name, t_e2))
|: TypingRule.EGetTupleItem
| _ ->
fatal_from ~loc (Error.BadField (field_name, t_e2))
|: TypingRule.EGetBadField)
)
| E_GetFields (e_base, fields) -> (
let reduced =
if e_base.version = V0 && C.use_field_getter_extension then
reduce_getfields_to_slices env e_base fields
else None
in
match reduced with
| Some (name, args) ->
let call, ret_ty_opt, ses =
annotate_call ~loc:(to_pos e) env
{ name; params = []; args; call_type = ST_Getter }
in
let ty =
match ret_ty_opt with Some ty -> ty | None -> assert false
in
(ty, E_Call call |> here, ses)
| None -> (
let t_base_annot, e_base_annot, ses_base =
annotate_expr env e_base
in
match (Types.make_anonymous env t_base_annot).desc with
| T_Bits (_, bitfields) ->
let one_field field =
match find_bitfields_slices_opt field bitfields with
| None ->
fatal_from ~loc (Error.BadField (field, t_base_annot))
| Some slices -> slices
in
E_Slice (e_base, list_concat_map one_field fields)
|> here |> annotate_expr env |: TypingRule.EGetFields
| T_Record base_fields ->
let get_bitfield_width name =
match List.assoc_opt name base_fields with
| None ->
fatal_from ~loc (Error.BadField (name, t_base_annot))
| Some t -> get_bitvector_width ~loc env t
in
let widths = List.map get_bitfield_width fields in
let e_slice_width =
let wh = List.hd widths and wts = List.tl widths in
List.fold_left (width_plus env) wh wts
in
( T_Bits (e_slice_width, []) |> here,
E_GetFields (e_base_annot, fields) |> here,
ses_base )
|: TypingRule.EGetFields
| _ -> conflict ~loc [ default_t_bits ] t_base_annot))
| E_Pattern (e1, pat) ->
let t_e2, e2, ses_e = annotate_expr env e1 in
let pat', ses_pat =
best_effort (pat, SES.empty) (fun _ ->
annotate_pattern ~loc env t_e2 pat)
in
let ses =
SES.union ses_pat ses_e
in
(T_Bool |> here, E_Pattern (e2, pat') |> here, ses)
|: TypingRule.EPattern
| E_GetArray (e_base, e_index) -> (
let t_base, e_base', ses_base = annotate_expr env e_base in
let t_anon_base = Types.make_anonymous env t_base in
match t_anon_base.desc with
| T_Array (size, t_elem) ->
annotate_get_array ~loc env (size, t_elem)
(e_base', ses_base, e_index)
| _ -> conflict ~loc [ default_array_ty ] t_base |: TypingRule.EGetArray
)
| E_GetItem _ | E_EnumArray _ | E_GetEnumArray _ -> assert false
and annotate_get_array ~loc env (size, t_elem) (e_base, ses_base, e_index) =
let t_index', e_index', ses_index = annotate_expr env e_index in
let wanted_t_index = type_of_array_length ~loc size in
let+ () = check_type_satisfies ~loc env t_index' wanted_t_index in
let ses = ses_non_conflicting_union ~loc ses_index ses_base in
let new_e =
match size with
| ArrayLength_Enum _ -> E_GetEnumArray (e_base, e_index')
| ArrayLength_Expr _ -> E_GetArray (e_base, e_index')
in
(t_elem, new_e |> add_pos_from ~loc, ses) |: TypingRule.AnnotateGetArray
(** For an expression of the form [e1.[f1,...,fn]], if [e1] represents a call
to a getter then this function returns a list of slices needed to read
the bitfields [f1...fn]. Otherwise, the result is [None].
It is an ASLRef extension, guarded by [C.use_field_getter_extension].
*)
and reduce_getfields_to_slices env e1 fields =
assert (e1.version = V0 && C.use_field_getter_extension);
match e1.desc with
| E_Var name when should_reduce_to_call env name ST_Getter ->
let empty_getter = E_Slice (e1, []) |> add_pos_from ~loc:e1 in
let ty, _, _ = annotate_expr env empty_getter in
should_fields_reduce_to_call env name ty fields
| _ -> None
let list_min_abs_z =
let min_abs acc z =
match Z.compare (Z.abs acc) (Z.abs z) with
| -1 -> acc
| 1 -> z
| 0 -> if Z.sign acc >= 0 then acc else z
| _ -> assert false
in
function
| [] -> raise (Invalid_argument "list_min_abs_z")
| h :: t -> List.fold_left min_abs h t
(** [base_value_v1 ~loc env t] returns an expression building the base value
of the type [t] in [env].
The base value expression can be used to initialize variables of type [t]
in [env].
This expression is side-effect free, and is a literal for singular types.
If a base value cannot be statically determined (e.g. for parameterized
integer types), a type error is thrown, at the ~location [loc].
*)
let rec base_value_v1 ~loc env t : expr =
let here = add_pos_from ~loc in
let lit v = here (E_Literal v) in
let fatal_non_static e =
fatal_from ~loc (Error.BaseValueNonStatic (t, e))
in
let fatal_is_empty () = fatal_from ~loc (Error.BaseValueEmptyType t) in
let reduce_to_z e =
match StaticModel.reduce_to_z_opt env e with
| None -> fatal_non_static e
| Some i -> i
in
match t.desc with
| T_Bool -> L_Bool false |> lit
| T_Bits (e, _) ->
let length = reduce_to_z e |> Z.to_int in
L_BitVector (Bitvector.zeros length) |> lit
| T_Enum [] -> assert false
| T_Enum (name :: _) -> lookup_constants env name |> lit
| T_Int UnConstrained -> L_Int Z.zero |> lit
| T_Int (Parameterized (_, id)) -> E_Var id |> here |> fatal_non_static
| T_Int PendingConstrained -> assert false
| T_Int (WellConstrained cs) ->
let constraint_abs_min = function
| Constraint_Exact e -> Some (reduce_to_z e)
| Constraint_Range (e1, e2) ->
let v1 = reduce_to_z e1 in
let v2 = reduce_to_z e2 in
if v1 <= v2 then
match Z.(sign v1, sign v2) with
| -1, -1 -> Some v2
| -1, _ -> Some Z.zero
| _, _ -> Some v1
else None
in
let z_min_list = List.filter_map constraint_abs_min cs in
if list_is_empty z_min_list then fatal_is_empty ()
else
let z_min = list_min_abs_z z_min_list in
L_Int z_min |> lit
| T_Named _ -> Types.make_anonymous env t |> base_value_v1 ~loc env
| T_Real -> L_Real Q.zero |> lit
| T_Exception fields | T_Record fields ->
let one_field (name, t_field) =
(name, base_value_v1 ~loc env t_field)
in
E_Record (t, List.map one_field fields) |> here
| T_String -> L_String "" |> lit
| T_Tuple li ->
let exprs = List.map (base_value_v1 ~loc env) li in
E_Tuple exprs |> here
| T_Array (index, ty) -> (
let value = base_value_v1 ~loc env ty in
match index with
| ArrayLength_Enum (enum, labels) ->
E_EnumArray { enum; labels; value } |> here
| ArrayLength_Expr length -> E_Array { length; value } |> here)
let rec base_value_v0 ~loc env t : expr =
assert (loc.version = V0);
let here = add_pos_from ~loc in
match t.desc with
| T_Bool | T_Int UnConstrained | T_Real | T_String | T_Enum _ ->
base_value_v1 ~loc env t
| T_Bits (width, _) ->
let e =
E_Call
{
name = "Zeros";
params = [];
args = [ width ];
call_type = ST_Function;
}
in
let _, e', _ = annotate_expr env (here e) in
e'
| T_Int (Parameterized (_, id)) -> E_Var id |> here
| T_Int (WellConstrained [] | PendingConstrained) -> assert false
| T_Int
(WellConstrained ((Constraint_Exact e | Constraint_Range (e, _)) :: _))
->
e
| T_Tuple li -> E_Tuple (List.map (base_value_v0 ~loc env) li) |> here
| T_Exception fields | T_Record fields ->
let fields =
List.map
(fun (name, t_field) -> (name, base_value_v0 ~loc env t_field))
fields
in
E_Record (t, fields) |> here
| T_Array (length, ty) -> (
let value = base_value_v0 ~loc env ty in
match length with
| ArrayLength_Enum (enum, labels) ->
E_EnumArray { enum; labels; value } |> here
| ArrayLength_Expr length -> E_Array { length; value } |> here)
| T_Named _id ->
let t = Types.make_anonymous env t in
base_value_v0 ~loc env t
(** [base_value ~loc env e] is [base_value_v1 ~loc env e] if running for ASLv1,
or [base_value_v0 ~loc env e] if running for ASLv0.
*)
let base_value ~loc env e =
match loc.version with
| V0 -> base_value_v0 ~loc env e
| V1 -> base_value_v1 ~loc env e
let annotate_set_array ~loc env (size, t_elem) rhs_ty
(e_base, ses_base, e_index) =
let+ () = check_type_satisfies ~loc env rhs_ty t_elem in
let t_index', e_index', ses_index = annotate_expr env e_index in
let wanted_t_index = type_of_array_length ~loc:e_base size in
let+ () = check_type_satisfies ~loc env t_index' wanted_t_index in
let ses = ses_non_conflicting_union ~loc ses_base ses_index in
let new_le =
match size with
| ArrayLength_Enum _ -> LE_SetEnumArray (e_base, e_index')
| ArrayLength_Expr _ -> LE_SetArray (e_base, e_index')
in
(new_le |> add_pos_from ~loc, ses) |: TypingRule.AnnotateSetArray
let rec annotate_lexpr env le t_e =
let () =
if false then
Format.eprintf "Typing lexpr: @[%a@] to @[%a@]@." PP.pp_lexpr le
PP.pp_ty t_e
in
let loc = to_pos le in
let here x = add_pos_from ~loc x in
match le.desc with
| LE_Discard -> (le, SES.empty) |: TypingRule.LEDiscard
| LE_Var x ->
let ty, ses =
match IMap.find_opt x env.local.storage_types with
| Some (ty, LDK_Var) -> (ty, SES.writes_local x)
| Some _ -> fatal_from ~loc @@ Error.AssignToImmutable x
| None -> (
match IMap.find_opt x env.global.storage_types with
| Some (ty, GDK_Var) -> (ty, SES.writes_global x)
| Some _ -> fatal_from ~loc @@ Error.AssignToImmutable x
| None -> undefined_identifier ~loc x)
in
let+ () = check_type_satisfies ~loc env t_e ty in
(le, ses) |: TypingRule.LEVar
| LE_Destructuring les ->
(match t_e.desc with
| T_Tuple tys ->
if List.compare_lengths tys les != 0 then
Error.fatal_from le
(Error.BadArity
(Static, "LEDestructuring", List.length tys, List.length les))
else
let les', sess =
List.map2 (annotate_lexpr env) les tys |> List.split
in
let ses =
SES.unions sess
in
(LE_Destructuring les' |> here, ses)
| _ -> conflict ~loc [ T_Tuple [] ] t_e)
|: TypingRule.LEDestructuring
| LE_Slice (le1, slices) -> (
let t_le1, _, _ = expr_of_lexpr le1 |> annotate_expr env in
let t_le1_anon = Types.make_anonymous env t_le1 in
match t_le1_anon.desc with
| T_Bits _ ->
let le2, ses1 = annotate_lexpr env le1 t_le1 in
let+ () =
fun () ->
let width =
slices_width env slices |> StaticModel.try_normalize env
in
let t = T_Bits (width, []) |> here in
check_type_satisfies ~loc env t_e t ()
in
let slices2, ses2 =
best_effort (slices, SES.empty) @@ fun _ ->
annotate_slices env slices ~loc
in
let+ () = check_disjoint_slices ~loc env slices2 in
let+ () =
check_true (not (list_is_empty slices)) @@ fun () ->
fatal_from ~loc Error.EmptySlice
in
let ses = ses_non_conflicting_union ~loc ses1 ses2 in
(LE_Slice (le2, slices2) |> here, ses |: TypingRule.LESlice)
| T_Array (size, t) when le.version = V0 -> (
match slices with
| [ Slice_Single e_index ] ->
let le2, ses2 = annotate_lexpr env le1 t_le1 in
annotate_set_array ~loc:le env (size, t) t_e (le2, ses2, e_index)
| _ -> invalid_expr (expr_of_lexpr le1))
| _ -> conflict ~loc:le1 [ default_t_bits ] t_le1
)
| LE_SetField (le1, field) ->
(let t_le1, _, _ = expr_of_lexpr le1 |> annotate_expr env in
let le2, ses = annotate_lexpr env le1 t_le1 in
let t_le1_anon = Types.make_anonymous env t_le1 in
match t_le1_anon.desc with
| T_Exception fields | T_Record fields ->
let t =
match List.assoc_opt field fields with
| None -> fatal_from ~loc (Error.BadField (field, t_le1))
| Some t -> t
in
let+ () = check_type_satisfies ~loc env t_e t in
( LE_SetField (le2, field) |> here,
ses |: TypingRule.LESetStructuredField )
| T_Bits (_, bitfields) ->
let bits slices bitfields =
T_Bits (slices_width env slices, bitfields) |> here
in
let t, slices =
match find_bitfield_opt field bitfields with
| None ->
fatal_from ~loc:le1 (Error.BadField (field, t_le1_anon))
| Some (BitField_Simple (_field, slices)) ->
(bits slices [], slices)
| Some (BitField_Nested (_field, slices, bitfields')) ->
(bits slices bitfields', slices)
| Some (BitField_Type (_field, slices, t)) ->
let t' = bits slices [] in
let+ () = check_type_satisfies ~loc env t' t in
(t, slices)
in
let+ () = check_type_satisfies ~loc:le1 env t_e t in
let le3 = LE_Slice (le1, slices) |> here in
annotate_lexpr env le3 t_e |: TypingRule.LESetBitField
| _ ->
conflict ~loc:le1
[ default_t_bits; T_Record []; T_Exception [] ]
t_e)
|: TypingRule.LESetBadField
| LE_SetFields (le_base, le_fields, []) -> (
let t_base, _, _ = expr_of_lexpr le_base |> annotate_expr env in
let le_base_annot, ses_base = annotate_lexpr env le_base t_base in
let t_base_anon = Types.make_anonymous env t_base in
match t_base_anon.desc with
| T_Bits (_, bitfields) ->
let slices_of_bitfield field =
match find_bitfields_slices_opt field bitfields with
| None -> fatal_from ~loc (Error.BadField (field, t_base_anon))
| Some slices -> slices
in
let le_slice =
LE_Slice
(le_base_annot, list_concat_map slices_of_bitfield le_fields)
|> here
in
annotate_lexpr env le_slice t_e |: TypingRule.LESetFields
| T_Record base_fields ->
let fold_bitvector_fields field (start, slices) =
match List.assoc_opt field base_fields with
| None -> fatal_from ~loc (Error.BadField (field, t_base_anon))
| Some t_field ->
let field_width =
get_bitvector_const_width ~loc env t_field
in
(start + field_width, (start, field_width) :: slices)
in
let length, slices =
List.fold_right fold_bitvector_fields le_fields (0, [])
in
let t_lhs = T_Bits (expr_of_int length, []) |> here in
let+ () = check_type_satisfies ~loc env t_e t_lhs in
(LE_SetFields (le_base_annot, le_fields, slices) |> here, ses_base)
| _ -> conflict ~loc [ default_t_bits ] t_base |: TypingRule.LESetFields
)
| LE_SetArray (e_base, e_index) -> (
let t_base, _, _ = expr_of_lexpr e_base |> annotate_expr env in
let t_anon_base = Types.make_anonymous env t_base in
match t_anon_base.desc with
| T_Array (size, t_elem) ->
let e_base', ses_base = annotate_lexpr env e_base t_base in
annotate_set_array ~loc env (size, t_elem) t_e
(e_base', ses_base, e_index)
| _ -> conflict ~loc [ default_array_ty ] t_base)
| LE_SetFields (_, _, _ :: _) | LE_SetEnumArray _ -> assert false
let can_be_initialized_with env s t =
let s_struct = Types.get_structure env s in
match s_struct.desc with
| T_Int (Parameterized _) -> assert false
| _ -> Types.type_satisfies env t s
let check_can_be_initialized_with ~loc env s t () =
if can_be_initialized_with env s t then () else conflict ~loc [ s.desc ] t
let should_remember_immutable_expression ses =
let ses_non_assert = SES.remove_assertions ses in
SES.is_symbolically_evaluable ses_non_assert
|: TypingRule.ShouldRememberImmutableExpression
let add_immutable_expression env ldk typed_e_opt x =
match (ldk, typed_e_opt) with
| (LDK_Constant | LDK_Let), Some (_, e, ses_e)
when should_remember_immutable_expression ses_e -> (
match StaticModel.normalize_opt env e with
| Some e' ->
add_local_immutable_expr x e' env
|: TypingRule.AddImmutableExpression
| None -> env)
| _ -> env
let rec inherit_integer_constraints ~loc lhs_ty rhs_ty =
match (lhs_ty.desc, rhs_ty.desc) with
| T_Int PendingConstrained, T_Int (WellConstrained _) -> rhs_ty
| T_Int PendingConstrained, _ ->
fatal_from ~loc (Error.ConstrainedIntegerExpected rhs_ty)
| T_Tuple lhs_tys, T_Tuple rhs_tys ->
if List.compare_lengths lhs_tys rhs_tys != 0 then
fatal_from ~loc
(Error.BadArity
( Static,
"tuple initialization",
List.length rhs_tys,
List.length lhs_tys ))
else
let lhs_tys' =
List.map2
(inherit_integer_constraints ~loc:(to_pos lhs_ty))
lhs_tys rhs_tys
in
T_Tuple lhs_tys' |> add_pos_from ~loc:lhs_ty
| _ -> lhs_ty
let annotate_local_decl_item ~loc (env : env) ty ldk ?e ldi =
let () =
if false then Format.eprintf "Annotating %a.@." PP.pp_local_decl_item ldi
in
match ldi with
| LDI_Var x ->
let+ () = check_var_not_in_env ~loc env x in
let env2 = add_local x ty ldk env in
let new_env = add_immutable_expression env2 ldk e x in
new_env |: TypingRule.LDVar
| LDI_Tuple names ->
let tys =
match (Types.make_anonymous env ty).desc with
| T_Tuple tys when List.compare_lengths tys names = 0 -> tys
| T_Tuple tys ->
fatal_from ~loc
(Error.BadArity
( Static,
"tuple initialization",
List.length tys,
List.length names ))
| _ -> conflict ~loc [ T_Tuple [] ] ty
in
let new_env =
List.fold_right2
(fun ty' name env' ->
let+ () = check_var_not_in_env ~loc env' name in
add_local name ty' ldk env')
tys names env
in
new_env |: TypingRule.LDTuple
let declare_local_constant env v = function
| LDI_Var x -> add_local_constant x v env
| LDI_Tuple _ -> env
let rec annotate_stmt env s : stmt * env * SES.t =
let () =
if false then
match s.desc with
| S_Seq _ -> ()
| _ -> Format.eprintf "@[<3>Annotating@ @[%a@]@]@." PP.pp_stmt s
in
let here x = add_pos_from ~loc:s x and loc = to_pos s in
match s.desc with
| S_Pass -> (s, env, SES.empty) |: TypingRule.SPass
| S_Seq (s1, s2) ->
let new_s1, env1, ses1 = try_annotate_stmt env s1 in
let new_s2, env2, ses2 = try_annotate_stmt env1 s2 in
let ses = SES.union ses1 ses2 in
(S_Seq (new_s1, new_s2) |> here, env2, ses) |: TypingRule.SSeq
| S_Assign (le, re) ->
(let () =
if false then
Format.eprintf "@[<3>Annotating assignment@ @[%a@]@]@." PP.pp_stmt
s
in
let ((t_re, re1, ses_re) as typed_re) = annotate_expr env re in
match s.version with
| V1 ->
let le1, ses_le = annotate_lexpr env le t_re in
let ses = SES.union ses_re ses_le in
(S_Assign (le1, re1) |> here, env, ses)
| V0 -> (
let reduced = setter_should_reduce_to_call_s env le typed_re in
match reduced with
| Some (new_s, ses_s) -> (new_s, env, ses_s)
| None ->
let env1 =
match ASTUtils.ldi_of_lexpr le with
| None -> env
| Some ldi ->
let undefined = function
| LDI_Var x -> is_undefined x env
| LDI_Tuple names ->
List.for_all (fun x -> is_undefined x env) names
in
if undefined ldi then
let () =
if false then
Format.eprintf
"@[<3>Assignment@ @[%a@] as declaration@]@."
PP.pp_stmt s
in
let ldk = LDK_Var in
let env2 =
annotate_local_decl_item ~loc env t_re ldk ldi
in
env2
else env
in
let le1, ses_le = annotate_lexpr env1 le t_re in
let ses = SES.union ses_re ses_le in
(S_Assign (le1, re1) |> here, env1, ses)))
|: TypingRule.SAssign
| S_Call call ->
let call, ty, ses = annotate_call ~loc env call in
let () = assert (ty = None) in
(S_Call call |> here, env, ses) |: TypingRule.SCall
| S_Return e_opt ->
(match (env.local.return_type, e_opt) with
| None, Some _ | Some _, None ->
fatal_from ~loc (Error.BadReturnStmt env.local.return_type)
|: TypingRule.SReturn
| None, None ->
(S_Return None |> here, env, SES.empty) |: TypingRule.SReturn
| Some t, Some e ->
let t_e', e', ses = annotate_expr env e in
let () =
if false then
Format.eprintf
"Can I return %a(of type %a) when return_type = %a?@."
PP.pp_expr e PP.pp_ty t_e' PP.pp_ty t
in
let+ () = check_type_satisfies ~loc env t_e' t in
(S_Return (Some e') |> here, env, ses))
|: TypingRule.SReturn
| S_Cond (e, s1, s2) ->
let t_cond, e_cond, ses_cond = annotate_expr env e in
let+ () = check_type_satisfies ~loc:e_cond env t_cond boolean in
let s1', ses1 = try_annotate_block env s1 in
let s2', ses2 = try_annotate_block env s2 in
let ses = SES.union3 ses_cond ses1 ses2 in
(S_Cond (e_cond, s1', s2') |> here, env, ses) |: TypingRule.SCond
| S_Assert e ->
let t_e', e', ses_e = annotate_expr env e in
let+ () = check_is_pure e ses_e in
let+ () = check_type_satisfies ~loc env t_e' boolean in
let ses = SES.add_assertion ses_e in
(S_Assert e' |> here, env, ses) |: TypingRule.SAssert
| S_While (e1, limit1, s1) ->
let t, e2, ses_e = annotate_expr env e1 in
let limit2, ses_limit = annotate_limit_expr ~loc env limit1 in
let+ () = check_type_satisfies ~loc:e2 env t boolean in
let s2, ses_block = try_annotate_block env s1 in
let ses = SES.union3 ses_e ses_block ses_limit in
(S_While (e2, limit2, s2) |> here, env, ses) |: TypingRule.SWhile
| S_Repeat (s1, e1, limit1) ->
let s2, ses_block = try_annotate_block env s1 in
let limit2, ses_limit = annotate_limit_expr ~loc env limit1 in
let t, e2, ses_e = annotate_expr env e1 in
let+ () = check_type_satisfies ~loc:e2 env t boolean in
let ses = SES.union3 ses_block ses_e ses_limit in
(S_Repeat (s2, e2, limit2) |> here, env, ses) |: TypingRule.SRepeat
| S_For { index_name; start_e; end_e; dir; body; limit } ->
let start_t, start_e', ses_start = annotate_expr env start_e
and end_t, end_e', ses_end = annotate_expr env end_e
and limit', ses_limit =
annotate_limit_expr ~warn:false ~loc env limit
in
let+ () = check_is_pure start_e ses_start in
let+ () = check_is_deterministic start_e ses_start in
let+ () = check_is_pure end_e ses_end in
let+ () = check_is_deterministic end_e ses_end in
let ses_cond = SES.union3 ses_start ses_end ses_limit in
let start_struct = Types.make_anonymous env start_t
and end_struct = Types.make_anonymous env end_t in
let cs =
match (start_struct.desc, end_struct.desc) with
| T_Int UnConstrained, T_Int _ | T_Int _, T_Int UnConstrained ->
UnConstrained
| T_Int _, T_Int _ ->
let start_n = StaticModel.try_normalize env start_e'
and end_n = StaticModel.try_normalize env end_e' in
let e_bot, e_top =
match dir with
| Up -> (start_n, end_n)
| Down -> (end_n, start_n)
in
WellConstrained [ Constraint_Range (e_bot, e_top) ]
| T_Int _, _ -> conflict ~loc [ integer' ] end_t
| _, _ -> conflict ~loc [ integer' ] start_t
in
let ty = T_Int cs |> here in
let body', ses_block =
let+ () = check_var_not_in_env ~loc env index_name in
let env' = add_local index_name ty LDK_Let env in
try_annotate_block env' body
in
let ses = ses_non_conflicting_union ~loc ses_cond ses_block in
( S_For
{
index_name;
dir;
start_e = start_e';
end_e = end_e';
body = body';
limit = limit';
}
|> here,
env,
ses )
|: TypingRule.SFor
| S_Decl (ldk, ldi, ty_opt, e_opt) -> (
match (ldk, e_opt) with
| _, Some e ->
let ((t_e, e', ses_e) as typed_e) = annotate_expr env e in
let () =
if false then
Format.eprintf "Found rhs side-effects: %a@." SES.pp_print ses_e
in
let env1, ty_opt', ses_ldi =
match ty_opt with
| None ->
let env1 =
annotate_local_decl_item ~loc env t_e ldk ~e:typed_e ldi
in
let ty_opt = if C.print_typed then Some t_e else None in
(env1, ty_opt, SES.empty)
| Some t ->
let t_e' = Types.get_structure env t_e in
let t = inherit_integer_constraints ~loc t t_e' in
let t', ses_t = annotate_type ~loc env t in
let+ () = check_can_be_initialized_with ~loc env t' t_e in
let env1 =
annotate_local_decl_item ~loc env t' ldk ~e:typed_e ldi
in
(env1, Some t', ses_t)
in
let ses = SES.union ses_e ses_ldi in
let new_env =
match ldk with
| LDK_Let | LDK_Var -> env1
| LDK_Constant -> (
let+ () = check_leq_constant_time ~loc:s typed_e in
try
let v = StaticInterpreter.static_eval env1 e in
declare_local_constant env1 v ldi
with Error.(ASLException _) -> env1)
in
(S_Decl (ldk, ldi, ty_opt', Some e') |> here, new_env, ses)
|: TypingRule.SDecl
| LDK_Var, None ->
(match ty_opt with
| None ->
fatal_from ~loc (Error.BadLDI ldi)
|: TypingRule.LDUninitialisedVar
| Some t ->
let t', ses_t' = annotate_type ~loc env t in
let e_init = base_value ~loc env t' in
let new_env =
annotate_local_decl_item ~loc env t' LDK_Var ldi
in
( S_Decl (LDK_Var, ldi, Some t', Some e_init) |> here,
new_env,
ses_t' )
|: TypingRule.LDUninitialisedTyped)
|: TypingRule.SDecl
| (LDK_Constant | LDK_Let), None ->
fatal_from ~loc UnrespectedParserInvariant)
| S_Throw (Some (e, _)) ->
let t_e, e', ses1 = annotate_expr env e in
let+ () = check_structure_exception ~loc env t_e in
let exn_name =
match t_e.desc with T_Named s -> s | _ -> assert false
in
let ses2 = SES.add_thrown_exception exn_name ses1 in
(S_Throw (Some (e', Some t_e)) |> here, env, ses2) |: TypingRule.SThrow
| S_Throw None ->
(s, env, SES.throws_exception "TODO") |: TypingRule.SThrow
| S_Try (s', catchers, otherwise) ->
let s'', ses1 = try_annotate_block env s' in
let ses2, catchers_and_ses =
list_fold_left_map (annotate_catcher ~loc env) ses1 catchers
in
let () =
if false then
Format.eprintf "After catchers, I have side effects:@ %a@."
SES.pp_print ses2
in
let catchers', catchers_sess = List.split catchers_and_ses in
let ses_catchers = SES.unions catchers_sess in
let otherwise', ses3, ses_otherwise =
match otherwise with
| None -> (None, ses2, SES.empty)
| Some block ->
let block', ses_block = try_annotate_block env block in
(Some block', SES.remove_thrown_exceptions ses2, ses_block)
in
let ses = SES.union3 ses3 ses_catchers ses_otherwise in
(S_Try (s'', catchers', otherwise') |> here, env, ses)
|: TypingRule.STry
| S_Print { args; newline; debug } ->
let args', sess =
List.map
(fun e ->
let ty, annot_e, ses_e = annotate_expr env e in
let+ () =
check_true (Types.is_singular env ty) @@ fun () ->
Error.fatal_from e (Error.BadPrintType ty)
in
(annot_e, ses_e))
args
|> List.split
in
let ses =
SES.non_conflicting_unions sess
~fail:(conflicting_side_effects_error ~loc)
in
(S_Print { args = args'; newline; debug } |> here, env, ses)
|: TypingRule.SPrint
| S_Pragma (id, args) ->
let () = warn_from ~loc (Error.PragmaUse id) in
let _, _, sess = List.map (annotate_expr env) args |> list_split3 in
let ses =
SES.non_conflicting_unions sess
~fail:(conflicting_side_effects_error ~loc)
in
(S_Pass |> here, env, ses) |: TypingRule.SPragma
| S_Unreachable -> (s, env, SES.empty)
and annotate_limit_expr ?(warn = true) ~loc env = function
| None ->
let () = if warn then warn_from ~loc Error.NoLoopLimit in
(None, SES.empty)
| Some limit ->
let new_limit, ses =
annotate_symbolic_constrained_integer ~loc env limit
in
(Some new_limit, ses) |: TypingRule.AnnotateLimitExpr
and annotate_catcher ~loc env ses_in (name_opt, ty, stmt) =
let ty', ses_ty = annotate_type ~loc env ty in
let+ () = check_structure_exception ~loc:ty' env ty' in
let new_stmt, ses_block =
let env' =
match name_opt with
| None -> env
| Some name ->
let+ () = check_var_not_in_env ~loc:stmt env name in
add_local name ty LDK_Let env
in
try_annotate_block env' stmt
and ses_filtered =
let ty_name = match ty'.desc with T_Named s -> s | _ -> assert false in
SES.filter_thrown_exceptions
(fun s -> not (Types.subtypes_names env s ty_name))
ses_in
in
let ses = SES.union ses_block ses_ty in
(ses_filtered, ((name_opt, ty, new_stmt), ses)) |: TypingRule.Catcher
and try_annotate_block env s =
( best_effort (s, SES.empty) @@ fun _ ->
let s, _env, ses = annotate_stmt env s in
(s, ses) )
|: TypingRule.Block
and try_annotate_stmt env s =
best_effort (s, env, SES.empty) (fun _ -> annotate_stmt env s)
and set_fields_should_reduce_to_call ~loc env x fields (t_e, e, ses_e) =
assert (loc.version = V0 && C.use_field_getter_extension);
let ( let* ) = Option.bind in
let _, _, callee, _ =
try Fn.try_subprogram_for_name ~loc env V0 x []
with Error.ASLException _ -> assert false
in
let* ty = callee.return_type in
let ty = Types.make_anonymous env ty in
let* name, args = should_fields_reduce_to_call env x ty fields in
let typed_args = (t_e, e, ses_e) :: List.map (annotate_expr env) args in
let call, ret_ty, ses_call =
annotate_call_v0 ~loc env name typed_args ST_Setter
in
let _, _, sess_args = list_split3 typed_args in
let ses = SES.union ses_call @@ ses_non_conflicting_unions ~loc sess_args in
let () = assert (ret_ty = None) in
Some (S_Call call |> add_pos_from ~loc, ses)
and setter_should_reduce_to_call_recurse ~loc env typed_e make_old_le sub_le =
let () = assert (loc.version = V0) in
let x = fresh_var "__setter_setfield" in
let here le = add_pos_from ~loc le in
let t_sub_re, sub_re, ses_sub_re =
expr_of_lexpr sub_le |> annotate_expr env
in
let ldi_x = LDI_Var x in
let env1 = annotate_local_decl_item ~loc env t_sub_re LDK_Var ldi_x in
let s1, ses_s1 =
(S_Decl (LDK_Var, ldi_x, None, Some sub_re) |> here, ses_sub_re)
in
let s2, ses_s2 =
let t_e, e, ses_e = typed_e in
let old_le = make_old_le (LE_Var x |> here) in
let old_le', ses_old_le = annotate_lexpr env1 old_le t_e in
(S_Assign (old_le', e) |> here, SES.union ses_old_le ses_e)
in
let typed_e_x = annotate_expr env1 (E_Var x |> here) in
match setter_should_reduce_to_call_s env1 sub_le typed_e_x with
| None -> None
| Some (s, ses_s) ->
Some (s_then (s_then s1 s2) s, SES.union3 ses_s1 ses_s2 ses_s)
and setter_should_reduce_to_call_s env le typed_e : (stmt * SES.t) option =
let () = assert (le.version = V0) in
let t_e, e, ses_e = typed_e in
let () =
if false then
Format.eprintf "@[<2>setter_..._s@ @[%a@]@ @[%a@]@]@." PP.pp_lexpr le
PP.pp_expr e
in
let loc = to_pos le in
let here d = add_pos_from ~loc d in
(if false then (fun o ->
let none f () = Format.fprintf f "no reduction." in
let pp_fst pp f (x, _y) = pp f x in
Format.eprintf "@[<2>Setter@ @[%a@ = %a@]@ gave @[%a@]@.@]" PP.pp_lexpr
le PP.pp_expr e
(Format.pp_print_option ~none (pp_fst PP.pp_stmt))
o;
o)
else Fun.id)
@@
match le.desc with
| LE_Discard -> None
| LE_SetField (sub_le, field) -> (
match sub_le.desc with
| LE_Var x
when C.use_field_getter_extension
&& should_reduce_to_call env x ST_Setter ->
set_fields_should_reduce_to_call env ~loc x [ field ] typed_e
| _ ->
let old_le le' = LE_SetField (le', field) |> here in
setter_should_reduce_to_call_recurse ~loc env typed_e old_le sub_le)
| LE_SetFields (sub_le, fields, slices) -> (
match sub_le.desc with
| LE_Var x
when C.use_field_getter_extension
&& should_reduce_to_call env x ST_Setter ->
set_fields_should_reduce_to_call env ~loc x fields typed_e
| _ ->
let old_le le' = LE_SetFields (le', fields, slices) |> here in
setter_should_reduce_to_call_recurse ~loc env typed_e old_le sub_le)
| LE_Slice (sub_le, slices) -> (
match sub_le.desc with
| LE_Var x
when should_reduce_to_call env x ST_Setter
&& List.for_all slice_is_single slices ->
let args =
try List.map slice_as_single slices
with Invalid_argument _ -> assert false
in
let typed_args = typed_e :: List.map (annotate_expr env) args in
let call, ret_ty, ses_call =
annotate_call_v0 ~loc env x typed_args ST_Setter
in
let _, _, sess_args = list_split3 typed_args in
let ses =
SES.union ses_call @@ ses_non_conflicting_unions ~loc sess_args
in
let () = assert (ret_ty = None) in
Some (S_Call call |> here, ses)
| _ ->
let old_le le' = LE_Slice (le', slices) |> here in
setter_should_reduce_to_call_recurse ~loc env typed_e old_le sub_le)
| LE_Destructuring les -> (
match (Types.make_anonymous env t_e).desc with
| T_Tuple t_es when List.compare_lengths les t_es = 0 ->
let x = fresh_var "__setter_destructuring" in
let ldi_x = LDI_Var x in
let env1 =
annotate_local_decl_item ~loc env t_e LDK_Let ~e:typed_e ldi_x
in
let sub_e i = E_GetItem (E_Var x |> here, i) |> here in
let recurse_one i sub_le t_sub_e =
setter_should_reduce_to_call_s env1 sub_le
(t_sub_e, sub_e i, SES.empty)
in
let subs = list_mapi2 recurse_one 0 les t_es in
if List.for_all Option.is_none subs then None
else
let s0 = S_Decl (LDK_Let, ldi_x, None, Some e) |> here in
let produce_one i sub_le t_sub_e_i = function
| None ->
let sub_le', sub_le_ses =
annotate_lexpr env sub_le t_sub_e_i
in
(S_Assign (sub_le', sub_e i) |> here, sub_le_ses)
| Some (s, ses) -> (s, ses)
in
let stmts, sess =
list_mapi3 produce_one 0 les t_es subs |> List.split
in
let s = stmt_from_list (s0 :: stmts)
and ses = SES.unions (ses_e :: sess) in
Some (s, ses)
| _ -> None)
| LE_Var x ->
let st = ST_EmptySetter in
if should_reduce_to_call env x st then
let args = [ typed_e ] in
let call, ret_ty, ses_call = annotate_call_v0 ~loc env x args st in
let () = assert (ret_ty = None) in
let ses = SES.union ses_call ses_e in
Some (S_Call call |> here, ses)
else None
| LE_SetArray _ | LE_SetEnumArray _ -> assert false
(** [func_sig_types f] returns a list of the types in the signature [f].
The return type is first, followed by the argument types in order. *)
let func_sig_types func_sig =
let arg_types = List.map snd func_sig.args in
let return_type =
match func_sig.return_type with None -> [] | Some ty -> [ ty ]
in
return_type @ arg_types
(** The parameters in a function signature, in order. *)
let ~env func_sig =
let rec parameters_of_expr ~env e =
match e.desc with
| E_Var x -> if is_undefined x env then [ x ] else []
| E_Binop (_, e1, e2) ->
parameters_of_expr ~env e1 @ parameters_of_expr ~env e2
| E_Unop (_, e) -> parameters_of_expr ~env e
| E_Literal _ -> []
| _ -> Error.fatal_from (to_pos e) (Error.UnsupportedExpr (Static, e))
in
let parameters_of_constraint ~env c =
match c with
| Constraint_Exact e -> parameters_of_expr ~env e
| Constraint_Range (e1, e2) ->
parameters_of_expr ~env e1 @ parameters_of_expr ~env e2
in
let rec parameters_of_ty ~env ty =
match ty.desc with
| T_Bits (e, _) -> parameters_of_expr ~env e
| T_Tuple tys -> list_concat_map (parameters_of_ty ~env) tys
| T_Int (WellConstrained cs) ->
list_concat_map (parameters_of_constraint ~env) cs
| T_Int UnConstrained | T_Real | T_String | T_Bool | T_Array _ | T_Named _
->
[]
| _ -> Error.fatal_from (to_pos ty) (Error.UnsupportedTy (Static, ty))
in
let types = func_sig_types func_sig in
let all_parameters = list_concat_map (parameters_of_ty ~env) types in
uniq all_parameters
(** The set of variables which could define a parameter in a function signature. *)
let ~env f =
let rec defining_of_ty ~env acc ty =
match ty.desc with
| T_Bits ({ desc = E_Var x; _ }, _) ->
if is_undefined x env then ISet.add x acc else acc
| T_Tuple tys -> List.fold_left (defining_of_ty ~env) acc tys
| _ -> acc
in
let types = func_sig_types f in
List.fold_left (defining_of_ty ~env)
(ISet.of_list (List.map fst f.args))
types
let annotate_func_sig_v1 ~loc genv func_sig =
let env = with_empty_local genv in
let recurse_limit, ses_recurse_limit =
annotate_limit_expr ~warn:false ~loc env func_sig.recurse_limit
in
let (env_with_params, ses_with_params), parameters =
let declare_parameter (new_env, new_ses) (x, ty_opt) =
let ty, ses_ty =
match ty_opt with
| None | Some { desc = T_Int UnConstrained; _ } ->
(Types.parameterized_ty x, SES.empty)
| Some ty ->
annotate_type ~loc env ty
in
let+ () = check_constrained_integer ~loc env ty in
let+ () = check_var_not_in_env ~loc new_env x in
let new_env' = add_local x ty LDK_Let new_env
and ses = SES.union new_ses ses_ty in
((new_env', ses), (x, Some ty))
in
list_fold_left_map declare_parameter (env, ses_recurse_limit)
func_sig.parameters
in
let+ () =
let inferred_parameters = extract_parameters ~env func_sig in
let declared_parameters = List.map fst func_sig.parameters in
let all_parameters_declared =
list_equal String.equal inferred_parameters declared_parameters
in
check_true all_parameters_declared @@ fun () ->
fatal_from ~loc
(BadParameterDecl
(func_sig.name, inferred_parameters, declared_parameters))
in
let (env_with_args, ses_with_args), args =
let declare_argument (new_env, new_ses) (x, ty) =
let ty, ses_ty = annotate_type ~loc env_with_params ty in
let+ () = check_var_not_in_env ~loc new_env x in
let new_env = add_local x ty LDK_Let new_env
and ses = SES.union new_ses ses_ty in
((new_env, ses), (x, ty))
in
list_fold_left_map declare_argument
(env_with_params, ses_with_params)
func_sig.args
in
let env_with_return, return_type, ses_with_return =
match func_sig.return_type with
| None -> (env_with_args, None, ses_with_args)
| Some ty ->
let new_ty, ses_ty = annotate_type ~loc env_with_params ty in
let return_type = Some new_ty in
let local_env = { env_with_args.local with return_type } in
let new_ses = SES.union ses_ty ses_with_args in
({ env_with_args with local = local_env }, return_type, new_ses)
in
let ses = SES.remove_locals ses_with_return in
( env_with_return,
{ func_sig with parameters; args; return_type; recurse_limit },
ses )
let annotate_func_sig_v0 ~loc genv func_sig =
let env = with_empty_local genv in
let recurse_limit, ses_with_limit =
annotate_limit_expr ~warn:false ~loc env func_sig.recurse_limit
in
let inferred_parameters = extract_parameters ~env func_sig in
let+ () =
let defining = extract_parameter_defining ~env func_sig in
let undefined_parameters =
List.filter (fun x -> not (ISet.mem x defining)) inferred_parameters
in
check_true (list_is_empty undefined_parameters) @@ fun () ->
fatal_from ~loc (ParameterWithoutDecl (List.hd undefined_parameters))
in
let (env_with_params, ses_with_params), typed_parameters =
let declare_parameter (new_env, new_ses) x =
let ty, ses_ty =
match List.assoc_opt x func_sig.args with
| None | Some { desc = T_Int UnConstrained } ->
(Types.parameterized_ty x, SES.empty)
| Some ty ->
annotate_type ~loc env ty
in
let+ () = check_constrained_integer ~loc env ty in
let+ () = check_var_not_in_env ~loc new_env x in
let new_ses = SES.union new_ses ses_ty
and new_env = add_local x ty LDK_Let new_env in
((new_env, new_ses), (x, ty))
in
list_fold_left_map declare_parameter (env, ses_with_limit)
inferred_parameters
in
let parameters = List.map (fun (x, ty) -> (x, Some ty)) typed_parameters in
let (env_with_args, ses_with_args), args =
let declare_argument (new_env, new_ses) (x, ty) =
match List.assoc_opt x typed_parameters with
| Some ({ desc = T_Int (Parameterized _) } as loc) ->
((new_env, new_ses), (x, T_Int UnConstrained |> add_pos_from ~loc))
| Some ty -> ((new_env, new_ses), (x, ty))
| None ->
let ty, ses_ty = annotate_type ~loc env_with_params ty in
let+ () = check_var_not_in_env ~loc new_env x in
let new_ses = SES.union new_ses ses_ty
and new_env = add_local x ty LDK_Let new_env in
((new_env, new_ses), (x, ty))
in
list_fold_left_map declare_argument
(env_with_params, ses_with_params)
func_sig.args
in
let env_with_return, return_type, ses_with_return =
match func_sig.return_type with
| None -> (env_with_args, None, ses_with_args)
| Some ty ->
let new_ty, ses_ty = annotate_type ~loc env_with_params ty in
let return_type = Some new_ty in
let local_env = { env_with_args.local with return_type } in
let new_ses = SES.union ses_ty ses_with_args in
({ env_with_args with local = local_env }, return_type, new_ses)
in
( env_with_return,
{ func_sig with parameters; args; return_type; recurse_limit },
ses_with_return )
let annotate_func_sig ~loc genv func_sig =
match loc.version with
| V0 -> annotate_func_sig_v0 ~loc genv func_sig
| V1 -> annotate_func_sig_v1 ~loc genv func_sig
module ControlFlow : sig
val check_stmt_returns_or_throws : identifier -> stmt_desc annotated -> prop
(** [check_stmt_interrupts name env body] checks that the function named
[name] with the statement body [body] returns a value or throws an
exception. *)
end = struct
(** Possible Control-Flow actions of a statement. *)
type t =
| Interrupt (** Throwing an exception or returning a value. *)
| AssertedNotInterrupt
(** Assert that this control-flow path is unused. *)
| MayNotInterrupt
(** Among all control-flow path in a statement, there is one that
will not throw an exception nor return a value. *)
(** Sequencial combination of two control flows. *)
let seq t1 t2 =
if t1 = MayNotInterrupt then t2 else t1 |: TypingRule.ControlFlowSeq
(** [join t1 t2] corresponds to the parallel combination of [t1] and [t2].
More precisely, it is the maximal element in the ordering
AssertedNotInterrupt < Interrupt < MayNotInterrupt
*)
let join t1 t2 =
match (t1, t2) with
| MayNotInterrupt, _ | _, MayNotInterrupt ->
MayNotInterrupt |: TypingRule.ControlFlowJoin
| AssertedNotInterrupt, t | t, AssertedNotInterrupt ->
t
| Interrupt, Interrupt -> Interrupt
(** [get_from_stmt env s] builds the control-flow analysis on [s] in [env].
*)
let rec from_stmt s =
match s.desc with
| S_Pass | S_Decl _ | S_Assign _ | S_Assert _ | S_Call _ | S_Print _
| S_Pragma _ ->
MayNotInterrupt |: TypingRule.ControlFlowFromStmt
| S_Unreachable -> AssertedNotInterrupt
| S_Return _ | S_Throw _ -> Interrupt
| S_Seq (s1, s2) -> seq (from_stmt s1) (from_stmt s2)
| S_Cond (_, s1, s2) -> join (from_stmt s1) (from_stmt s2)
| S_Repeat (body, _, _) -> from_stmt body
| S_While _ | S_For _ -> MayNotInterrupt
| S_Try (body, catchers, otherwise) ->
let res0 = from_stmt body in
let res1 =
match otherwise with
| None -> res0
| Some s -> join (from_stmt s) res0
in
List.fold_left
(fun res (_, _, s) -> join res (from_stmt s))
res1 catchers
(** [check_stmt_interrupts name env body] checks that the function named
[name] with the statement body [body] returns a value or throws an
exception. *)
let check_stmt_returns_or_throws name s () =
match from_stmt s with
| AssertedNotInterrupt | Interrupt -> ()
| MayNotInterrupt -> fatal_from ~loc:s (Error.NonReturningFunction name)
end
let annotate_subprogram (env : env) (f : AST.func) ses_func_sig :
AST.func * SES.t =
let () =
if false then
Format.eprintf "@[<hov>Annotating body in env:@ %a@]@." pp_env env
in
let body =
match f.body with SB_ASL body -> body | SB_Primitive _ -> assert false
in
let new_body, ses_body = try_annotate_block env body in
let ses = SES.union ses_func_sig @@ SES.remove_locals ses_body in
let () =
if false then
Format.eprintf "@[<v 2>For program %s, I got side-effects:@ %a@]@."
f.name SES.pp_print ses
in
let+ () =
match f.return_type with
| None -> ok
| Some _ -> ControlFlow.check_stmt_returns_or_throws f.name new_body
in
({ f with body = SB_ASL new_body }, ses) |: TypingRule.Subprogram
let try_annotate_subprogram env f ses_func_sig =
best_effort (f, ses_func_sig) @@ fun _ ->
annotate_subprogram env f ses_func_sig
let check_setter_has_getter ~loc env (func_sig : AST.func) =
let fail () =
fatal_from ~loc (Error.SetterWithoutCorrespondingGetter func_sig)
in
let check_true thing = check_true thing fail in
match func_sig.subprogram_type with
| ST_Getter | ST_EmptyGetter | ST_Function | ST_Procedure -> ok
| ST_EmptySetter | ST_Setter ->
let ret_type, arg_types =
match func_sig.args with
| [] -> fatal_from ~loc Error.UnrespectedParserInvariant
| (_, ret_type) :: args -> (ret_type, List.map snd args)
in
let _, _, func_sig', _ =
try Fn.subprogram_for_name ~loc env V1 func_sig.name arg_types
with
| Error.(
ASLException
{ desc = NoCallCandidate _ | TooManyCallCandidates _; _ })
->
fail ()
in
let wanted_getter_type =
match func_sig.subprogram_type with
| ST_Setter -> ST_Getter
| ST_EmptySetter -> ST_EmptyGetter
| _ -> assert false
in
let+ () = check_true (func_sig'.subprogram_type = wanted_getter_type) in
let+ () =
let () = assert (List.compare_lengths func_sig'.args arg_types = 0) in
check_true
@@ List.for_all2
(fun (_, t1) t2 -> Types.type_equal env t1 t2)
func_sig'.args arg_types
in
let+ () =
match func_sig'.return_type with
| None ->
assert
false
| Some t -> check_true @@ Types.type_equal env ret_type t
in
ok |: TypingRule.CheckSetterHasGetter
let declare_one_func ~loc (func_sig : AST.func) ses_func_sig env =
let env1, name' =
best_effort (env, func_sig.name) @@ fun _ ->
Fn.add_new_func ~loc env func_sig.name func_sig.args
func_sig.subprogram_type
in
let () =
if false then
let open Format in
eprintf
"@[<hov>Adding function %s to env with@ return-type: %a@ and \
argtypes:@ %a@."
name' (pp_print_option PP.pp_ty) func_sig.return_type
(pp_print_list ~pp_sep:pp_print_space PP.pp_typed_identifier)
func_sig.args
in
let+ () = check_var_not_in_genv ~loc env1.global name' in
let+ () = check_setter_has_getter ~loc env1 func_sig in
let new_func_sig = { func_sig with name = name' } in
let init_ses =
match func_sig.body with
| SB_ASL _ | SB_Primitive true ->
SES.add_calls_recursive name' ses_func_sig
| SB_Primitive false -> ses_func_sig
in
(add_subprogram name' new_func_sig init_ses env1, new_func_sig)
|: TypingRule.DeclareOneFunc
let annotate_and_declare_func ~loc func_sig genv =
let env1, func_sig1, ses_f1 = annotate_func_sig ~loc genv func_sig in
(declare_one_func ~loc func_sig1 ses_f1 env1, ses_f1)
|: TypingRule.AnnotateAndDeclareFunc
let add_global_storage ~loc name keyword genv ty =
if is_global_ignored name then genv
else
let+ () = check_var_not_in_genv ~loc genv name in
add_global_storage name ty keyword genv |: TypingRule.AddGlobalStorage
let declare_const ~loc name t v genv =
add_global_storage ~loc name GDK_Constant genv t
|> add_global_constant name v |: TypingRule.DeclareConst
let declare_type ~loc name ty s genv =
let () =
if false then Format.eprintf "Declaring type %s of %a@." name PP.pp_ty ty
in
let here x = add_pos_from ~loc:ty x in
let+ () = check_var_not_in_genv ~loc genv name in
let env = with_empty_local genv in
let env1, t1 =
match s with
| None -> (env, ty)
| Some (super, ) ->
let+ () =
fun () ->
if Types.subtype_satisfies env ty (T_Named super |> here) then ()
else conflict ~loc [ T_Named super ] ty
in
let new_ty =
if extra_fields = [] then ty
else
match IMap.find_opt super genv.declared_types with
| Some ({ desc = T_Record fields; _ }, _) ->
T_Record (fields @ extra_fields) |> here
| Some ({ desc = T_Exception fields; _ }, _) ->
T_Exception (fields @ extra_fields) |> here
| Some _ -> conflict ~loc [ T_Record []; T_Exception [] ] ty
| None -> undefined_identifier ~loc super
and env = add_subtype name super env in
(env, new_ty)
in
let t2, ses_t = annotate_type ~decl:true ~loc env1 t1 in
let time_frame = SES.max_time_frame ses_t in
let env2 = add_type name t2 time_frame env1 in
let new_tenv =
match t2.desc with
| T_Enum ids ->
let t = T_Named name |> here in
let declare_one env2 label =
declare_const ~loc label t (L_Label label) env2
in
let genv3 = List.fold_left declare_one env2.global ids in
{ env2 with global = genv3 }
| _ -> env2
in
let () = if false then Format.eprintf "Declared %s.@." name in
new_tenv.global
let try_add_global_constant name env e =
try
let v = StaticInterpreter.static_eval env e in
{ env with global = add_global_constant name v env.global }
with Error.(ASLException { desc = UnsupportedExpr _; _ }) -> env
let declare_global_storage ~loc gsd genv =
let () = if false then Format.eprintf "Declaring %s@." gsd.name in
best_effort (gsd, genv) @@ fun _ ->
let here x = add_pos_from ~loc x in
let { keyword; initial_value; ty = ty_opt; name } = gsd in
let+ () = check_var_not_in_genv ~loc genv name in
let env = with_empty_local genv in
let target_time_frame = TimeFrame.of_gdk keyword in
let typed_initial_value, ty_opt', declared_t =
match (ty_opt, initial_value) with
| Some t, Some e ->
let t', ses_t = annotate_type ~loc env t
and ((t_e, _e', _vses_e) as typed_e) = annotate_expr env e in
let+ () = check_type_satisfies ~loc env t_e t' in
let+ () =
let fake_e_for_error = E_ATC (e, t') |> here in
check_is_time_frame ~loc target_time_frame
(t', fake_e_for_error, ses_t)
in
(typed_e, Some t', t')
| Some t, None ->
let t', ses_t = annotate_type ~loc env t in
let+ () =
let fake_e_for_error = E_ATC (E_Var "-" |> here, t') |> here in
check_is_time_frame ~loc target_time_frame
(t', fake_e_for_error, ses_t)
in
let e' = base_value ~loc env t' in
((t', e', SES.empty), Some t', t')
| None, Some e ->
let ((t_e, _e', _ses_e) as typed_e) = annotate_expr env e in
(typed_e, None, t_e)
| None, None -> fatal_from ~loc UnrespectedParserInvariant
in
let genv1 = add_global_storage ~loc name keyword genv declared_t in
let env1 = with_empty_local genv1 in
let _, initial_value', ses_initial_value = typed_initial_value in
let env2 =
match keyword with
| GDK_Constant ->
let+ () = check_leq_constant_time ~loc typed_initial_value in
try_add_global_constant name env1 initial_value'
| GDK_Let when should_remember_immutable_expression ses_initial_value -> (
match StaticModel.normalize_opt env1 initial_value' with
| Some e' -> add_global_immutable_expr name e' env1
| None -> env1)
| GDK_Config ->
let+ () = check_leq_config_time ~loc typed_initial_value in
env1
| _ -> env1
in
let () = assert (env2.local == empty_local) in
let ty_opt' = if C.print_typed then Some declared_t else ty_opt' in
({ gsd with ty = ty_opt'; initial_value = Some initial_value' }, env2.global)
|: TypingRule.DeclareGlobalStorage
let type_check_decl d (acc, genv) =
let here = add_pos_from_st d and loc = to_pos d in
let () =
if false then
Format.eprintf "@[<v>Typing with %s in env:@ %a@]@." strictness_string
pp_global genv
else if false then Format.eprintf "@[Typing %a.@]@." PP.pp_t [ d ]
in
let new_d, new_genv =
match d.desc with
| D_Func ({ body = SB_ASL _; _ } as f) ->
let (env1, f1), ses_func_sig =
annotate_and_declare_func ~loc f genv
in
let new_f, ses_f = try_annotate_subprogram env1 f1 ses_func_sig in
let () =
if
ISet.mem f.name (SES.get_calls_recursives ses_f)
&& Option.is_none f.recurse_limit
then warn_from ~loc Error.(NoRecursionLimit [ f.name ])
in
let ses_f = SES.remove_calls_recursives ses_f in
let new_d = D_Func new_f |> here
and new_env = StaticEnv.add_subprogram new_f.name new_f ses_f env1 in
(new_d, new_env.global) |: TypingRule.TypecheckDecl
| D_Func ({ body = SB_Primitive _; _ } as f) ->
let (new_env, new_f), _ = annotate_and_declare_func ~loc f genv in
let new_d = D_Func new_f |> here in
(new_d, new_env.global)
| D_GlobalStorage gsd ->
let gsd', new_genv = declare_global_storage ~loc gsd genv in
let new_d = D_GlobalStorage gsd' |> here in
(new_d, new_genv) |: TypingRule.TypecheckDecl
| D_TypeDecl (x, ty, s) ->
let new_genv = declare_type ~loc x ty s genv in
(d, new_genv) |: TypingRule.TypecheckDecl
| D_Pragma _ -> assert false
in
(new_d :: acc, new_genv)
let check_global_pragma genv d =
let loc = to_pos d in
match d.desc with
| D_Pragma (id, args) ->
let () = warn_from ~loc (Error.PragmaUse id) in
List.iter
(fun e -> annotate_expr (with_empty_local genv) e |> ignore)
args
|: TypingRule.CheckGlobalPragma
| _ -> assert false
let propagate_recursive_calls_sess (sess : (func * SES.t) list) :
(func * SES.t) list =
let () =
if false then
let open Format in
let pp_sep f () = fprintf f ";@ " in
let pp f ((func_sig : func), ses) =
fprintf f "@[<h 2>%s:@ %a@]" func_sig.name SES.pp_print ses
in
eprintf "@[<v 2>Propagating side-effects from:@ @[<v 2>[%a]@]@]@."
(pp_print_list ~pp_sep pp) sess
in
let map0 =
List.map (fun ((f : func), ses) -> (f.name, ses)) sess |> IMap.of_list
in
let call_graph = IMap.map (fun ses -> SES.get_calls_recursives ses) map0 in
let transitive_call_graph = transitive_closure call_graph in
let map0_without_recursive_calls =
IMap.map (fun ses -> SES.remove_calls_recursives ses) map0
in
let res =
List.map
(fun ((func : func), ses) ->
let callees =
IMap.find func.name transitive_call_graph |> ISet.elements
in
let sess =
List.map (fun x -> IMap.find x map0_without_recursive_calls) callees
in
(func, SES.unions (SES.remove_calls_recursives ses :: sess)))
sess
in
let () =
if false then
let open Format in
let pp_sep f () = fprintf f ";@ " in
let pp f ((func_sig : func), ses) =
fprintf f "@[<h 2>%s:@ %a@]" func_sig.name SES.pp_print ses
in
eprintf "@[<v 2>Propagating side-effects from:@ @[<v 2>[%a]@]@]@."
(pp_print_list ~pp_sep pp) res
in
res
(** [check_recursive_limit_annotations locs sess] emits a warning if there a
cycle in the call-graph described by [sess] without static annotations.
The argument [locs] is only used for identifying an location in which to
print the error.
*)
let check_recursive_limit_annotations locs sess =
let call_graph_without_annotated_functions =
List.filter_map
(function
| { recurse_limit = None; body = SB_ASL _; name }, ses ->
Some (name, SES.get_calls_recursives ses)
| _ -> None)
sess
|> IMap.of_list
in
match get_cycle call_graph_without_annotated_functions with
| None -> ()
| Some [] -> assert false
| Some (x :: _ as cycle) ->
let loc =
List.find (fun d -> String.equal x (identifier_of_decl d)) locs
in
warn_from ~loc Error.(NoRecursionLimit cycle)
let type_check_mutually_rec ds (acc, genv0) =
let () =
if false then
let open Format in
eprintf "@[Type-checking@ mutually@ recursive@ declarations:@ %a@]@."
(pp_print_list ~pp_sep:pp_print_space pp_print_string)
(List.map identifier_of_decl ds)
in
let env_and_fs =
List.map
(fun d ->
let loc = to_pos d in
match d.desc with
| D_Func f ->
let env', f, ses_f = annotate_func_sig ~loc genv0 f in
(env'.local, f, ses_f, loc)
| _ ->
fatal_from ~loc
(Error.BadRecursiveDecls
(List.map ASTUtils.identifier_of_decl ds)))
ds
in
let env_and_fs1 =
let setters, others =
List.partition
(fun (_, f, _, _) ->
match f.subprogram_type with
| ST_Setter | ST_EmptySetter -> true
| _ -> false)
env_and_fs
in
List.rev_append others setters
in
let genv2, env_and_fs2 =
list_fold_left_map
(fun genv (lenv, f, ses_f, loc) ->
let env = { global = genv; local = lenv } in
let env1, f1 = declare_one_func ~loc f ses_f env in
(env1.global, (env1.local, f1, ses_f, loc)))
genv0 env_and_fs1
|: TypingRule.DeclareSubprograms
in
let ds, sess =
list_map_split
(fun (lenv2, f, ses_f, loc) ->
let env2 = { local = lenv2; global = genv2 } in
let here d = add_pos_from ~loc d in
match f.body with
| SB_ASL _ ->
let () =
if false then Format.eprintf "@[Analysing decl %s.@]@." f.name
in
let new_f, ses_f = try_annotate_subprogram env2 f ses_f in
(D_Func new_f |> here, (new_f, ses_f))
| SB_Primitive side_effecting ->
let ses =
if side_effecting then SES.calls_recursive f.name else SES.empty
in
(D_Func f |> here, (f, ses)))
env_and_fs2
in
let () = check_recursive_limit_annotations ds sess in
let env3 =
let sess_prop = propagate_recursive_calls_sess sess in
List.fold_left
(fun env2 ((new_f : func), ses_f) ->
StaticEnv.add_subprogram new_f.name new_f ses_f env2)
(StaticEnv.with_empty_local genv2)
sess_prop
in
(List.rev_append ds acc, env3.global) |: TypingRule.TypeCheckMutuallyRec
let type_check_ast_in_env =
let fold = function
| TopoSort.ASTFold.Single d -> type_check_decl d
| TopoSort.ASTFold.Recursive ds -> type_check_mutually_rec ds
in
let fold =
if false then (fun d e ->
let res = fold d e in
Format.eprintf "Ended type-checking of this declaration.@.";
res)
else fold
in
let fold_topo ast acc = TopoSort.ASTFold.fold fold ast acc in
fun env ast ->
let is_pragma d = match d.desc with D_Pragma _ -> true | _ -> false in
let pragmas, others = List.partition is_pragma ast in
let ast_rev, env = fold_topo others ([], env) in
let () = List.iter (check_global_pragma env) pragmas in
(List.rev ast_rev, env)
let type_check_ast ast = type_check_ast_in_env empty_global ast
end
module TypeCheckDefault = Annotate (struct
let check = TypeCheck
let output_format = Error.HumanReadable
let print_typed = false
let use_field_getter_extension = false
end)
let type_and_run ?instrumentation ast =
let ast, static_env =
Builder.with_stdlib ast
|> Builder.with_primitives Native.DeterministicBackend.primitives
|> TypeCheckDefault.type_check_ast
in
Native.interprete ?instrumentation static_env ast