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
open AST
open ASTUtils
open Infix
open StaticEnv
module TypingRule = Instrumentation.TypingRule
let ( |: ) = Instrumentation.TypingNoInstr.use_with
let fatal_from = Error.fatal_from
let undefined_identifier pos x = fatal_from pos (Error.UndefinedIdentifier x)
let unsupported_expr e = fatal_from e (Error.UnsupportedExpr e)
let conflict pos expected provided =
fatal_from pos (Error.ConflictingTypes (expected, provided))
let expr_of_z z = literal (L_Int z)
let plus = binop PLUS
let t_bits_bitwidth e = T_Bits (e, [])
let reduce_expr env e =
let open StaticInterpreter in
try Normalize.normalize env e with NotYetImplemented -> e
let reduce_constants env e =
let open StaticInterpreter in
let eval_expr env e =
try static_eval env e with NotYetImplemented -> unsupported_expr e
in
try eval_expr env e
with StaticEvaluationUnknown -> (
let () =
if false then
Format.eprintf
"@[<hov>Static evaluation failed. Trying to reduce.@ For %a@ at \
%a@]@."
PP.pp_expr e PP.pp_pos e
in
try reduce_expr env e |> eval_expr env
with StaticEvaluationUnknown -> unsupported_expr e)
let reduce_constraint env = function
| Constraint_Exact e -> Constraint_Exact (reduce_expr env e)
| Constraint_Range (e1, e2) ->
Constraint_Range (reduce_expr env e1, reduce_expr env e2)
let reduce_constraints env = function
| (UnConstrained | UnderConstrained _) as c -> c
| WellConstrained constraints ->
WellConstrained (List.map (reduce_constraint env) constraints)
let sum = function [] -> !$0 | [ x ] -> x | h :: t -> List.fold_left plus h t
let slices_width env =
let minus = binop MINUS in
let one = !$1 in
let slice_length = function
| Slice_Single _ -> one
| Slice_Star (_, e) | Slice_Length (_, e) -> e
| Slice_Range (e1, e2) -> plus one (minus e1 e2)
in
fun li -> List.map slice_length li |> sum |> reduce_expr env
let width_plus env acc w = plus acc w |> reduce_expr env
let rename_ty_eqs : (AST.identifier * AST.expr) list -> AST.ty -> AST.ty =
let subst_constraint eqs = function
| Constraint_Exact e -> Constraint_Exact (subst_expr eqs e)
| Constraint_Range (e1, e2) ->
Constraint_Range (subst_expr eqs e1, subst_expr eqs e2)
in
let subst_constraints eqs = List.map (subst_constraint eqs) in
fun eqs ty ->
match ty.desc with
| T_Bits (e, fields) ->
T_Bits (subst_expr eqs e, fields) |> add_pos_from_st ty
| T_Int (WellConstrained constraints) ->
let constraints = subst_constraints eqs constraints in
T_Int (WellConstrained constraints) |> add_pos_from_st ty
| _ -> ty
let annotate_literal = 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
exception ConstraintMinMaxTop
let min_constraint env = function
| Constraint_Exact e | Constraint_Range (e, _) -> (
let e = reduce_expr env e in
match e.desc with
| E_Literal (L_Int i) -> i
| _ ->
let () =
if false then
Format.eprintf "Min constraint found strange value %a@."
PP.pp_expr e
in
raise ConstraintMinMaxTop)
let max_constraint env = function
| Constraint_Exact e | Constraint_Range (_, e) -> (
let e = reduce_expr env e in
match e.desc with
| E_Literal (L_Int i) -> i
| _ ->
let () =
if false then
Format.eprintf "Max constraint found strange value %a@."
PP.pp_expr e
in
raise ConstraintMinMaxTop)
let min_max_constraints m_constraint m =
let rec do_rec env = function
| [] ->
failwith
"A well-constrained integer cannot have an empty list of constraints."
| [ c ] -> m_constraint env c
| c :: cs ->
let i = m_constraint env c and j = do_rec env cs in
m i j
in
do_rec
let min_constraints = min_max_constraints min_constraint min
and max_constraints = min_max_constraints max_constraint max
let get_first_duplicate li =
let exception Duplicate of identifier in
let folder acc elt =
let x = extractor elt in
let acc' = ISet.add x acc in
if acc' == acc then raise (Duplicate x) else acc'
in
try
let _ = List.fold_left folder ISet.empty li in
None
with Duplicate x -> Some x
type strictness = [ `Silence | `Warn | `TypeCheck ]
module type ANNOTATE_CONFIG = sig
val check : strictness
end
module Property (C : ANNOTATE_CONFIG) = struct
exception TypingAssumptionFailed
type ('a, 'b) property = 'a -> 'b
type prop = (unit, unit) property
let strictness_string =
match C.check with
| `TypeCheck -> "type-checking-strict"
| `Warn -> "type-checking-warn"
| `Silence -> "type-inference"
let check : prop -> prop =
match C.check with
| `TypeCheck -> fun f () -> f ()
| `Warn -> (
fun f () -> try f () with Error.ASLException e -> Error.eprintln e)
| `Silence -> fun _f () -> ()
let best_effort' : ('a, 'a) property -> ('a, 'a) property =
match C.check with
| `TypeCheck -> fun f x -> f x
| `Warn -> (
fun f x ->
try f x
with Error.ASLException e ->
Error.eprintln e;
x)
| `Silence -> ( fun f x -> try f x with Error.ASLException _ -> x)
let best_effort : 'a -> ('a, 'a) property -> 'a = fun x f -> best_effort' f x
let[@inline] ( let+ ) m f = check m () |> f
let[@inline] both (p1 : prop) (p2 : prop) () =
let () = p1 () in
let () = p2 () in
()
let either (p1 : ('a, 'b) property) (p2 : ('a, 'b) property) x =
try p1 x with TypingAssumptionFailed | Error.ASLException _ -> p2 x
let rec any (li : prop list) : prop =
match li with
| [] -> raise (Invalid_argument "any")
| [ f ] -> f
| p :: li -> either p (any li)
let assumption_failed () = raise_notrace TypingAssumptionFailed [@@inline]
let ok () = () [@@inline]
let check_true b fail () = if b then () else fail () [@@inline]
let check_true' b = check_true b assumption_failed [@@inline]
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
let has_subprogram_type_clash s1 s2 =
match (s1, s2) with
| ST_Function, _ | _, ST_Function | ST_Procedure, _ | _, ST_Procedure ->
true
| ST_Getter, ST_Getter | ST_Setter, ST_Setter -> true
| ST_Getter, ST_Setter | ST_Setter, ST_Getter -> false
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 arg_types subpgm_type =
match IMap.find_opt name env.global.subprogram_renamings with
| None ->
let env = set_renamings name (ISet.singleton name) env in
(env, name)
| Some set ->
let name' = name ^ "-" ^ string_of_int (ISet.cardinal set) in
let clash =
let arg_types = List.map snd arg_types in
(not (ISet.is_empty set))
&& ISet.exists
(fun name'' ->
let other_func_sig = IMap.find name'' env.global.subprograms in
has_subprogram_type_clash subpgm_type
other_func_sig.subprogram_type
&& has_arg_clash env arg_types other_func_sig.args)
set
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)
arg_types
in
Error.fatal_from loc (Error.AlreadyDeclaredIdentifier name)
in
let env = set_renamings name (ISet.add name' set) env in
(env, name')
let find_name loc env name caller_arg_types =
let () =
if false then Format.eprintf "Trying to rename call to %S@." name
in
match IMap.find_opt name env.global.subprogram_renamings with
| None -> (
match IMap.find_opt name env.global.subprograms with
| Some func_sig ->
let callee_arg_types = func_sig.args in
if has_arg_clash env caller_arg_types callee_arg_types then
let () =
if false then
Format.eprintf "Found already translated name: %S.@." name
in
( deduce_eqs env caller_arg_types callee_arg_types,
name,
callee_arg_types,
func_sig.return_type,
func_sig.parameters )
else fatal_from loc (Error.NoCallCandidate (name, caller_arg_types))
| None -> undefined_identifier loc name)
| Some set -> (
let finder name' acc =
let func_sig = IMap.find name' env.global.subprograms in
let callee_arg_types = func_sig.args in
if has_arg_clash env caller_arg_types callee_arg_types then
( deduce_eqs env caller_arg_types callee_arg_types,
name',
callee_arg_types,
func_sig.return_type,
func_sig.parameters )
:: acc
else acc
in
match ISet.fold finder set [] with
| [ res ] -> res
| [] -> fatal_from loc (Error.NoCallCandidate (name, caller_arg_types))
| _ :: _ ->
fatal_from loc
(Error.TooManyCallCandidates (name, caller_arg_types)))
let try_find_name loc env name caller_arg_types =
try find_name loc env 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 { args = callee_arg_types; return_type; parameters; _ } ->
if false then
Format.eprintf "@[<2>%a:@ No extra arguments for %s@]@." PP.pp_pos
loc name;
([], name, callee_arg_types, return_type, parameters)
with Error.ASLException _ -> raise error)
end
module Annotate (C : ANNOTATE_CONFIG) = struct
open Property (C)
module Fn = FunctionRenaming (C)
let should_reduce_to_call env name =
IMap.mem name env.global.subprogram_renamings
let should_slices_reduce_to_call env name slices =
let args =
try Some (List.map slice_as_single slices)
with Invalid_argument _ -> None
in
match args with
| None -> None
| Some args -> if should_reduce_to_call env name then Some args else None
let disjoint_slices_to_diet loc env slices =
let eval env e =
match reduce_constants env e with
| L_Int z -> Z.to_int z
| _ -> unsupported_expr e
in
let module DI = Diet.Int in
let one_slice loc env diet slice =
let interval =
let make x y =
if x > y then fatal_from loc @@ Error.OverlappingSlices [ slice ]
else DI.Interval.make x y
in
match slice with
| Slice_Single e ->
let x = eval env e in
make x x
| Slice_Range (e1, e2) ->
let x = eval env e2 and y = eval env e1 in
make x y
| Slice_Length (e1, e2) ->
let x = eval env e1 and y = eval env e2 in
make x (x + y - 1)
| Slice_Star (e1, e2) ->
let x = eval env e1 and y = eval env e2 in
make (x * y) ((x * (y + 1)) - 1)
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)
in
List.fold_left (one_slice loc env) Diet.Int.empty slices
exception NoSingleField
let to_singles env =
let eval e =
match reduce_constants env e with
| L_Int z -> Z.to_int z
| _ -> raise NoSingleField
in
let one slice k =
match slice with
| Slice_Single e -> e :: k
| Slice_Length (e1, e2) ->
let i1 = eval e1 and i2 = eval e2 in
let rec do_rec n =
if n >= i2 then k
else
let e = E_Literal (L_Int (Z.of_int (i1 + n))) |> add_dummy_pos 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 k
else
let e = E_Literal (L_Int (Z.of_int i)) |> add_dummy_pos in
e :: do_rec (i + 1)
in
do_rec i2
| Slice_Star _ -> raise NoSingleField
in
fun slices -> List.fold_right one slices []
let slices_of_bitfield = function
| BitField_Simple (_, slices)
| BitField_Nested (_, slices, _)
| BitField_Type (_, slices, _) ->
slices
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
let should_fields_reduce_to_call env name ty fields =
match ty.desc with
| T_Bits (_, bf) when should_reduce_to_call env name -> (
try Some (name, list_concat_map (field_to_single env bf) fields)
with NoSingleField -> None)
| _ -> None
let should_field_reduce_to_call env name ty field =
should_fields_reduce_to_call env name ty [ field ]
let check_type_satisfies' 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 assumption_failed ()
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
with TypingAssumptionFailed -> conflict loc [ default_t_bits ] t
(** [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 _ | UnderConstrained _) -> ()
| _ -> 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 storage_is_pure loc (env : env) s =
match IMap.find_opt s env.local.storage_types with
| Some (_, (LDK_Constant | LDK_Let)) -> true
| Some (_, LDK_Var) -> false
| None -> (
match IMap.find_opt s env.global.storage_types with
| Some (_, (GDK_Constant | GDK_Config | GDK_Let)) -> true
| Some (_, GDK_Var) -> false
| None -> undefined_identifier loc s)
let check_statically_evaluable (env : env) e () =
let e = reduce_expr env e in
let use_set = use_e ISet.empty e in
if ISet.for_all (storage_is_pure e env) use_set then ()
else fatal_from e (Error.UnpureExpression e)
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 (StaticInterpreter.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 has_bitvector_structure env t =
match (Types.get_structure env t).desc with T_Bits _ -> true | _ -> false
let expr_is_strict_positive e =
match e.desc with
| E_Literal (L_Int i) -> Z.sign i = 1
| E_Var _n -> false
| _ -> unsupported_expr e
let constraint_is_strict_positive = function
| Constraint_Exact e | Constraint_Range (e, _) -> expr_is_strict_positive e
let constraints_is_strict_positive =
List.for_all constraint_is_strict_positive
let expr_is_non_negative e =
match e.desc with
| E_Literal (L_Int i) -> Z.sign i != -1
| E_Var _n -> false
| _ -> unsupported_expr e
let constraint_is_non_negative = function
| Constraint_Exact e | Constraint_Range (e, _) -> expr_is_non_negative e
let constraints_is_non_negative = List.for_all constraint_is_non_negative
let constraint_binop env op cs1 cs2 =
let res = constraint_binop op cs1 cs2 |> reduce_constraints env in
let () =
if false then
Format.eprintf
"Reduction of binop %s@ on@ constraints@ %a@ and@ %a@ gave@ %a@."
(PP.binop_to_string op) PP.pp_int_constraints cs1
PP.pp_int_constraints cs2 PP.pp_ty
(T_Int res |> add_dummy_pos)
in
res
let type_of_array_length ~loc env = function
| ArrayLength_Enum (s, _) -> T_Named s |> add_pos_from loc
| ArrayLength_Expr e ->
let m = binop MINUS e !$1 |> reduce_expr env in
let c = Constraint_Range (!$0, m) in
T_Int (WellConstrained [ c ]) |> add_pos_from loc
let check_binop 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 with_loc = add_pos_from loc in
either
(fun () ->
match op with
| BAND | BOR | BEQ | IMPL ->
let+ () = check_type_satisfies' env t1 boolean in
let+ () = check_type_satisfies' env t2 boolean in
T_Bool |> with_loc
| AND | OR | EOR ->
let+ () = check_bits_equal_width' env t1 t2 in
let w = get_bitvector_width' env t1 in
T_Bits (w, []) |> with_loc
| (PLUS | MINUS) when has_bitvector_structure env t1 ->
let+ () =
either
(check_bits_equal_width' env t1 t2)
(check_type_satisfies' env t2 integer)
in
let w = get_bitvector_width' env t1 in
T_Bits (w, []) |> with_loc
| EQ_OP | NEQ ->
let t1_anon = Types.make_anonymous env t1
and t2_anon = Types.make_anonymous env t2 in
let+ () =
any
[
both
(check_type_satisfies' env t1_anon integer)
(check_type_satisfies' env t2_anon integer);
check_bits_equal_width' env t1_anon t2_anon;
both
(check_type_satisfies' env t1_anon boolean)
(check_type_satisfies' env t2_anon boolean);
both
(check_type_satisfies' env t1_anon real)
(check_type_satisfies' env t2_anon real);
both
(check_type_satisfies' env t1_anon string)
(check_type_satisfies' env t2_anon string);
(fun () ->
match (t1_anon.desc, t2_anon.desc) with
| T_Enum li1, T_Enum li2 ->
check_true' (list_equal String.equal li1 li2) ()
| _ -> assumption_failed ());
]
in
T_Bool |> with_loc
| LEQ | GEQ | GT | LT ->
let+ () =
either
(both
(check_type_satisfies' env t1 integer)
(check_type_satisfies' env t2 integer))
(both
(check_type_satisfies' env t1 real)
(check_type_satisfies' env t2 real))
in
T_Bool |> with_loc
| MUL | DIV | DIVRM | MOD | SHL | SHR | POW | PLUS | MINUS -> (
let struct1 = Types.get_well_constrained_structure env t1
and struct2 = Types.get_well_constrained_structure env t2 in
match (struct1.desc, struct2.desc) with
| T_Int UnConstrained, T_Int _ | T_Int _, T_Int UnConstrained ->
T_Int UnConstrained |> with_loc
| T_Int (UnderConstrained _), _ | _, T_Int (UnderConstrained _) ->
assert false
| T_Int (WellConstrained cs1), T_Int (WellConstrained cs2) ->
let+ () =
match op with
| DIV ->
check_true' (constraints_is_strict_positive cs2)
| DIVRM | MOD ->
check_true' (constraints_is_strict_positive cs2)
| SHL | SHR ->
check_true' (constraints_is_non_negative cs2)
| _ -> fun () -> ()
in
let cs =
best_effort UnConstrained (fun _ ->
constraint_binop env op cs1 cs2)
in
T_Int cs |> with_loc
| T_Real, T_Real -> (
match op with
| PLUS | MINUS | MUL -> T_Real |> with_loc
| _ -> assumption_failed ())
| T_Real, T_Int _ -> (
match op with
| POW -> T_Real |> with_loc
| _ -> assumption_failed ())
| _ -> assumption_failed ())
| RDIV ->
let+ () = check_type_satisfies' env t1 real in
T_Real |> with_loc)
(fun () -> fatal_from loc (Error.BadTypesForBinop (op, t1, t2)))
()
|: TypingRule.CheckBinop
let check_unop loc env op t1 =
match op with
| BNOT ->
let+ () = check_type_satisfies loc env t1 boolean in
T_Bool |> add_pos_from loc
| NEG -> (
let+ () =
either
(check_type_satisfies loc env t1 integer)
(check_type_satisfies loc env t1 real)
in
let struct1 = Types.get_well_constrained_structure env t1 in
match struct1.desc with
| T_Int UnConstrained -> T_Int UnConstrained |> add_pos_from loc
| T_Int (WellConstrained cs) ->
let neg e = E_Unop (NEG, e) |> add_pos_from 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))
|> add_pos_from loc
| T_Int (UnderConstrained _) ->
assert false
| _ -> t1)
| NOT ->
let+ () = check_structure_bits loc env t1 in
t1 |: TypingRule.CheckUnop
let var_in_env ?(local = true) env x =
(local && IMap.mem x env.local.storage_types)
|| IMap.mem x env.global.storage_types
|| IMap.mem x env.global.subprograms
|| IMap.mem x env.global.declared_types
let check_var_not_in_env ?(local = true) loc env x () =
if var_in_env ~local env x then
fatal_from loc (Error.AlreadyDeclaredIdentifier x)
else ()
let check_var_not_in_genv loc = check_var_not_in_env ~local:false loc
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 li -> Some (x, List.length li)
| _ -> None)
| None -> None)
| _ -> None
let check_diet_in_width loc slices width diet () =
let x = Diet.Int.min_elt diet |> Diet.Int.Interval.x
and y = Diet.Int.max_elt diet |> Diet.Int.Interval.y in
if 0 <= x && y < width then ()
else fatal_from loc (BadSlices (Error.Static, slices, width))
let check_slices_in_width loc env width slices () =
let diet = disjoint_slices_to_diet loc env slices in
check_diet_in_width loc slices width diet ()
let rec annotate_bitfield ~loc env width bitfield : bitfield =
match bitfield with
| BitField_Simple (name, slices) ->
let slices = annotate_slices env slices in
let+ () = check_slices_in_width loc env width slices in
BitField_Simple (name, slices)
| BitField_Nested (name, slices, bitfields') ->
let slices = annotate_slices env slices in
let diet = disjoint_slices_to_diet loc env slices in
let+ () = check_diet_in_width loc slices width diet in
let width' = Diet.Int.cardinal diet |> expr_of_int in
let bitfields'' = annotate_bitfields ~loc env width' bitfields' in
BitField_Nested (name, slices, bitfields'')
| BitField_Type (name, slices, ty) ->
let ty' = annotate_type ~loc env ty in
let slices = annotate_slices env slices in
let diet = disjoint_slices_to_diet loc env slices in
let+ () = check_diet_in_width loc slices width diet in
let width' = Diet.Int.cardinal diet |> expr_of_int in
let+ () =
t_bits_bitwidth width' |> add_dummy_pos
|> check_bits_equal_width loc env ty
in
BitField_Type (name, slices, ty')
and annotate_bitfields ~loc env e_width bitfields =
let+ () =
match get_first_duplicate bitfield_get_name bitfields with
| None -> ok
| Some x -> fun () -> fatal_from loc (Error.AlreadyDeclaredIdentifier x)
in
let width =
let v = reduce_constants env e_width in
match v with L_Int i -> Z.to_int i | _ -> assert false
in
List.map (annotate_bitfield ~loc env width) bitfields
and annotate_type ?(decl = false) ~(loc : 'a annotated) env ty : ty =
let () =
if false then
Format.eprintf "Annotating@ %a@ in env:@ %a@." PP.pp_ty ty
StaticEnv.pp_env env
in
let here t = add_pos_from ty t in
best_effort ty @@ fun _ ->
match ty.desc with
| T_String -> ty
| T_Real -> ty
| T_Bool -> ty
| T_Named x ->
let+ () =
if IMap.mem x env.global.declared_types then ok
else fun () -> undefined_identifier loc x
in
ty
| T_Int constraints -> (
match constraints with
| WellConstrained constraints ->
let constraints =
List.map (annotate_constraint ~loc env) constraints
in
T_Int (WellConstrained constraints) |> here
| UnderConstrained _ | UnConstrained -> ty)
| T_Bits (e_width, bitfields) ->
let e_width' = annotate_static_constrained_integer ~loc env e_width in
let bitfields' =
if bitfields = [] then bitfields
else annotate_bitfields ~loc env e_width' bitfields
in
T_Bits (e_width', bitfields') |> here
| T_Tuple tys ->
let tys' = List.map (annotate_type ~loc env) tys in
T_Tuple tys' |> here
| T_Array (index, t) ->
let t' = annotate_type ~loc env t
and index' =
match index with
| ArrayLength_Expr e -> (
match get_variable_enum' env e with
| Some (s, i) -> ArrayLength_Enum (s, i)
| None ->
let e' = annotate_static_integer ~loc env e in
ArrayLength_Expr e')
| ArrayLength_Enum (s, i) -> (
let ty = T_Named s |> here in
match (Types.make_anonymous env ty).desc with
| T_Enum li when List.length li = i -> index
| _ -> conflict loc [ T_Enum [] ] ty)
in
T_Array (index', t') |> here
| (T_Record fields | T_Exception fields) when decl -> (
let+ () =
match get_first_duplicate fst fields with
| None -> ok
| Some x ->
fun () -> fatal_from loc (Error.AlreadyDeclaredIdentifier x)
in
let fields' =
List.map (fun (x, ty) -> (x, annotate_type ~loc env ty)) fields
in
match ty.desc with
| T_Record _ -> T_Record fields' |> here
| T_Exception _ -> T_Exception fields' |> here
| _ -> assert false
)
| T_Enum li when decl ->
let+ () =
match get_first_duplicate Fun.id 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 ty env s ()) li
in
ty
| 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.")
and annotate_static_integer ~(loc : 'a annotated) env e =
let t, e' = annotate_expr env e in
let+ () = check_structure_integer loc env t in
let+ () = check_statically_evaluable env e' in
reduce_expr env e'
and annotate_static_constrained_integer ~(loc : 'a annotated) env e =
let t, e' = annotate_expr env e in
let+ () = check_constrained_integer ~loc env t in
let+ () = check_statically_evaluable env e' in
reduce_expr env e'
and annotate_constraint ~loc env = function
| Constraint_Exact e ->
let e' = annotate_static_constrained_integer ~loc env e in
Constraint_Exact e'
| Constraint_Range (e1, e2) ->
let e1' = annotate_static_constrained_integer ~loc env e1
and e2' = annotate_static_constrained_integer ~loc env e2 in
Constraint_Range (e1', e2')
and annotate_slices env =
let rec tr_one s =
let () =
if false then
Format.eprintf "Annotating slice %a@." PP.pp_slice_list [ s ]
in
match s with
| Slice_Single i ->
tr_one (Slice_Length (i, !$1)) |: TypingRule.SliceSingle
| Slice_Length (offset, length) ->
let t_offset, offset' = annotate_expr env offset
and length' =
annotate_static_constrained_integer ~loc:(to_pos length) env length
in
let+ () = check_structure_integer offset' env t_offset in
Slice_Length (offset', length') |: TypingRule.SliceLength
| Slice_Range (j, i) ->
let pre_length = binop MINUS j i |> binop PLUS !$1 in
tr_one (Slice_Length (i, pre_length)) |: TypingRule.SliceRange
| Slice_Star (factor, pre_length) ->
let pre_offset = binop MUL factor pre_length in
tr_one (Slice_Length (pre_offset, pre_length)) |: TypingRule.SliceStar
in
List.map tr_one
and annotate_pattern loc env t = function
| Pattern_All as p -> p |: TypingRule.PAll
| Pattern_Any li ->
let new_li = List.map (annotate_pattern loc env t) li in
Pattern_Any new_li |: TypingRule.PAny
| Pattern_Not q ->
let new_q = annotate_pattern loc env t q in
Pattern_Not new_q |: TypingRule.PNot
| Pattern_Single e ->
let t_e, e = annotate_expr env e 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_Bool, T_Bool | T_Real, T_Real | T_Int _, T_Int _ -> ()
| 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.BadTypesForBinop (EQ_OP, t, t_e))
in
Pattern_Single e |: TypingRule.PSingle
| Pattern_Geq e ->
let t_e, e' = annotate_expr env e in
let+ () = check_statically_evaluable env e' 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.BadTypesForBinop (GEQ, t, t_e))
in
Pattern_Geq e' |: TypingRule.PGeq
| Pattern_Leq e ->
let t_e, e' = annotate_expr env e in
let+ () = check_statically_evaluable env e' in
let+ () =
both
(check_structure_integer loc env t)
(check_structure_integer loc env t_e)
in
Pattern_Leq e' |: TypingRule.PLeq
| Pattern_Range (e1, e2) ->
let t_e1, e1' = annotate_expr env e1
and t_e2, e2' = annotate_expr env e2 in
let+ () =
fun () ->
let t_struct = Types.get_structure env t
and t_e1_struct = Types.get_structure env t_e1
and t_e2_struct = Types.get_structure env t_e2 in
match (t_struct.desc, t_e1_struct.desc, t_e2_struct.desc) with
| T_Real, T_Real, T_Real | T_Int _, T_Int _, T_Int _ -> ()
| _, T_Int _, T_Int _ | _, T_Real, T_Real ->
fatal_from loc (Error.BadTypesForBinop (GEQ, t, t_e1))
| _ -> fatal_from loc (Error.BadTypesForBinop (GEQ, t_e1, t_e2))
in
Pattern_Range (e1', e2') |: TypingRule.PRange
| Pattern_Mask m as p ->
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 |: 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 ->
Error.fatal_from loc
(Error.BadArity
("pattern matching on tuples", List.length li, List.length ts))
|: TypingRule.PTupleBadArity
| T_Tuple ts ->
let new_li = List.map2 (annotate_pattern loc env) ts li in
Pattern_Tuple new_li |: TypingRule.PTuple
| _ -> conflict loc [ T_Tuple [] ] t |: TypingRule.PTupleConflict
)
and annotate_call loc env name args eqs call_type =
let () =
if false then
Format.eprintf "Annotating call to %S at %a.@." name PP.pp_pos loc
in
let caller_arg_typed = List.map (annotate_expr env) args in
let caller_arg_types, args1 = List.split caller_arg_typed in
let , name1, callee_arg_types, ret_ty, callee_params =
Fn.try_find_name loc env name caller_arg_types
in
let () =
if false then
match extra_nargs 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))
extra_nargs name
in
let eqs1 = List.rev_append eqs extra_nargs in
let () =
if List.compare_lengths callee_arg_types args1 != 0 then
fatal_from loc
@@ Error.BadArity (name, List.length callee_arg_types, List.length args1)
|: TypingRule.FCallBadArity
in
let eqs2 =
let folder acc (_x, ty) (t_e, _e) =
match ty.desc with
| T_Bits ({ desc = E_Var x; _ }, _) -> (
match (Types.get_structure env t_e).desc with
| T_Bits (e, _) -> (x, e) :: acc
| _ -> acc)
| _ -> acc
in
List.fold_left2 folder eqs1 callee_arg_types caller_arg_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))
eqs2
in
let () =
List.iter2
(fun (_, callee_arg) caller_arg ->
let callee_arg = rename_ty_eqs eqs2 callee_arg in
let () =
if false then
Format.eprintf "Checking calling arg from %a to %a@." PP.pp_ty
caller_arg PP.pp_ty callee_arg
in
let+ () = check_type_satisfies loc env caller_arg callee_arg in
())
callee_arg_types 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 eqs3 =
List.map
(fun (param_name, e) ->
let e' = annotate_static_constrained_integer ~loc env e in
(param_name, e'))
eqs2
in
let eqs4 =
List.fold_left2
(fun eqs (callee_x, _) (caller_ty, caller_e) ->
if
List.exists
(fun (p_name, _ty) -> String.equal callee_x p_name)
callee_params
then
let+ () = check_constrained_integer ~loc env caller_ty in
(callee_x, caller_e) :: eqs
else eqs)
eqs3 callee_arg_types caller_arg_typed
in
let ret_ty1 =
match (call_type, ret_ty) with
| (ST_Function | ST_Getter), Some ty ->
Some (rename_ty_eqs eqs4 ty) |: TypingRule.FCallGetter
| (ST_Setter | ST_Procedure), None -> None |: TypingRule.FCallSetter
| _ ->
fatal_from loc @@ Error.MismatchedReturnValue name
|: TypingRule.FCallMismatch
in
let () = if false then Format.eprintf "Annotated call to %S.@." name1 in
(name1, args1, eqs4, ret_ty1)
and annotate_expr env (e : expr) : ty * expr =
let () = if false then Format.eprintf "@[Annotating %a@]@." PP.pp_expr e in
let here x = add_pos_from e x and loc = to_pos e in
match e.desc with
| E_Literal v -> (annotate_literal v |> here, e) |: TypingRule.ELit
| E_CTC (e', ty) ->
let t, e'' = annotate_expr env e' in
let ty' = annotate_type ~loc env ty in
best_effort
(ty', E_CTC (e'', ty') |> here)
(fun res ->
if Types.structural_subtype_satisfies env t ty' then
if Types.domain_subtype_satisfies env t ty' then
res
else res
else conflict e [ ty'.desc ] t)
|: TypingRule.CTC
| E_Var x -> (
let () = if false then Format.eprintf "Looking at %S.@." x in
if should_reduce_to_call env x then
let () =
if false then
Format.eprintf "@[Reducing getter %S@ at %a@]@." x PP.pp_pos e
in
let name, args, eqs, ty =
annotate_call (to_pos e) env x [] [] ST_Getter
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call (name, args, eqs) |> here)
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 ->
let v = IMap.find x env.local.constant_values in
let e = E_Literal v |> here in
(ty, e) |: TypingRule.ELocalVarConstant
| ty, _ -> (ty, e) |: TypingRule.ELocalVar
with Not_found -> (
try
match IMap.find x env.global.storage_types with
| ty, GDK_Constant -> (
match IMap.find_opt x env.global.constant_values with
| Some v ->
(ty, E_Literal v |> here)
|: TypingRule.EGlobalVarConstantVal
| None -> (ty, e) |: TypingRule.EGlobalVarConstantNoVal)
| ty, _ -> (ty, e) |: TypingRule.EGlobalVar
with Not_found ->
let () =
if false then
Format.eprintf "@[Cannot find %s in env@ %a.@]@." x pp_env env
in
undefined_identifier e x |: TypingRule.EUndefIdent))
| E_Binop (op, e1, e2) ->
let t1, e1' = annotate_expr env e1 in
let t2, e2' = annotate_expr env e2 in
let t = check_binop e env op t1 t2 in
(t, E_Binop (op, e1', e2') |> here) |: TypingRule.Binop
| E_Unop (op, e') ->
let t'', e'' = annotate_expr env e' in
let t = check_unop e env op t'' in
(t, E_Unop (op, e'') |> here) |: TypingRule.Unop
| E_Call (name, args, eqs) ->
let name', args', eqs', ty_opt =
annotate_call (to_pos e) env name args eqs ST_Function
in
let t = match ty_opt with Some ty -> ty | None -> assert false in
(t, E_Call (name', args', eqs') |> here) |: TypingRule.ECall
| E_Cond (e_cond, e_true, e_false) ->
let t_cond, e'_cond = annotate_expr env e_cond in
let+ () = check_structure_boolean e env t_cond in
let t_true, e'_true = annotate_expr env e_true
and t_false, e'_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 e (Error.UnreconciliableTypes (t_true, t_false))
| Some t -> t)
in
(t, E_Cond (e'_cond, e'_true, e'_false) |> here) |: TypingRule.ECond
| E_Tuple li ->
let ts, es = List.map (annotate_expr env) li |> List.split in
(T_Tuple ts |> here, E_Tuple es |> here) |: TypingRule.ETuple
| E_Concat [] ->
(T_Bits (expr_of_int 0, []) |> here, e) |: TypingRule.EConcatEmpty
| E_Concat (_ :: _ as li) ->
let ts, es = List.map (annotate_expr env) li |> List.split in
let w =
let widths = List.map (get_bitvector_width e env) ts in
let wh = List.hd widths and wts = List.tl widths in
List.fold_left (width_plus env) wh wts
in
(T_Bits (w, []) |> here, E_Concat es |> here) |: TypingRule.EConcat
| E_Record (ty, fields) ->
let+ () =
check_true (Types.is_named ty) (fun () ->
failwith "Typing error: should be a named type")
in
let field_types =
match (Types.get_structure env ty).desc with
| T_Exception fields | T_Record fields -> fields
| _ ->
conflict e [ T_Record [] ] ty
|: TypingRule.EStructuredNotStructured
in
let fields' =
best_effort fields (fun _ ->
let () =
if
List.for_all
(fun (name, _) -> List.mem_assoc name fields)
field_types
then ()
else
fatal_from e (Error.MissingField (List.map fst fields, ty))
|: TypingRule.EStructuredMissingField
in
List.map
(fun (name, e') ->
let t', e'' = annotate_expr env e' in
let t_spec' =
match List.assoc_opt name field_types with
| None -> fatal_from e (Error.BadField (name, ty))
| Some t_spec' -> t_spec'
in
let+ () = check_type_satisfies e env t' t_spec' in
(name, e''))
fields)
in
(ty, E_Record (ty, fields') |> here) |: TypingRule.ERecord
| E_Unknown ty ->
let ty1 = annotate_type ~loc env ty in
let ty2 = Types.get_structure env ty1 in
(ty1, E_Unknown ty2 |> here) |: TypingRule.EUnknown
| E_Slice (e', slices) -> (
let reduced =
match e'.desc with
| E_Var x ->
should_slices_reduce_to_call env x slices |> Option.map (pair x)
| _ -> None
in
match reduced with
| Some (name, args) ->
let name, args, eqs, ty =
annotate_call (to_pos e) env name args [] ST_Getter
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call (name, args, eqs) |> here)
| None -> (
let t_e', e'' = annotate_expr env e' in
let struct_t_e' = Types.get_structure env t_e' in
match struct_t_e'.desc with
| T_Int _ | T_Bits _ ->
let w = slices_width env slices in
let slices' = best_effort slices (annotate_slices env) in
(T_Bits (w, []) |> here, E_Slice (e'', slices') |> here)
|: TypingRule.ESlice
| T_Array (size, ty') -> (
match slices with
| [ Slice_Single e_index ] ->
let t_index', e_index' = annotate_expr env e_index in
let wanted_t_index = type_of_array_length ~loc:e env size in
let+ () =
check_type_satisfies e env t_index' wanted_t_index
in
(ty', E_GetArray (e'', e_index') |> here)
| _ -> conflict e [ integer'; default_t_bits ] t_e')
| _ ->
conflict e [ integer'; default_t_bits ] t_e'
|: TypingRule.EGetArray))
| E_GetField (e1, field_name) -> (
let t_e1, e2 = annotate_expr env e1 in
let t_e2 = Types.make_anonymous env t_e1 in
let reduced =
match e1.desc with
| E_Var x -> should_field_reduce_to_call env x t_e2 field_name
| _ -> None
in
match reduced with
| Some (name, args) ->
let name, args, eqs, ty =
annotate_call (to_pos e) env name args [] ST_Getter
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call (name, args, eqs) |> here)
| None -> (
match t_e2.desc with
| T_Exception fields | T_Record fields -> (
match List.assoc_opt field_name fields with
| None ->
fatal_from e (Error.BadField (field_name, t_e2))
|: TypingRule.EGetBadRecordField
| Some t ->
(t, E_GetField (e2, field_name) |> here)
|: TypingRule.EGetRecordField
)
| T_Bits (_, bitfields) -> (
match find_bitfield_opt field_name bitfields with
| None ->
fatal_from e (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 t_e3, e3 =
E_Slice (e2, slices) |> here |> annotate_expr env
in
let t_e4 =
match t_e3.desc with
| T_Bits (width, _bitfields) ->
T_Bits (width, bitfields') |> add_pos_from t_e2
| _ -> assert false
in
(t_e4, e3) |: TypingRule.EGetBitFieldNested
| Some (BitField_Type (_field, slices, t)) ->
let t_e3, e3 =
E_Slice (e2, slices) |> here |> annotate_expr env
in
let+ () = check_type_satisfies e3 env t_e3 t in
(t, e3) |: TypingRule.EGetBitFieldTyped)
| _ ->
conflict e [ default_t_bits; T_Record []; T_Exception [] ] t_e1
|: TypingRule.EGetBadField)
)
| E_GetFields (e_1, fields) -> (
let t_e', e_2 = annotate_expr env e_1 in
let t_e' = Types.make_anonymous env t_e' in
let reduced =
match e_1.desc with
| E_Var x -> should_fields_reduce_to_call env x t_e' fields
| _ -> None
in
match reduced with
| Some (name, args) ->
let name, args, eqs, ty =
annotate_call (to_pos e) env name args [] ST_Getter
in
let ty = match ty with Some ty -> ty | None -> assert false in
(ty, E_Call (name, args, eqs) |> here)
| None ->
let bitfields =
match t_e'.desc with
| T_Bits (_, bitfields) -> bitfields
| _ -> conflict e [ default_t_bits ] t_e'
in
let one_field field =
match find_bitfields_slices_opt field bitfields with
| None -> fatal_from e (Error.BadField (field, t_e'))
| Some slices -> slices
in
E_Slice (e_2, list_concat_map one_field fields)
|> here |> annotate_expr env |: TypingRule.EGetBitFields)
| E_Pattern (e', patterns) ->
let t_e', e'' = annotate_expr env e' in
let patterns' = best_effort patterns (annotate_pattern e env t_e') in
(T_Bool |> here, E_Pattern (e'', patterns') |> here)
|: TypingRule.EPattern
| E_GetArray _ -> assert false |: TypingRule.EGetArray
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 here x = add_pos_from le x in
match le.desc with
| LE_Discard -> le |: TypingRule.LEDiscard
| LE_Var x ->
let+ () =
fun () ->
let ty =
match IMap.find_opt x env.local.storage_types with
| Some (ty, LDK_Var) -> ty |: TypingRule.LELocalVar
| Some _ -> fatal_from le @@ Error.AssignToImmutable x
| None -> (
match IMap.find_opt x env.global.storage_types with
| Some (ty, GDK_Var) -> ty |: TypingRule.LEGlobalVar
| Some _ -> fatal_from le @@ Error.AssignToImmutable x
| None -> undefined_identifier le x)
in
check_type_satisfies le env t_e ty ()
in
le
| LE_Destructuring les ->
(match t_e.desc with
| T_Tuple sub_tys ->
if List.compare_lengths sub_tys les != 0 then
Error.fatal_from le
(Error.BadArity
("LEDestructuring", List.length sub_tys, List.length les))
else
let les' = List.map2 (annotate_lexpr env) les sub_tys in
LE_Destructuring les' |> here
| _ -> conflict le [ T_Tuple [] ] t_e)
|: TypingRule.LEDestructuring
| LE_Slice (le1, slices) -> (
let t_le1, _ = expr_of_lexpr le1 |> annotate_expr env in
let struct_t_le1 = Types.get_structure env t_le1 in
match struct_t_le1.desc with
| T_Bits _ ->
let le2 = annotate_lexpr env le1 t_le1 in
let+ () =
fun () ->
let width = slices_width env slices |> reduce_expr env in
let t = T_Bits (width, []) |> here in
check_type_satisfies le env t_e t ()
in
let slices2 = best_effort slices (annotate_slices env) in
LE_Slice (le2, slices2) |> here |: TypingRule.LESlice
| T_Array (size, t) -> (
let le2 = annotate_lexpr env le1 t_le1 in
let+ () = check_type_satisfies le2 env t_e t in
match slices with
| [ Slice_Single e_index ] ->
let t_index', e_index' = annotate_expr env e_index in
let wanted_t_index = type_of_array_length ~loc:le env size in
let+ () =
check_type_satisfies le2 env t_index' wanted_t_index
in
LE_SetArray (le2, e_index') |> here |: TypingRule.LESetArray
| _ -> unsupported_expr (expr_of_lexpr le1))
| _ -> conflict le1 [ default_t_bits ] t_le1)
| LE_SetField (le1, field) ->
(let t_le1, _ = expr_of_lexpr le1 |> annotate_expr env in
let le2 = annotate_lexpr env le1 t_le1 in
let t_le1_struct = Types.get_structure env t_le1 in
match t_le1_struct.desc with
| T_Exception fields | T_Record fields ->
let t =
match List.assoc_opt field fields with
| None ->
fatal_from le (Error.BadField (field, t_le1))
|: TypingRule.LESetBadStructuredField
| Some t -> t
in
let+ () = check_type_satisfies le env t_e t in
LE_SetField (le2, field) |> here |: 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 le1 (Error.BadField (field, t_le1_struct))
|: TypingRule.LESetBadBitField
| Some (BitField_Simple (_field, slices)) ->
(bits slices [], slices) |: TypingRule.LESetBitField
| Some (BitField_Nested (_field, slices, bitfields')) ->
(bits slices bitfields', slices)
|: TypingRule.LESetBitFieldNested
| Some (BitField_Type (_field, slices, t)) ->
let t' = bits slices [] in
let+ () = check_type_satisfies le env t' t in
(t, slices) |: TypingRule.LESetBitFieldTyped
in
let+ () = check_type_satisfies le1 env t_e t in
let le2 = LE_Slice (le1, slices) |> here in
annotate_lexpr env le2 t_e
| _ -> conflict le1 [ default_t_bits; T_Record []; T_Exception [] ] t_e)
|: TypingRule.LESetBadField
| LE_SetFields (le', fields) ->
let t_le', _ = expr_of_lexpr le' |> annotate_expr env in
let le' = annotate_lexpr env le' t_le' in
let t_le'_struct = Types.get_structure env t_le' in
let bitfields =
match t_le'_struct.desc with
| T_Bits (_, bitfields) -> bitfields
| _ -> conflict le [ default_t_bits ] t_le'
in
let one_field field =
match find_bitfields_slices_opt field bitfields with
| None -> fatal_from le (Error.BadField (field, t_le'_struct))
| Some slices -> slices
in
let new_le = LE_Slice (le', list_concat_map one_field fields) |> here in
annotate_lexpr env new_le t_e |: TypingRule.LESetFields
| LE_SetArray _ -> assert false
| LE_Concat (les, _) ->
let e_eq = expr_of_lexpr le in
let t_e_eq, _e_eq = annotate_expr env e_eq in
let+ () = check_bits_equal_width' env t_e_eq t_e in
let bv_length t =
let e_width = get_bitvector_width le env t in
match reduce_constants env e_width with
| L_Int z -> Z.to_int z
| _ -> fatal_from le @@ MismatchType ("bitvector width", [ integer' ])
in
let annotate_one (les, widths, sum) le =
let e = expr_of_lexpr le in
let t_e, _e = annotate_expr env e in
let width = bv_length t_e in
let t_e' = T_Bits (expr_of_int width, []) |> add_pos_from le in
let le = annotate_lexpr env le t_e' in
(le :: les, width :: widths, sum + width)
in
let rev_les, rev_widths, _real_width =
List.fold_left annotate_one ([], [], 0) les
in
let les = List.rev rev_les and widths = List.rev rev_widths in
LE_Concat (les, Some widths) |> add_pos_from le |: TypingRule.LEConcat
let can_be_initialized_with env s t =
let s_struct = Types.get_structure env s in
match s_struct.desc with
| T_Int (UnderConstrained _) -> 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 rec annotate_local_decl_item loc (env : env) ty ldk ldi =
match ldi with
| LDI_Discard -> (env, ldi) |: TypingRule.LDDiscard
| LDI_Typed (ldi', t) ->
let t' = annotate_type ~loc env t in
let+ () = check_can_be_initialized_with loc env t' ty in
let new_env, new_ldi' = annotate_local_decl_item loc env t' ldk ldi' in
(new_env, LDI_Typed (new_ldi', t')) |: TypingRule.LDTyped
| LDI_Var x ->
let+ () = check_var_not_in_env loc env x in
let new_env = add_local x ty ldk env in
(new_env, LDI_Var x) |: TypingRule.LDVar
| LDI_Tuple ldis ->
let tys =
match (Types.get_structure env ty).desc with
| T_Tuple tys when List.compare_lengths tys ldis = 0 -> tys
| T_Tuple tys ->
fatal_from loc
(Error.BadArity
("tuple initialization", List.length tys, List.length ldis))
| _ -> conflict loc [ T_Tuple [] ] ty
in
let new_env, new_ldis =
List.fold_right2
(fun ty' ldi' (env', les) ->
let env', le = annotate_local_decl_item loc env' ty' ldk ldi' in
(env', le :: les))
tys ldis (env, [])
in
(new_env, LDI_Tuple new_ldis) |: TypingRule.LDTuple
let annotate_local_decl_item_uninit loc (env : env) ldi =
match ldi with
| LDI_Discard -> (env, LDI_Discard)
| LDI_Var _ ->
fatal_from loc (Error.BadLDI ldi) |: TypingRule.LDUninitialisedVar
| LDI_Tuple _ldis ->
fatal_from loc (Error.BadLDI ldi) |: TypingRule.LDUninitialisedTuple
| LDI_Typed (ldi', t) ->
let t' = annotate_type ~loc env t in
let new_env, new_ldi' =
annotate_local_decl_item loc env t' LDK_Var ldi'
in
(new_env, LDI_Typed (new_ldi', t')) |: TypingRule.LDUninitialisedTyped
let declare_local_constant loc env t_e v ldi =
let rec add_constants env ldi =
match ldi with
| LDI_Discard -> env
| LDI_Var x -> add_local_constant x v env
| LDI_Tuple ldis -> List.fold_left add_constants env ldis
| LDI_Typed (ldi, _ty) -> add_constants env ldi
in
let env, ldi = annotate_local_decl_item loc env t_e LDK_Constant ldi in
(add_constants env ldi, ldi)
let rec annotate_stmt env s =
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 s x and loc = to_pos s in
match s.desc with
| S_Pass -> (s, env) |: TypingRule.SPass
| S_Seq (s1, s2) ->
let new_s1, env1 = try_annotate_stmt env s1 in
let new_s2, env2 = try_annotate_stmt env1 s2 in
(S_Seq (new_s1, new_s2) |> here, env2) |: TypingRule.SSeq
| S_Assign (le, re, ver) ->
(let () =
if false then
Format.eprintf "@[<3>Annotating assignment@ @[%a@]@]@." PP.pp_stmt
s
in
let t_e, e1 = annotate_expr env re in
let () =
if false then Format.eprintf "@[Type: @[%a@]@]@." PP.pp_ty t_e
in
let reduced = setter_should_reduce_to_call_s env le e1 in
match reduced with
| Some s -> (s, env)
| None ->
let env1 =
match ver with
| V1 -> env
| V0 -> (
match ASTUtils.lid_of_lexpr le with
| None -> env
| Some ldi ->
let rec undefined = function
| LDI_Discard -> true
| LDI_Var x -> StaticEnv.is_undefined x env
| LDI_Tuple ldis -> List.for_all undefined ldis
| LDI_Typed (ldi', _) -> undefined ldi'
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, _ldi =
annotate_local_decl_item loc env t_e ldk ldi
in
env2
else env)
in
let le1 = annotate_lexpr env1 le t_e in
(S_Assign (le1, e1, ver) |> here, env1))
|: TypingRule.SAssign
| S_Call (name, args, eqs) ->
let new_name, new_args, new_eqs, ty =
annotate_call loc env name args eqs ST_Procedure
in
let () = assert (ty = None) in
(S_Call (new_name, new_args, new_eqs) |> here, env) |: 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.SReturnOne
| None, None -> (S_Return None |> here, env) |: TypingRule.SReturnNone
| Some t, Some e ->
let t_e', e' = 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 s env t_e' t in
(S_Return (Some e') |> here, env))
|: TypingRule.SReturnSome
| S_Cond (e, s1, s2) ->
let t_cond, e_cond = annotate_expr env e in
let+ () = check_type_satisfies e_cond env t_cond boolean in
let s1' = try_annotate_block env s1 in
let s2' = try_annotate_block env s2 in
(S_Cond (e_cond, s1', s2') |> here, env) |: TypingRule.SCond
| S_Case (e, cases) ->
let t_e, e1 = annotate_expr env e in
let annotate_case (acc, env) case =
let p, s = case.desc in
let p1 = annotate_pattern e1 env t_e p in
let s1 = try_annotate_block env s in
(add_pos_from_st case (p1, s1) :: acc, env)
in
let cases1, env1 = List.fold_left annotate_case ([], env) cases in
(S_Case (e1, List.rev cases1) |> here, env1) |: TypingRule.SCase
| S_Assert e ->
let t_e', e' = annotate_expr env e in
let+ () = check_type_satisfies s env t_e' boolean in
(S_Assert e' |> here, env) |: TypingRule.SAssert
| S_While (e1, s1) ->
let t, e2 = annotate_expr env e1 in
let+ () = check_type_satisfies e2 env t boolean in
let s2 = try_annotate_block env s1 in
(S_While (e2, s2) |> here, env) |: TypingRule.SWhile
| S_Repeat (s1, e1) ->
let s2 = try_annotate_block env s1 in
let t, e2 = annotate_expr env e1 in
let+ () = check_type_satisfies e2 env t boolean in
(S_Repeat (s2, e2) |> here, env) |: TypingRule.SRepeat
| S_For (id, e1, dir, e2, s') ->
let t1, e1' = annotate_expr env e1 and t2, e2' = annotate_expr env e2 in
let struct1 = Types.get_well_constrained_structure env t1
and struct2 = Types.get_well_constrained_structure env t2 in
let cs =
match (struct1.desc, struct2.desc) with
| T_Int UnConstrained, T_Int _ | T_Int _, T_Int UnConstrained ->
UnConstrained
| T_Int (WellConstrained cs1), T_Int (WellConstrained cs2) -> (
let bot_cs, top_cs =
match dir with Up -> (cs1, cs2) | Down -> (cs2, cs1)
in
try
let bot = min_constraints env bot_cs
and top = max_constraints env top_cs in
if bot <= top then
WellConstrained
[ Constraint_Range (expr_of_z bot, expr_of_z top) ]
else WellConstrained cs1
with ConstraintMinMaxTop -> (
match (bot_cs, top_cs) with
| [ Constraint_Exact e_bot ], [ Constraint_Exact e_top ] ->
WellConstrained [ Constraint_Range (e_bot, e_top) ]
| _ ->
UnConstrained))
| T_Int (UnderConstrained _), T_Int _
| T_Int _, T_Int (UnderConstrained _) ->
assert false
| T_Int _, _ -> conflict s [ integer' ] t2
| _, _ -> conflict s [ integer' ] t1
in
let ty = T_Int cs |> here in
let s'' =
let+ () = check_var_not_in_env s' env id in
let env' = add_local id ty LDK_Let env in
try_annotate_block env' s'
in
(S_For (id, e1', dir, e2', s'') |> here, env) |: TypingRule.SFor
| S_Decl (ldk, ldi, e_opt) -> (
match (ldk, e_opt) with
| _, Some e ->
let t_e, e' = annotate_expr env e in
let env', ldi' =
if ldk = LDK_Constant then
let v = reduce_constants env e in
declare_local_constant loc env t_e v ldi
else annotate_local_decl_item loc env t_e ldk ldi
in
(S_Decl (ldk, ldi', Some e') |> here, env') |: TypingRule.SDeclSome
| LDK_Var, None ->
let env', ldi' = annotate_local_decl_item_uninit loc env ldi in
(S_Decl (LDK_Var, ldi', None) |> here, env') |: TypingRule.SDeclNone
| (LDK_Constant | LDK_Let), None ->
fatal_from s UnrespectedParserInvariant)
| S_Throw (Some (e, _)) ->
let t_e, e' = annotate_expr env e in
let+ () = check_structure_exception s env t_e in
(S_Throw (Some (e', Some t_e)) |> here, env) |: TypingRule.SThrowSome
| S_Throw None ->
(s, env) |: TypingRule.SThrowNone
| S_Try (s', catchers, otherwise) ->
let s'' = try_annotate_block env s' in
let otherwise' = Option.map (try_annotate_block env) otherwise in
let catchers' = List.map (annotate_catcher loc env) catchers in
(S_Try (s'', catchers', otherwise') |> here, env) |: TypingRule.STry
| S_Print { args; debug } ->
let args' = List.map (fun e -> annotate_expr env e |> snd) args in
(S_Print { args = args'; debug } |> here, env) |: TypingRule.SDebug
and annotate_catcher loc env (name_opt, ty, stmt) =
let ty' = annotate_type ~loc env ty in
let+ () = check_structure_exception ty' env ty' in
let env' =
match name_opt with
| None -> env |: TypingRule.CatcherNone
| Some name ->
let+ () = check_var_not_in_env stmt env name in
add_local name ty LDK_Let env |: TypingRule.CatcherSome
in
let new_stmt = try_annotate_block env' stmt in
(name_opt, ty, new_stmt)
and try_annotate_block env s =
best_effort s (fun _ -> annotate_stmt env s |> fst) |: TypingRule.Block
and try_annotate_stmt env s =
best_effort (s, env) (fun _ -> annotate_stmt env s)
and set_fields_should_reduce_to_call env le x fields e =
if not (should_reduce_to_call env x) then None
else
let ( let* ) = Option.bind in
let _, _, _, ty_opt, _ =
try Fn.try_find_name le env x []
with Error.ASLException _ -> assert false
in
let* ty = ty_opt in
let ty = Types.make_anonymous env ty in
let* name, args = should_fields_reduce_to_call env x ty fields in
let name, args, eqs, ret_ty =
annotate_call (to_pos le) env name (e :: args) [] ST_Setter
in
let () = assert (ret_ty = None) in
Some (S_Call (name, args, eqs) |> add_pos_from le)
and setter_should_reduce_to_call_s env le e : stmt option =
let () =
if false then
Format.eprintf "@[<2>setter_..._s@ @[%a@]@ @[%a@]@]@." PP.pp_lexpr le
PP.pp_expr e
in
let here d = add_pos_from le d in
let s_then = s_then in
let to_expr = expr_of_lexpr in
let with_temp old_le sub_le =
let x = fresh_var "setter_setfield" in
let le_x = LE_Var x |> here in
match setter_should_reduce_to_call_s env sub_le (E_Var x |> here) with
| None -> None
| Some s ->
let s1, _env1 =
S_Assign (le_x, to_expr sub_le, V1) |> here |> annotate_stmt env
and s2, _env2 =
S_Assign (old_le le_x, e, V1) |> here |> annotate_stmt env
in
Some (s_then (s_then s1 s2) s)
in
match le.desc with
| LE_Discard -> None
| LE_SetField ({ desc = LE_Var x; _ }, field) ->
set_fields_should_reduce_to_call env le x [ field ] e
| LE_SetField (sub_le, field) ->
let old_le le' = LE_SetField (le', field) |> here in
with_temp old_le sub_le
| LE_SetFields ({ desc = LE_Var x; _ }, fields) ->
set_fields_should_reduce_to_call env le x fields e
| LE_SetFields (sub_le, fields) ->
let old_le le' = LE_SetFields (le', fields) |> here in
with_temp old_le sub_le
| LE_Slice ({ desc = LE_Var x; _ }, slices) -> (
let slices = Slice_Single e :: slices in
match should_slices_reduce_to_call env x slices with
| None -> None
| Some args ->
let name, args, eqs, ret_ty =
annotate_call (to_pos le) env x args [] ST_Setter
in
let () = assert (ret_ty = None) in
Some (S_Call (name, args, eqs) |> here))
| LE_Slice (sub_le, slices) ->
let old_le le' = LE_Slice (le', slices) |> here in
with_temp old_le sub_le
| LE_Destructuring _ -> None
| LE_Var x ->
if should_reduce_to_call env x then
let name, args, eqs, ret_ty =
annotate_call (to_pos le) env x [ e ] [] ST_Setter
in
let () = assert (ret_ty = None) in
Some (S_Call (name, args, eqs) |> here)
else None
| LE_Concat (_les, _) -> None
| LE_SetArray _ -> assert false
let fold_types_func_sig folder f init =
let from_args =
List.fold_left (fun acc (_x, t) -> folder acc t) init f.args
in
match f.return_type with None -> from_args | Some t -> folder from_args t
let get_undeclared_defining env =
let of_ty acc ty =
match ty.desc with
| T_Bits ({ desc = E_Var x; _ }, _) ->
if StaticEnv.is_undefined x env then ISet.add x acc else acc
| _ -> acc
in
fun f -> fold_types_func_sig of_ty f ISet.empty
let use_func_sig f = fold_types_func_sig ASTUtils.use_ty f ISet.empty
let annotate_func_sig ~loc env (f : AST.func) : env * AST.func =
let () =
if false then
Format.eprintf "Annotating %s in env:@ %a.@." f.name StaticEnv.pp_env
env
in
let env1 = { env with local = empty_local } in
let potential_params = get_undeclared_defining env1 f in
let env2, declared_params =
let () =
if false then
Format.eprintf "Defined potential parameters: %a@." ISet.pp_print
potential_params
in
let folder (env1', acc) (x, ty_opt) =
let+ () = check_var_not_in_env loc env1' x in
let+ () =
check_true (ISet.mem x potential_params) @@ fun () ->
fatal_from loc (Error.ParameterWithoutDecl x)
in
let t =
match ty_opt with
| None | Some { desc = T_Int UnConstrained; _ } ->
Types.under_constrained_ty x
| Some t -> annotate_type ~loc env1 t
in
let+ () = check_constrained_integer ~loc env1 t in
(add_local x t LDK_Let env1', IMap.add x t acc)
in
List.fold_left folder (env1, IMap.empty) f.parameters
in
let () = if false then Format.eprintf "Explicit parameters added.@." in
let env3, arg_params =
let used =
use_func_sig f
|> ISet.filter (fun s ->
StaticEnv.is_undefined s env1 && not (IMap.mem s declared_params))
in
let () =
if false then
Format.eprintf "Undefined used in func sig: %a@." ISet.pp_print used
in
let folder (env2', acc) (x, ty) =
if ISet.mem x used then
let+ () = check_var_not_in_env loc env2' x in
let t =
match ty.desc with
| T_Int UnConstrained -> Types.under_constrained_ty x
| _ -> annotate_type ~loc env2 ty
in
let+ () = check_constrained_integer ~loc env2 t in
(add_local x t LDK_Let env2', IMap.add x t acc)
else (env2', acc)
in
List.fold_left folder (env2, IMap.empty) f.args
in
let parameters =
List.append (IMap.bindings declared_params) (IMap.bindings arg_params)
|> List.map (fun (x, t) -> (x, Some t))
in
let env3, parameters =
if C.check = `TypeCheck then (env3, parameters)
else
let folder x (env3', parameters) =
if var_in_env env3 x then (env3', parameters)
else
let t = Types.under_constrained_ty x in
(add_local x t LDK_Let env3', (x, Some t) :: parameters)
in
ISet.fold folder potential_params (env3, parameters)
in
let () =
if false then
Format.eprintf "@[<hov>Annotating arguments in env:@ %a@]@."
StaticEnv.pp_env env3
in
let env4, args =
let one_arg env3' (x, ty) =
if IMap.mem x arg_params then
let ty' = annotate_type ~loc env2 ty in
(env3', (x, ty'))
else
let () = if false then Format.eprintf "Adding argument %s.@." x in
let+ () = check_var_not_in_env loc env3' x in
let ty' = annotate_type ~loc env3 ty in
let env3'' = add_local x ty' LDK_Let env3' in
(env3'', (x, ty'))
in
list_fold_left_map one_arg env3 f.args
in
let env5, return_type =
match f.return_type with
| None -> (env4, f.return_type)
| Some ty ->
let () =
if false then
Format.eprintf "@[<hov>Annotating return-type in env:@ %a@]@."
StaticEnv.pp_env env3
in
let ty' = annotate_type ~loc env3 ty in
let return_type = Some ty' in
let env4' =
StaticEnv.{ env4 with local = { env4.local with return_type } }
in
(env4', return_type)
in
(env5, { f with parameters; args; return_type })
let annotate_subprogram (env : env) (f : AST.func) : AST.func =
let () =
if false then
Format.eprintf "@[<hov>Annotating body in env:@ %a@]@." StaticEnv.pp_env
env
in
let body =
match f.body with SB_ASL body -> body | SB_Primitive -> assert false
in
let new_body = try_annotate_block env body in
{ f with body = SB_ASL new_body } |: TypingRule.Subprogram
let try_annotate_subprogram env f = best_effort f (annotate_subprogram env)
let declare_one_func loc (func_sig : func) env =
let env, 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 env name' in
let func_sig = { func_sig with name = name' } in
(add_subprogram name' func_sig env, func_sig)
let annotate_and_declare_func ~loc func env =
let env, func = annotate_func_sig ~loc env func in
declare_one_func loc func env
let add_global_storage loc name keyword env ty =
if is_global_ignored name then env
else
let+ () = check_var_not_in_genv loc env name in
add_global_storage name ty keyword env
let declare_const loc name t v env =
add_global_storage loc name GDK_Constant env t |> add_global_constant name v
let declare_type loc name ty s env =
let () =
if false then Format.eprintf "Declaring type %s of %a@." name PP.pp_ty ty
in
let+ () = check_var_not_in_genv loc env name in
let env, ty =
match s with
| None -> (env, ty)
| Some (s, ) ->
let+ () =
fun () ->
if Types.subtype_satisfies env ty (T_Named s |> add_pos_from loc)
then ()
else conflict loc [ T_Named s ] ty
in
let ty =
if extra_fields = [] then ty
else
match IMap.find_opt s env.global.declared_types with
| Some { desc = T_Record fields; _ } ->
T_Record (fields @ extra_fields) |> add_pos_from_st ty
| Some { desc = T_Exception fields; _ } ->
T_Exception (fields @ extra_fields) |> add_pos_from_st ty
| Some _ -> conflict loc [ T_Record []; T_Exception [] ] ty
| None -> undefined_identifier loc s
and env = add_subtype name s env in
(env, ty)
in
let ty' = annotate_type ~decl:true ~loc env ty in
let env = add_type name ty' env in
let res =
match ty'.desc with
| T_Enum ids ->
let t = T_Named name |> add_pos_from ty in
let declare_one (env, i) x =
(declare_const loc x t (L_Int (Z.of_int i)) env, succ i)
in
let env, _ = List.fold_left declare_one (env, 0) ids in
env
| _ -> env
in
let () = if false then Format.eprintf "Declared %s.@." name in
res
let try_add_global_constant name env e =
try
let v = reduce_constants env e in
add_global_constant name v env
with Error.ASLException _ -> env
let declare_global_storage loc gsd env =
let () = if false then Format.eprintf "Declaring %s@." gsd.name in
best_effort (gsd, env) @@ fun _ ->
let { keyword; initial_value; ty; name } = gsd in
let+ () = check_var_not_in_genv loc env name in
let ty' =
match ty with Some ty -> Some (annotate_type ~loc env ty) | None -> ty
in
let typed_initial_value =
match initial_value with
| Some e -> Some (annotate_expr env e)
| None -> None
in
let declared_t =
match (typed_initial_value, ty') with
| Some (t, _), Some ty ->
let+ () = check_type_satisfies loc env t ty in
ty
| None, Some ty -> ty
| Some (t, _), None -> t
| None, None ->
Error.fatal_from loc
(Error.NotYetImplemented
"Global storage declaration must have an initial value or a \
type.")
in
let env1 = add_global_storage loc name keyword env declared_t in
let env2 =
match (keyword, typed_initial_value) with
| GDK_Constant, Some (_t, e) -> try_add_global_constant name env1 e
| (GDK_Constant | GDK_Let), None ->
Error.fatal_from loc
(Error.NotYetImplemented
"Constants or let-bindings must be initialized.")
| _ -> env1
in
let initial_value' =
match typed_initial_value with None -> None | Some (_t, e) -> Some e
in
({ gsd with ty = ty'; initial_value = initial_value' }, env2)
let rename_primitive loc env (f : AST.func) =
let name =
best_effort f.name @@ fun _ ->
let _, name, _, _, _ =
Fn.find_name loc env f.name (List.map snd f.args)
in
name
in
{ f with name }
let type_check_decl d (acc, env) =
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
StaticEnv.pp_env env
else if false then Format.eprintf "@[Typing %a.@]@." PP.pp_t [ d ]
in
match d.desc with
| D_Func ({ body = SB_ASL _; _ } as f) ->
let env, f = annotate_and_declare_func ~loc f env in
let d = D_Func (try_annotate_subprogram env f) |> here in
(d :: acc, env)
| D_Func ({ body = SB_Primitive; _ } as f) ->
let env, f = annotate_and_declare_func ~loc f env in
let d = D_Func f |> here in
(d :: acc, env)
| D_GlobalStorage gsd ->
let gsd', env' = declare_global_storage loc gsd env in
let d' = D_GlobalStorage gsd' |> here in
(d' :: acc, env')
| D_TypeDecl (x, ty, s) ->
let env = declare_type loc x ty s env in
(d :: acc, env)
let type_check_mutually_rec ds (acc, env) =
let env_and_fs =
List.map
(fun d ->
match d.desc with
| D_Func f ->
let loc = to_pos d in
let env', f = annotate_func_sig ~loc env f in
(env'.local, f, loc)
| _ ->
fatal_from d
(Error.BadRecursiveDecls
(List.map ASTUtils.identifier_of_decl ds)))
ds
in
let genv, fs =
list_fold_left_map
(fun genv (lenv, f, loc) ->
let env = { global = genv; local = lenv } in
let env', f = declare_one_func loc f env in
(env'.global, (env'.local, f, loc)))
env.global env_and_fs
in
let ds =
List.map
(fun (lenv, f, loc) ->
let here = add_pos_from loc in
let env' = { local = lenv; global = genv } in
match f.body with
| SB_ASL _ ->
let () =
if false then Format.eprintf "@[Analysing decl %s.@]@." f.name
in
D_Func (try_annotate_subprogram env' f) |> here
| SB_Primitive -> D_Func (rename_primitive loc env' f) |> here)
fs
in
(List.rev_append ds acc, { env with global = genv })
let type_check_ast =
let fold = function
| TopoSort.ASTFold.Single d -> type_check_decl d
| TopoSort.ASTFold.Recursive ds -> type_check_mutually_rec ds
in
let fold_topo ast acc = TopoSort.ASTFold.fold fold ast acc in
fun ast env ->
let ast_rev, env = fold_topo ast ([], env) in
(List.rev ast_rev, env)
end
module TypeCheck = Annotate (struct
let check = `TypeCheck
end)
module TypeInferWarn = Annotate (struct
let check = `Warn
end)
module TypeInferSilence = Annotate (struct
let check = `Silence
end)
let type_check_ast = function
| `TypeCheck -> TypeCheck.type_check_ast
| `Warn -> TypeInferWarn.type_check_ast
| `Silence -> TypeInferSilence.type_check_ast