1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
|
local _tl_compat53 = ((tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3) and require('compat53.module'); local assert = _tl_compat53 and _tl_compat53.assert or assert; local io = _tl_compat53 and _tl_compat53.io or io; local ipairs = _tl_compat53 and _tl_compat53.ipairs or ipairs; local load = _tl_compat53 and _tl_compat53.load or load; local math = _tl_compat53 and _tl_compat53.math or math; local os = _tl_compat53 and _tl_compat53.os or os; local package = _tl_compat53 and _tl_compat53.package or package; local pairs = _tl_compat53 and _tl_compat53.pairs or pairs; local string = _tl_compat53 and _tl_compat53.string or string; local table = _tl_compat53 and _tl_compat53.table or table; local _tl_table_unpack = unpack or table.unpack; local Env = {}
local TypeCheckOptions = {}
local LoadMode = {}
local LoadFunction = {}
local tl = {
load = nil,
process = nil,
process_string = nil,
gen = nil,
type_check = nil,
init_env = nil,
}
local inspect = function(x)
return tostring(x)
end
local keywords = {
["and"] = true,
["break"] = true,
["do"] = true,
["else"] = true,
["elseif"] = true,
["end"] = true,
["false"] = true,
["for"] = true,
["function"] = true,
["goto"] = true,
["if"] = true,
["in"] = true,
["local"] = true,
["nil"] = true,
["not"] = true,
["or"] = true,
["repeat"] = true,
["return"] = true,
["then"] = true,
["true"] = true,
["until"] = true,
["while"] = true,
}
local TokenKind = {}
local Token = {}
local lex_word_start = {}
for c = string.byte("a"), string.byte("z") do
lex_word_start[string.char(c)] = true
end
for c = string.byte("A"), string.byte("Z") do
lex_word_start[string.char(c)] = true
end
lex_word_start["_"] = true
local lex_word = {}
for c = string.byte("a"), string.byte("z") do
lex_word[string.char(c)] = true
end
for c = string.byte("A"), string.byte("Z") do
lex_word[string.char(c)] = true
end
for c = string.byte("0"), string.byte("9") do
lex_word[string.char(c)] = true
end
lex_word["_"] = true
local lex_decimal_start = {}
for c = string.byte("1"), string.byte("9") do
lex_decimal_start[string.char(c)] = true
end
local lex_decimals = {}
for c = string.byte("0"), string.byte("9") do
lex_decimals[string.char(c)] = true
end
local lex_hexadecimals = {}
for c = string.byte("0"), string.byte("9") do
lex_hexadecimals[string.char(c)] = true
end
for c = string.byte("a"), string.byte("f") do
lex_hexadecimals[string.char(c)] = true
end
for c = string.byte("A"), string.byte("F") do
lex_hexadecimals[string.char(c)] = true
end
local lex_char_symbols = {}
for _, c in ipairs({ "[", "]", "(", ")", "{", "}", ",", "#", "`", ";" }) do
lex_char_symbols[c] = true
end
local lex_op_start = {}
for _, c in ipairs({ "+", "*", "/", "|", "&", "%", "^" }) do
lex_op_start[c] = true
end
local lex_space = {}
for _, c in ipairs({ " ", "\t", "\v", "\n", "\r" }) do
lex_space[c] = true
end
local LexState = {}
function tl.lex(input)
local tokens = {}
local state = "start"
local fwd = true
local y = 1
local x = 0
local i = 0
local lc_open_lvl = 0
local lc_close_lvl = 0
local ls_open_lvl = 0
local ls_close_lvl = 0
local errs = {}
local tx
local ty
local ti
local in_token = false
local function begin_token()
tx = x
ty = y
ti = i
in_token = true
end
local function end_token(kind, last, t)
local tk = t or input:sub(ti, last or i) or ""
if keywords[tk] then
kind = "keyword"
end
table.insert(tokens, {
x = tx,
y = ty,
i = ti,
tk = tk,
kind = kind,
})
in_token = false
end
local function drop_token()
in_token = false
end
while i <= #input do
if fwd then
i = i + 1
if i > #input then
break
end
end
local c = input:sub(i, i)
if fwd then
if c == "\n" then
y = y + 1
x = 0
else
x = x + 1
end
else
fwd = true
end
if state == "start" then
if input:sub(1, 2) == "#!" then
i = input:find("\n")
if not i then
break
end
c = "\n"
y = 2
x = 0
end
state = "any"
end
if state == "any" then
if c == "-" then
state = "maybecomment"
begin_token()
elseif c == "." then
state = "maybedotdot"
begin_token()
elseif c == "\"" then
state = "dblquote_string"
begin_token()
elseif c == "'" then
state = "singlequote_string"
begin_token()
elseif lex_word_start[c] then
state = "identifier"
begin_token()
elseif c == "0" then
state = "decimal_or_hex"
begin_token()
elseif lex_decimal_start[c] then
state = "decimal_number"
begin_token()
elseif c == "<" then
state = "lt"
begin_token()
elseif c == ":" then
state = "colon"
begin_token()
elseif c == ">" then
state = "gt"
begin_token()
elseif c == "=" or c == "~" then
state = "maybeequals"
begin_token()
elseif c == "[" then
state = "maybelongstring"
begin_token()
elseif lex_char_symbols[c] then
begin_token()
end_token(c)
elseif lex_op_start[c] then
begin_token()
end_token("op")
elseif lex_space[c] then
else
begin_token()
end_token("$invalid$")
table.insert(errs, tokens[#tokens])
end
elseif state == "maybecomment" then
if c == "-" then
state = "maybecomment2"
else
end_token("op", nil, "-")
fwd = false
state = "any"
end
elseif state == "maybecomment2" then
if c == "[" then
state = "maybelongcomment"
else
fwd = false
state = "comment"
drop_token()
end
elseif state == "maybelongcomment" then
if c == "[" then
state = "longcomment"
elseif c == "=" then
lc_open_lvl = lc_open_lvl + 1
else
fwd = false
state = "comment"
drop_token()
lc_open_lvl = 0
end
elseif state == "longcomment" then
if c == "]" then
state = "maybelongcommentend"
end
elseif state == "maybelongcommentend" then
if c == "]" and lc_close_lvl == lc_open_lvl then
drop_token()
state = "any"
lc_open_lvl = 0
lc_close_lvl = 0
elseif c == "=" then
lc_close_lvl = lc_close_lvl + 1
else
state = "longcomment"
lc_close_lvl = 0
end
elseif state == "dblquote_string" then
if c == "\\" then
state = "escape_dblquote_string"
elseif c == "\"" then
end_token("string")
state = "any"
end
elseif state == "escape_dblquote_string" then
state = "dblquote_string"
elseif state == "singlequote_string" then
if c == "\\" then
state = "escape_singlequote_string"
elseif c == "'" then
end_token("string")
state = "any"
end
elseif state == "escape_singlequote_string" then
state = "singlequote_string"
elseif state == "maybeequals" then
if c == "=" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "lt" then
if c == "=" or c == "<" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "colon" then
if c == ":" then
end_token("::")
state = "any"
else
end_token(":", i - 1)
fwd = false
state = "any"
end
elseif state == "gt" then
if c == "=" or c == ">" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "maybelongstring" then
if c == "[" then
state = "longstring"
elseif c == "=" then
ls_open_lvl = ls_open_lvl + 1
else
end_token("[", i - 1)
fwd = false
state = "any"
ls_open_lvl = 0
end
elseif state == "longstring" then
if c == "]" then
state = "maybelongstringend"
end
elseif state == "maybelongstringend" then
if c == "]" then
if ls_close_lvl == ls_open_lvl then
end_token("string")
state = "any"
ls_open_lvl = 0
ls_close_lvl = 0
end
elseif c == "=" then
ls_close_lvl = ls_close_lvl + 1
else
state = "longstring"
ls_close_lvl = 0
end
elseif state == "maybedotdot" then
if c == "." then
state = "maybedotdotdot"
elseif lex_decimals[c] then
state = "decimal_float"
else
end_token(".", i - 1)
fwd = false
state = "any"
end
elseif state == "maybedotdotdot" then
if c == "." then
end_token("...")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "comment" then
if c == "\n" then
state = "any"
end
elseif state == "identifier" then
if not lex_word[c] then
end_token("identifier", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_or_hex" then
if c == "x" or c == "X" then
state = "hex_number"
elseif c == "e" or c == "E" then
state = "power_sign"
elseif lex_decimals[c] then
state = "decimal_number"
elseif c == "." then
state = "decimal_float"
else
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "hex_number" then
if c == "." then
state = "hex_float"
elseif c == "p" or c == "P" then
state = "power_sign"
elseif not lex_hexadecimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "hex_float" then
if c == "p" or c == "P" then
state = "power_sign"
elseif not lex_hexadecimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_number" then
if c == "." then
state = "decimal_float"
elseif c == "e" or c == "E" then
state = "power_sign"
elseif not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_float" then
if c == "e" or c == "E" then
state = "power_sign"
elseif not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "power_sign" then
if c == "-" or c == "+" then
state = "power"
elseif lex_decimals[c] then
state = "power"
else
end_token("$invalid$")
table.insert(errs, tokens[#tokens])
state = "any"
end
elseif state == "power" then
if not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
end
end
local terminals = {
["identifier"] = "identifier",
["decimal_or_hex"] = "number",
["decimal_number"] = "number",
["decimal_float"] = "number",
["hex_number"] = "number",
["hex_float"] = "number",
["power"] = "number",
}
if in_token then
if terminals[state] then
end_token(terminals[state], i - 1)
else
drop_token()
end
end
return tokens, (#errs > 0) and errs
end
local add_space = {
["word:keyword"] = true,
["word:word"] = true,
["word:string"] = true,
["word:="] = true,
["word:op"] = true,
["keyword:word"] = true,
["keyword:keyword"] = true,
["keyword:string"] = true,
["keyword:number"] = true,
["keyword:="] = true,
["keyword:op"] = true,
["keyword:{"] = true,
["keyword:("] = true,
["keyword:#"] = true,
["=:word"] = true,
["=:keyword"] = true,
["=:string"] = true,
["=:number"] = true,
["=:{"] = true,
["=:("] = true,
["op:("] = true,
["op:{"] = true,
["op:#"] = true,
[",:word"] = true,
[",:keyword"] = true,
[",:string"] = true,
[",:{"] = true,
["):op"] = true,
["):word"] = true,
["):keyword"] = true,
["op:string"] = true,
["op:number"] = true,
["op:word"] = true,
["op:keyword"] = true,
["]:word"] = true,
["]:keyword"] = true,
["]:="] = true,
["]:op"] = true,
["string:op"] = true,
["string:word"] = true,
["string:keyword"] = true,
["number:word"] = true,
["number:keyword"] = true,
}
local should_unindent = {
["end"] = true,
["elseif"] = true,
["else"] = true,
["}"] = true,
}
local should_indent = {
["{"] = true,
["for"] = true,
["if"] = true,
["while"] = true,
["elseif"] = true,
["else"] = true,
["function"] = true,
}
function tl.pretty_print_tokens(tokens)
local y = 1
local out = {}
local indent = 0
local newline = false
local kind = ""
for _, t in ipairs(tokens) do
while t.y > y do
table.insert(out, "\n")
y = y + 1
newline = true
kind = ""
end
if should_unindent[t.tk] then
indent = indent - 1
if indent < 0 then
indent = 0
end
end
if newline then
for _ = 1, indent do
table.insert(out, " ")
end
newline = false
end
if should_indent[t.tk] then
indent = indent + 1
end
if add_space[(kind or "") .. ":" .. t.kind] then
table.insert(out, " ")
end
table.insert(out, t.tk)
kind = t.kind or ""
end
return table.concat(out)
end
local last_typeid = 0
local function new_typeid()
last_typeid = last_typeid + 1
return last_typeid
end
local ParseError = {}
local TypeName = {}
local table_types = {
["array"] = true,
["map"] = true,
["arrayrecord"] = true,
["record"] = true,
["emptytable"] = true,
}
local Type = {}
local Operator = {}
local NodeKind = {}
local FactType = {}
local Fact = {}
local KeyParsed = {}
local Node = {}
local function is_array_type(t)
return t.typename == "array" or t.typename == "arrayrecord"
end
local function is_record_type(t)
return t.typename == "record" or t.typename == "arrayrecord"
end
local function is_type(t)
return t.typename == "typetype" or t.typename == "nestedtype"
end
local ParseState = {}
local ParseTypeListMode = {}
local parse_type_list
local parse_expression
local parse_statements
local parse_argument_list
local parse_argument_type_list
local parse_type
local parse_newtype
local function fail(ps, i, msg)
if not ps.tokens[i] then
local eof = ps.tokens[#ps.tokens]
table.insert(ps.errs, { y = eof.y, x = eof.x, msg = msg or "unexpected end of file" })
return #ps.tokens
end
table.insert(ps.errs, { y = ps.tokens[i].y, x = ps.tokens[i].x, msg = msg or "syntax error" })
return math.min(#ps.tokens, i + 1)
end
local function verify_tk(ps, i, tk)
if ps.tokens[i].tk == tk then
return i + 1
end
return fail(ps, i, "syntax error, expected '" .. tk .. "'")
end
local function new_node(tokens, i, kind)
local t = tokens[i]
return { y = t.y, x = t.x, tk = t.tk, kind = kind or t.kind }
end
local function a_type(t)
t.typeid = new_typeid()
return t
end
local function new_type(ps, i, typename)
local token = ps.tokens[i]
return a_type({
typename = assert(typename),
filename = ps.filename,
y = token.y,
x = token.x,
tk = token.tk,
})
end
local function verify_kind(ps, i, kind, node_kind)
if ps.tokens[i].kind == kind then
return i + 1, new_node(ps.tokens, i, node_kind)
end
return fail(ps, i, "syntax error, expected " .. kind)
end
local is_newtype = {
["enum"] = true,
["record"] = true,
}
local function parse_table_value(ps, i)
if is_newtype[ps.tokens[i].tk] then
return parse_newtype(ps, i)
else
local i, node, _ = parse_expression(ps, i)
return i, node
end
end
local function parse_table_item(ps, i, n)
local node = new_node(ps.tokens, i, "table_item")
if ps.tokens[i].kind == "$EOF$" then
return fail(ps, i)
end
if ps.tokens[i].tk == "[" then
node.key_parsed = "long"
i = i + 1
i, node.key = parse_expression(ps, i)
i = verify_tk(ps, i, "]")
i = verify_tk(ps, i, "=")
i, node.value = parse_table_value(ps, i)
return i, node, n
elseif ps.tokens[i].kind == "identifier" and ps.tokens[i + 1].tk == "=" then
node.key_parsed = "short"
i, node.key = verify_kind(ps, i, "identifier", "string")
node.key.conststr = node.key.tk
node.key.tk = '"' .. node.key.tk .. '"'
i = verify_tk(ps, i, "=")
i, node.value = parse_table_value(ps, i)
return i, node, n
elseif ps.tokens[i].kind == "identifier" and ps.tokens[i + 1].tk == ":" then
node.key_parsed = "short"
local orig_i = i
local try_ps = {
filename = ps.filename,
tokens = ps.tokens,
errs = {},
}
i, node.key = verify_kind(try_ps, i, "identifier", "string")
node.key.conststr = node.key.tk
node.key.tk = '"' .. node.key.tk .. '"'
i = verify_tk(try_ps, i, ":")
i, node.decltype = parse_type(try_ps, i)
if node.decltype and ps.tokens[i].tk == "=" then
i = verify_tk(try_ps, i, "=")
i, node.value = parse_table_value(try_ps, i)
if node.value then
for _, e in ipairs(try_ps.errs) do
table.insert(ps.errs, e)
end
return i, node, n
end
end
node.decltype = nil
i = orig_i
end
node.key = new_node(ps.tokens, i, "number")
node.key_parsed = "implicit"
node.key.constnum = n
node.key.tk = tostring(n)
i, node.value = parse_expression(ps, i)
return i, node, n + 1
end
local ParseItem = {}
local SeparatorMode = {}
local function parse_list(ps, i, list, close, sep, parse_item)
local n = 1
while ps.tokens[i].kind ~= "$EOF$" do
if close[ps.tokens[i].tk] then
(list).yend = ps.tokens[i].y
break
end
local item
i, item, n = parse_item(ps, i, n)
table.insert(list, item)
if ps.tokens[i].tk == "," then
i = i + 1
if sep == "sep" and close[ps.tokens[i].tk] then
return fail(ps, i)
end
elseif sep == "term" and ps.tokens[i].tk == ";" then
i = i + 1
elseif not close[ps.tokens[i].tk] then
return fail(ps, i)
end
end
return i, list
end
local function parse_bracket_list(ps, i, list, open, close, sep, parse_item)
i = verify_tk(ps, i, open)
i = parse_list(ps, i, list, { [close] = true }, sep, parse_item)
i = verify_tk(ps, i, close)
return i, list
end
local function parse_table_literal(ps, i)
local node = new_node(ps.tokens, i, "table_literal")
return parse_bracket_list(ps, i, node, "{", "}", "term", parse_table_item)
end
local function parse_trying_list(ps, i, list, parse_item)
local try_ps = {
filename = ps.filename,
tokens = ps.tokens,
errs = {},
}
local tryi, item = parse_item(try_ps, i)
if not item then
return i, list
end
for _, e in ipairs(try_ps.errs) do
table.insert(ps.errs, e)
end
i = tryi
table.insert(list, item)
if ps.tokens[i].tk == "," then
while ps.tokens[i].tk == "," do
i = i + 1
i, item = parse_item(ps, i)
table.insert(list, item)
end
end
return i, list
end
local function parse_typearg_type(ps, i)
local backtick = false
if ps.tokens[i].tk == "`" then
i = verify_tk(ps, i, "`")
backtick = true
end
i = verify_kind(ps, i, "identifier")
return i, a_type({
y = ps.tokens[i - 2].y,
x = ps.tokens[i - 2].x,
typename = "typearg",
typearg = (backtick and "`" or "") .. ps.tokens[i - 1].tk,
})
end
local function parse_typevar_type(ps, i)
i = verify_tk(ps, i, "`")
i = verify_kind(ps, i, "identifier")
return i, a_type({
y = ps.tokens[i - 2].y,
x = ps.tokens[i - 2].x,
typename = "typevar",
typevar = "`" .. ps.tokens[i - 1].tk,
})
end
local function parse_typearg_list(ps, i)
local typ = new_type(ps, i, "tuple")
return parse_bracket_list(ps, i, typ, "<", ">", "sep", parse_typearg_type)
end
local function parse_typeval_list(ps, i)
local typ = new_type(ps, i, "tuple")
return parse_bracket_list(ps, i, typ, "<", ">", "sep", parse_type)
end
local function parse_return_types(ps, i)
return parse_type_list(ps, i, "rets")
end
local function parse_function_type(ps, i)
local node = new_type(ps, i, "function")
node.args = {}
node.rets = {}
i = i + 1
if ps.tokens[i].tk == "<" then
i, node.typeargs = parse_typearg_list(ps, i)
end
if ps.tokens[i].tk == "(" then
i, node.args = parse_argument_type_list(ps, i)
i, node.rets = parse_return_types(ps, i)
else
node.args = { a_type({ typename = "any", is_va = true }) }
node.rets = { a_type({ typename = "any", is_va = true }) }
end
return i, node
end
local function parse_base_type(ps, i)
if ps.tokens[i].tk == "string" or
ps.tokens[i].tk == "boolean" or
ps.tokens[i].tk == "nil" or
ps.tokens[i].tk == "number" or
ps.tokens[i].tk == "thread" then
local typ = new_type(ps, i, ps.tokens[i].tk)
typ.tk = nil
return i + 1, typ
elseif ps.tokens[i].tk == "table" then
local typ = new_type(ps, i, "map")
typ.keys = a_type({ typename = "any" })
typ.values = a_type({ typename = "any" })
return i + 1, typ
elseif ps.tokens[i].tk == "function" then
return parse_function_type(ps, i)
elseif ps.tokens[i].tk == "{" then
i = i + 1
local decl = new_type(ps, i, "array")
local t
i, t = parse_type(ps, i)
if ps.tokens[i].tk == "}" then
decl.elements = t
decl.yend = ps.tokens[i].y
i = verify_tk(ps, i, "}")
elseif ps.tokens[i].tk == ":" then
decl.typename = "map"
i = i + 1
decl.keys = t
i, decl.values = parse_type(ps, i)
decl.yend = ps.tokens[i].y
i = verify_tk(ps, i, "}")
end
return i, decl
elseif ps.tokens[i].tk == "`" then
return parse_typevar_type(ps, i)
elseif ps.tokens[i].kind == "identifier" then
local typ = new_type(ps, i, "nominal")
typ.names = { ps.tokens[i].tk }
i = i + 1
while ps.tokens[i].tk == "." do
i = i + 1
if ps.tokens[i].kind == "identifier" then
table.insert(typ.names, ps.tokens[i].tk)
i = i + 1
else
return fail(ps, i, "syntax error, expected identifier")
end
end
if ps.tokens[i].tk == "<" then
i, typ.typevals = parse_typeval_list(ps, i)
end
return i, typ
end
return fail(ps, i)
end
parse_type = function(ps, i)
if ps.tokens[i].tk == "(" then
i = i + 1
local t
i, t = parse_type(ps, i)
i = verify_tk(ps, i, ")")
return i, t
end
local bt
local istart = i
i, bt = parse_base_type(ps, i)
if not bt then
return i
end
if ps.tokens[i].tk == "|" then
local u = new_type(ps, istart, "union")
u.types = { bt }
while ps.tokens[i].tk == "|" do
i = i + 1
i, bt = parse_base_type(ps, i)
if not bt then
return i
end
table.insert(u.types, bt)
end
bt = u
end
return i, bt
end
parse_type_list = function(ps, i, mode)
local list = new_type(ps, i, "tuple")
local first_token = ps.tokens[i].tk
if mode == "rets" or mode == "decltype" then
if first_token == ":" then
i = i + 1
else
return i, list
end
end
local optional_paren = false
if ps.tokens[i].tk == "(" then
optional_paren = true
i = i + 1
end
local prev_i = i
i = parse_trying_list(ps, i, list, parse_type)
if i == prev_i and ps.tokens[i].tk ~= ")" then
fail(ps, i - 1, "expected a type list")
end
if mode == "rets" and ps.tokens[i].tk == "..." then
i = i + 1
local nrets = #list
if nrets > 0 then
list[nrets].is_va = true
else
return fail(ps, i, "unexpected '...'")
end
end
if optional_paren then
i = verify_tk(ps, i, ")")
end
return i, list
end
local function parse_function_args_rets_body(ps, i, node)
if ps.tokens[i].tk == "<" then
i, node.typeargs = parse_typearg_list(ps, i)
end
i, node.args = parse_argument_list(ps, i)
i, node.rets = parse_return_types(ps, i)
i, node.body = parse_statements(ps, i)
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_function_value(ps, i)
local node = new_node(ps.tokens, i, "function")
i = verify_tk(ps, i, "function")
return parse_function_args_rets_body(ps, i, node)
end
local function unquote(str)
local f = str:sub(1, 1)
if f == '"' or f == "'" then
return str:sub(2, -2)
end
f = str:match("^%[=*%[")
local l = #f + 1
return str:sub(l, -l)
end
local function parse_literal(ps, i)
if ps.tokens[i].tk == "{" then
return parse_table_literal(ps, i)
elseif ps.tokens[i].kind == "..." then
return verify_kind(ps, i, "...")
elseif ps.tokens[i].kind == "string" then
local tk = unquote(ps.tokens[i].tk)
local node
i, node = verify_kind(ps, i, "string")
node.conststr = tk
return i, node
elseif ps.tokens[i].kind == "identifier" then
return verify_kind(ps, i, "identifier", "variable")
elseif ps.tokens[i].kind == "number" then
local n = tonumber(ps.tokens[i].tk)
local node
i, node = verify_kind(ps, i, "number")
node.constnum = n
return i, node
elseif ps.tokens[i].tk == "true" then
return verify_kind(ps, i, "keyword", "boolean")
elseif ps.tokens[i].tk == "false" then
return verify_kind(ps, i, "keyword", "boolean")
elseif ps.tokens[i].tk == "nil" then
return verify_kind(ps, i, "keyword", "nil")
elseif ps.tokens[i].tk == "function" then
return parse_function_value(ps, i)
end
return fail(ps, i)
end
do
local precedences = {
[1] = {
["not"] = 11,
["#"] = 11,
["-"] = 11,
["~"] = 11,
},
[2] = {
["or"] = 1,
["and"] = 2,
["is"] = 3,
["<"] = 3,
[">"] = 3,
["<="] = 3,
[">="] = 3,
["~="] = 3,
["=="] = 3,
["|"] = 4,
["~"] = 5,
["&"] = 6,
["<<"] = 7,
[">>"] = 7,
[".."] = 8,
["+"] = 8,
["-"] = 9,
["*"] = 10,
["/"] = 10,
["//"] = 10,
["%"] = 10,
["^"] = 12,
["as"] = 50,
["@funcall"] = 100,
["@index"] = 100,
["."] = 100,
[":"] = 100,
},
}
local is_right_assoc = {
["^"] = true,
[".."] = true,
}
local function new_operator(tk, arity, op)
op = op or tk.tk
return { y = tk.y, x = tk.x, arity = arity, op = op, prec = precedences[arity][op] }
end
local E
local function P(ps, i)
if ps.tokens[i].kind == "$EOF$" then
return i
end
local e1
local t1 = ps.tokens[i]
if precedences[1][ps.tokens[i].tk] ~= nil then
local op = new_operator(ps.tokens[i], 1)
i = i + 1
i, e1 = P(ps, i)
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1 }
elseif ps.tokens[i].tk == "(" then
i = i + 1
i, e1 = parse_expression(ps, i)
e1 = { y = t1.y, x = t1.x, kind = "paren", e1 = e1 }
i = verify_tk(ps, i, ")")
else
i, e1 = parse_literal(ps, i)
end
while true do
if ps.tokens[i].kind == "string" or ps.tokens[i].kind == "{" then
local op = new_operator(ps.tokens[i], 2, "@funcall")
local args = new_node(ps.tokens, i, "expression_list")
local arg
if ps.tokens[i].kind == "string" then
arg = new_node(ps.tokens, i)
arg.conststr = unquote(ps.tokens[i].tk)
i = i + 1
else
i, arg = parse_table_literal(ps, i)
end
table.insert(args, arg)
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1, e2 = args }
elseif ps.tokens[i].tk == "(" then
local op = new_operator(ps.tokens[i], 2, "@funcall")
local args = new_node(ps.tokens, i, "expression_list")
i, args = parse_bracket_list(ps, i, args, "(", ")", "sep", parse_expression)
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1, e2 = args }
elseif ps.tokens[i].tk == "[" then
local op = new_operator(ps.tokens[i], 2, "@index")
local idx
i = i + 1
i, idx = parse_expression(ps, i)
i = verify_tk(ps, i, "]")
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1, e2 = idx }
elseif ps.tokens[i].tk == "." or ps.tokens[i].tk == ":" then
local op = new_operator(ps.tokens[i], 2)
local key
i = i + 1
i, key = verify_kind(ps, i, "identifier")
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1, e2 = key }
elseif ps.tokens[i].tk == "as" or ps.tokens[i].tk == "is" then
local op = new_operator(ps.tokens[i], 2, ps.tokens[i].tk)
i = i + 1
local cast = new_node(ps.tokens, i, "cast")
if ps.tokens[i].tk == "(" then
i, cast.casttype = parse_type_list(ps, i, "casttype")
else
i, cast.casttype = parse_type(ps, i)
end
e1 = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = e1, e2 = cast, conststr = e1.conststr }
else
break
end
end
return i, e1
end
local function E(ps, i, lhs, min_precedence)
local lookahead = ps.tokens[i].tk
while precedences[2][lookahead] and precedences[2][lookahead] >= min_precedence do
local t1 = ps.tokens[i]
local op = new_operator(t1, 2)
i = i + 1
local rhs
i, rhs = P(ps, i)
lookahead = ps.tokens[i].tk
while precedences[2][lookahead] and ((precedences[2][lookahead] > (precedences[2][op.op])) or
(is_right_assoc[lookahead] and (precedences[2][lookahead] == precedences[2][op.op]))) do
i, rhs = E(ps, i, rhs, precedences[2][lookahead])
lookahead = ps.tokens[i].tk
end
lhs = { y = t1.y, x = t1.x, kind = "op", op = op, e1 = lhs, e2 = rhs }
end
return i, lhs
end
parse_expression = function(ps, i)
local lhs
i, lhs = P(ps, i)
i, lhs = E(ps, i, lhs, 0)
if lhs then
return i, lhs, 0
else
return fail(ps, i, "expected an expression")
end
end
end
local function parse_variable_name(ps, i)
local is_const = false
local node
i, node = verify_kind(ps, i, "identifier")
if not node then
return i
end
if ps.tokens[i].tk == "<" then
i = i + 1
local annotation
i, annotation = verify_kind(ps, i, "identifier")
if annotation and annotation.tk == "const" then
is_const = true
end
i = verify_tk(ps, i, ">")
end
node.is_const = is_const
return i, node
end
local function parse_argument(ps, i)
local node
if ps.tokens[i].tk == "..." then
i, node = verify_kind(ps, i, "...")
else
i, node = verify_kind(ps, i, "identifier", "argument")
end
if ps.tokens[i].tk == ":" then
i = i + 1
local decltype
i, decltype = parse_type(ps, i)
if node then
i, node.decltype = i, decltype
end
end
return i, node, 0
end
parse_argument_list = function(ps, i)
local node = new_node(ps.tokens, i, "argument_list")
return parse_bracket_list(ps, i, node, "(", ")", "sep", parse_argument)
end
local function parse_argument_type(ps, i)
local is_va = false
if ps.tokens[i].kind == "identifier" and ps.tokens[i + 1].tk == ":" then
i = i + 2
elseif ps.tokens[i].tk == "..." then
if ps.tokens[i + 1].tk == ":" then
i = i + 2
is_va = true
else
return fail(ps, i, "cannot have untyped '...' when declaring the type of an argument")
end
end
local i, typ = parse_type(ps, i)
if typ then
typ.is_va = is_va
end
return i, typ, 0
end
parse_argument_type_list = function(ps, i)
local list = new_type(ps, i, "tuple")
return parse_bracket_list(ps, i, list, "(", ")", "sep", parse_argument_type)
end
local function parse_local_function(ps, i)
local node = new_node(ps.tokens, i, "local_function")
i = verify_tk(ps, i, "local")
i = verify_tk(ps, i, "function")
i, node.name = verify_kind(ps, i, "identifier")
return parse_function_args_rets_body(ps, i, node)
end
local function parse_function(ps, i)
local orig_i = i
local fn = new_node(ps.tokens, i, "global_function")
local node = fn
i = verify_tk(ps, i, "function")
local names = {}
i, names[1] = verify_kind(ps, i, "identifier", "variable")
while ps.tokens[i].tk == "." do
i = i + 1
i, names[#names + 1] = verify_kind(ps, i, "identifier")
end
if ps.tokens[i].tk == ":" then
i = i + 1
i, names[#names + 1] = verify_kind(ps, i, "identifier")
fn.is_method = true
end
if #names > 1 then
fn.kind = "record_function"
local owner = names[1]
for i = 2, #names - 1 do
local dot = { y = names[i].y, x = names[i].x - 1, arity = 2, op = "." }
names[i].kind = "identifier"
local op = { y = names[i].y, x = names[i].x, kind = "op", op = dot, e1 = owner, e2 = names[i] }
owner = op
end
fn.fn_owner = owner
end
fn.name = names[#names]
local selfx, selfy = ps.tokens[i].x, ps.tokens[i].y
i = parse_function_args_rets_body(ps, i, fn)
if fn.is_method then
table.insert(fn.args, 1, { x = selfx, y = selfy, tk = "self", kind = "variable" })
end
if not fn.name then
return orig_i
end
return i, node
end
local function parse_if(ps, i)
local node = new_node(ps.tokens, i, "if")
i = verify_tk(ps, i, "if")
i, node.exp = parse_expression(ps, i)
i = verify_tk(ps, i, "then")
i, node.thenpart = parse_statements(ps, i)
node.elseifs = {}
local n = 0
while ps.tokens[i].tk == "elseif" do
n = n + 1
local subnode = new_node(ps.tokens, i, "elseif")
subnode.parent_if = node
subnode.elseif_n = n
i = i + 1
i, subnode.exp = parse_expression(ps, i)
i = verify_tk(ps, i, "then")
i, subnode.thenpart = parse_statements(ps, i)
table.insert(node.elseifs, subnode)
end
if ps.tokens[i].tk == "else" then
local subnode = new_node(ps.tokens, i, "else")
subnode.parent_if = node
i = i + 1
i, subnode.elsepart = parse_statements(ps, i)
node.elsepart = subnode
end
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_while(ps, i)
local node = new_node(ps.tokens, i, "while")
i = verify_tk(ps, i, "while")
i, node.exp = parse_expression(ps, i)
i = verify_tk(ps, i, "do")
i, node.body = parse_statements(ps, i)
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_fornum(ps, i)
local node = new_node(ps.tokens, i, "fornum")
i = i + 1
i, node.var = verify_kind(ps, i, "identifier")
i = verify_tk(ps, i, "=")
i, node.from = parse_expression(ps, i)
i = verify_tk(ps, i, ",")
i, node.to = parse_expression(ps, i)
if ps.tokens[i].tk == "," then
i = i + 1
i, node.step = parse_expression(ps, i)
end
i = verify_tk(ps, i, "do")
i, node.body = parse_statements(ps, i)
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_forin(ps, i)
local node = new_node(ps.tokens, i, "forin")
i = i + 1
node.vars = new_node(ps.tokens, i, "variables")
i, node.vars = parse_list(ps, i, node.vars, { ["in"] = true }, "sep", parse_variable_name)
i = verify_tk(ps, i, "in")
node.exps = new_node(ps.tokens, i, "expression_list")
i = parse_list(ps, i, node.exps, { ["do"] = true }, "sep", parse_expression)
if #node.exps < 1 then
return fail(ps, i, "missing iterator expression in generic for")
elseif #node.exps > 3 then
return fail(ps, i, "too many expressions in generic for")
end
i = verify_tk(ps, i, "do")
i, node.body = parse_statements(ps, i)
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_for(ps, i)
if ps.tokens[i + 1].kind == "identifier" and ps.tokens[i + 2].tk == "=" then
return parse_fornum(ps, i)
else
return parse_forin(ps, i)
end
end
local function parse_repeat(ps, i)
local node = new_node(ps.tokens, i, "repeat")
i = verify_tk(ps, i, "repeat")
i, node.body = parse_statements(ps, i)
node.body.is_repeat = true
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "until")
i, node.exp = parse_expression(ps, i)
return i, node
end
local function parse_do(ps, i)
local node = new_node(ps.tokens, i, "do")
i = verify_tk(ps, i, "do")
i, node.body = parse_statements(ps, i)
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_break(ps, i)
local node = new_node(ps.tokens, i, "break")
i = verify_tk(ps, i, "break")
return i, node
end
local function parse_goto(ps, i)
local node = new_node(ps.tokens, i, "goto")
i = verify_tk(ps, i, "goto")
node.label = ps.tokens[i].tk
i = verify_kind(ps, i, "identifier")
return i, node
end
local function parse_label(ps, i)
local node = new_node(ps.tokens, i, "label")
i = verify_tk(ps, i, "::")
node.label = ps.tokens[i].tk
i = verify_kind(ps, i, "identifier")
i = verify_tk(ps, i, "::")
return i, node
end
local stop_statement_list = {
["end"] = true,
["else"] = true,
["elseif"] = true,
["until"] = true,
}
local stop_return_list = {
[";"] = true,
["$EOF$"] = true,
}
for k, v in pairs(stop_statement_list) do
stop_return_list[k] = v
end
local function parse_return(ps, i)
local node = new_node(ps.tokens, i, "return")
i = verify_tk(ps, i, "return")
node.exps = new_node(ps.tokens, i, "expression_list")
i = parse_list(ps, i, node.exps, stop_return_list, "sep", parse_expression)
if ps.tokens[i].kind == ";" then
i = i + 1
end
return i, node
end
local function store_field_in_record(name, def, nt)
if def.fields[name] then
return false
end
def.fields[name] = nt.newtype
table.insert(def.field_order, name)
return true
end
local ParseBody = {}
local function parse_nested_type(ps, i, def, typename, parse_body)
i = i + 1
local v
i, v = verify_kind(ps, i, "identifier", "variable")
if not v then
return fail(ps, i, "expected a variable name")
end
local nt = new_node(ps.tokens, i, "newtype")
nt.newtype = new_type(ps, i, "typetype")
local rdef = new_type(ps, i, typename)
local iok = parse_body(ps, i, rdef, nt)
if iok then
i = iok
nt.newtype.def = rdef
end
local ok = store_field_in_record(v.tk, def, nt)
if not ok then
fail(ps, i, "attempt to redeclare field '" .. v.tk .. "' (only functions can be overloaded)")
end
return i
end
local function parse_enum_body(ps, i, def, node)
def.enumset = {}
while not ((not ps.tokens[i]) or ps.tokens[i].tk == "end") do
local item
i, item = verify_kind(ps, i, "string", "enum_item")
if item then
table.insert(node, item)
def.enumset[unquote(item.tk)] = true
end
end
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
local function parse_record_body(ps, i, def, node)
def.fields = {}
def.field_order = {}
if ps.tokens[i].tk == "<" then
i, def.typeargs = parse_typearg_list(ps, i)
end
while not ((not ps.tokens[i]) or ps.tokens[i].tk == "end") do
if ps.tokens[i].tk == "{" then
if def.typename == "arrayrecord" then
return fail(ps, i, "duplicated declaration of array element type in record")
end
i = i + 1
local t
i, t = parse_type(ps, i)
if ps.tokens[i].tk == "}" then
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "}")
else
return fail(ps, i, "expected an array declaration")
end
def.typename = "arrayrecord"
def.elements = t
elseif ps.tokens[i].tk == "type" and ps.tokens[i + 1].tk ~= ":" then
i = i + 1
local v
i, v = verify_kind(ps, i, "identifier", "variable")
if not v then
return fail(ps, i, "expected a variable name")
end
i = verify_tk(ps, i, "=")
local nt
i, nt = parse_newtype(ps, i)
if not nt or not nt.newtype then
return fail(ps, i, "expected a type definition")
end
local ok = store_field_in_record(v.tk, def, nt)
if not ok then
return fail(ps, i, "attempt to redeclare field '" .. v.tk .. "' (only functions can be overloaded)")
end
elseif ps.tokens[i].tk == "record" and ps.tokens[i + 1].tk ~= ":" then
i = parse_nested_type(ps, i, def, "record", parse_record_body)
elseif ps.tokens[i].tk == "enum" and ps.tokens[i + 1].tk ~= ":" then
i = parse_nested_type(ps, i, def, "enum", parse_enum_body)
else
local v
i, v = verify_kind(ps, i, "identifier", "variable")
local iv = i
if not v then
return fail(ps, i, "expected a variable name")
end
if ps.tokens[i].tk == ":" then
i = verify_tk(ps, i, ":")
local t
i, t = parse_type(ps, i)
if not t then
return fail(ps, i, "expected a type")
end
if not def.fields[v.tk] then
def.fields[v.tk] = t
table.insert(def.field_order, v.tk)
else
local prev_t = def.fields[v.tk]
if t.typename == "function" and prev_t.typename == "function" then
def.fields[v.tk] = new_type(ps, iv, "poly")
def.fields[v.tk].types = { prev_t, t }
elseif t.typename == "function" and prev_t.typename == "poly" then
table.insert(prev_t.types, t)
else
return fail(ps, i, "attempt to redeclare field '" .. v.tk .. "' (only functions can be overloaded)")
end
end
elseif ps.tokens[i].tk == "=" then
local next_word = ps.tokens[i + 1].tk
if next_word == "record" or next_word == "enum" then
return fail(ps, i, "syntax error: this syntax is no longer valid; use '" .. next_word .. " " .. v.tk .. "'")
elseif next_word == "functiontype" then
return fail(ps, i, "syntax error: this syntax is no longer valid; use 'type " .. v.tk .. " = function('...")
else
return fail(ps, i, "syntax error: this syntax is no longer valid; use 'type " .. v.tk .. " = '...")
end
end
end
end
node.yend = ps.tokens[i].y
i = verify_tk(ps, i, "end")
return i, node
end
parse_newtype = function(ps, i)
local node = new_node(ps.tokens, i, "newtype")
node.newtype = new_type(ps, i, "typetype")
if ps.tokens[i].tk == "record" then
local def = new_type(ps, i, "record")
i = i + 1
i = parse_record_body(ps, i, def, node)
node.newtype.def = def
return i, node
elseif ps.tokens[i].tk == "enum" then
local def = new_type(ps, i, "enum")
i = i + 1
i = parse_enum_body(ps, i, def, node)
node.newtype.def = def
return i, node
else
i, node.newtype.def = parse_type(ps, i)
return i, node
end
return fail(ps, i)
end
local function parse_call_or_assignment(ps, i)
local asgn = new_node(ps.tokens, i, "assignment")
local tryi = i
asgn.vars = new_node(ps.tokens, i, "variables")
i = parse_trying_list(ps, i, asgn.vars, parse_expression)
if #asgn.vars < 1 then
return fail(ps, i)
end
local lhs = asgn.vars[1]
if ps.tokens[i].tk == "=" then
asgn.exps = new_node(ps.tokens, i, "values")
repeat
i = i + 1
local val
i, val = parse_expression(ps, i)
table.insert(asgn.exps, val)
until ps.tokens[i].tk ~= ","
return i, asgn
end
if #asgn.vars > 1 then
local err_ps = {
tokens = ps.tokens,
errs = {},
}
local expi = parse_expression(err_ps, tryi)
return fail(ps, expi or i)
end
if lhs.op and lhs.op.op == "@funcall" and #asgn.vars == 1 then
return i, lhs
end
return fail(ps, i)
end
local function parse_variable_declarations(ps, i, node_name)
local asgn = new_node(ps.tokens, i, node_name)
asgn.vars = new_node(ps.tokens, i, "variables")
i = parse_trying_list(ps, i, asgn.vars, parse_variable_name)
if #asgn.vars == 0 then
return fail(ps, i, "expected a local variable definition")
end
local lhs = asgn.vars[1]
i, asgn.decltype = parse_type_list(ps, i, "decltype")
if ps.tokens[i].tk == "=" then
if ps.tokens[i + 1].tk == "record" or
ps.tokens[i + 1].tk == "enum" then
local scope = node_name == "local_declaration" and "local" or "global"
fail(ps, i, "syntax error: this syntax is no longer valid; use '" .. scope .. " " .. ps.tokens[i + 1].tk .. " " .. asgn.vars[1].tk .. "'")
elseif ps.tokens[i + 1].tk == "functiontype" then
local scope = node_name == "local_declaration" and "local" or "global"
fail(ps, i, "syntax error: this syntax is no longer valid; use '" .. scope .. " type " .. asgn.vars[1].tk .. " = function('...")
end
asgn.exps = new_node(ps.tokens, i, "values")
local v = 1
repeat
i = i + 1
local val
i, val = parse_expression(ps, i)
table.insert(asgn.exps, val)
v = v + 1
until ps.tokens[i].tk ~= ","
end
return i, asgn
end
local function parse_type_declaration(ps, i, node_name)
i = i + 2
local asgn = new_node(ps.tokens, i, node_name)
i, asgn.var = parse_variable_name(ps, i)
if not asgn.var then
return fail(ps, i, "expected a type name")
end
i = verify_tk(ps, i, "=")
i, asgn.value = parse_newtype(ps, i)
if asgn.value then
asgn.value.newtype.def.names = { asgn.var.tk }
else
return i
end
return i, asgn
end
local ParseBody = {}
local function parse_type_constructor(ps, i, node_name, type_name, parse_body)
local asgn = new_node(ps.tokens, i, node_name)
local nt = new_node(ps.tokens, i, "newtype")
asgn.value = nt
nt.newtype = new_type(ps, i, "typetype")
local def = new_type(ps, i, type_name)
nt.newtype.def = def
i = i + 2
i, asgn.var = verify_kind(ps, i, "identifier")
if not asgn.var then
return fail(ps, i, "expected a type name")
end
nt.newtype.def.names = { asgn.var.tk }
i = parse_body(ps, i, def, nt)
return i, asgn
end
local function parse_statement(ps, i)
if ps.tokens[i].tk == "local" then
if ps.tokens[i + 1].tk == "type" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_declaration(ps, i, "local_type")
elseif ps.tokens[i + 1].tk == "function" then
return parse_local_function(ps, i)
elseif ps.tokens[i + 1].tk == "record" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_constructor(ps, i, "local_type", "record", parse_record_body)
elseif ps.tokens[i + 1].tk == "enum" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_constructor(ps, i, "local_type", "enum", parse_enum_body)
else
i = i + 1
return parse_variable_declarations(ps, i, "local_declaration")
end
elseif ps.tokens[i].tk == "global" then
if ps.tokens[i + 1].tk == "type" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_declaration(ps, i, "global_type")
elseif ps.tokens[i + 1].tk == "record" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_constructor(ps, i, "global_type", "record", parse_record_body)
elseif ps.tokens[i + 1].tk == "enum" and ps.tokens[i + 2].kind == "identifier" then
return parse_type_constructor(ps, i, "global_type", "enum", parse_enum_body)
elseif ps.tokens[i + 1].tk == "function" then
i = i + 1
return parse_function(ps, i)
else
i = i + 1
return parse_variable_declarations(ps, i, "global_declaration")
end
elseif ps.tokens[i].tk == "function" then
return parse_function(ps, i)
elseif ps.tokens[i].tk == "if" then
return parse_if(ps, i)
elseif ps.tokens[i].tk == "while" then
return parse_while(ps, i)
elseif ps.tokens[i].tk == "repeat" then
return parse_repeat(ps, i)
elseif ps.tokens[i].tk == "for" then
return parse_for(ps, i)
elseif ps.tokens[i].tk == "do" then
return parse_do(ps, i)
elseif ps.tokens[i].tk == "break" then
return parse_break(ps, i)
elseif ps.tokens[i].tk == "return" then
return parse_return(ps, i)
elseif ps.tokens[i].tk == "goto" then
return parse_goto(ps, i)
elseif ps.tokens[i].tk == "::" then
return parse_label(ps, i)
else
return parse_call_or_assignment(ps, i)
end
end
parse_statements = function(ps, i, filename, toplevel)
local node = new_node(ps.tokens, i, "statements")
while true do
while ps.tokens[i].kind == ";" do
i = i + 1
end
if ps.tokens[i].kind == "$EOF$" then
break
end
if (not toplevel) and stop_statement_list[ps.tokens[i].tk] then
break
end
local item
i, item = parse_statement(ps, i)
if filename then
for j = 1, #ps.errs do
if not ps.errs[j].filename then
ps.errs[j].filename = filename
end
end
end
if not item then
break
end
table.insert(node, item)
end
return i, node
end
function tl.parse_program(tokens, errs, filename)
errs = errs or {}
local ps = {
tokens = tokens,
errs = errs,
filename = filename,
}
local last = ps.tokens[#ps.tokens] or { y = 1, x = 1, tk = "" }
table.insert(ps.tokens, { y = last.y, x = last.x + #last.tk, tk = "$EOF$", kind = "$EOF$" })
return parse_statements(ps, 1, filename, true)
end
local VisitorCallbacks = {}
local Visitor = {}
local function visit_before(ast, kind, visit)
assert(visit.cbs[kind], "no visitor for " .. (kind))
if visit.cbs[kind].before then
visit.cbs[kind].before(ast)
end
end
local function visit_after(ast, kind, visit, xs)
if visit.after and visit.after.before then
visit.after.before(ast, xs)
end
local ret
if visit.cbs[kind].after then
ret = visit.cbs[kind].after(ast, xs)
end
if visit.after and visit.after.after then
ret = visit.after.after(ast, xs, ret)
end
return ret
end
local function recurse_type(ast, visit)
visit_before(ast, ast.typename, visit)
local xs = {}
if ast.typeargs then
for _, child in ipairs(ast.typeargs) do
table.insert(xs, recurse_type(child, visit))
end
end
for i, child in ipairs(ast) do
xs[i] = recurse_type(child, visit)
end
if ast.types then
for i, child in ipairs(ast.types) do
table.insert(xs, recurse_type(child, visit))
end
end
if ast.def then
table.insert(xs, recurse_type(ast.def, visit))
end
if ast.keys then
table.insert(xs, recurse_type(ast.keys, visit))
end
if ast.values then
table.insert(xs, recurse_type(ast.values, visit))
end
if ast.elements then
table.insert(xs, recurse_type(ast.elements, visit))
end
if ast.fields then
for _, child in pairs(ast.fields) do
table.insert(xs, recurse_type(child, visit))
end
end
if ast.args then
for i, child in ipairs(ast.args) do
if i > 1 or not ast.is_method then
table.insert(xs, recurse_type(child, visit))
end
end
end
if ast.rets then
for _, child in ipairs(ast.rets) do
table.insert(xs, recurse_type(child, visit))
end
end
if ast.typevals then
for _, child in ipairs(ast.typevals) do
table.insert(xs, recurse_type(child, visit))
end
end
if ast.ktype then
table.insert(xs, recurse_type(ast.ktype, visit))
end
if ast.vtype then
table.insert(xs, recurse_type(ast.vtype, visit))
end
return visit_after(ast, ast.typename, visit, xs)
end
local function recurse_node(ast,
visit_node,
visit_type)
if not ast then
return
end
visit_before(ast, ast.kind, visit_node)
local xs = {}
local cbs = visit_node.cbs[ast.kind]
if ast.kind == "statements" or
ast.kind == "variables" or
ast.kind == "values" or
ast.kind == "argument_list" or
ast.kind == "expression_list" or
ast.kind == "table_literal" then
for i, child in ipairs(ast) do
xs[i] = recurse_node(child, visit_node, visit_type)
end
elseif ast.kind == "local_declaration" or
ast.kind == "global_declaration" or
ast.kind == "assignment" then
xs[1] = recurse_node(ast.vars, visit_node, visit_type)
if ast.exps then
xs[2] = recurse_node(ast.exps, visit_node, visit_type)
end
if ast.decltype then
xs[3] = recurse_type(ast.decltype, visit_type)
end
elseif ast.kind == "local_type" or
ast.kind == "global_type" then
xs[1] = recurse_node(ast.var, visit_node, visit_type)
xs[2] = recurse_node(ast.value, visit_node, visit_type)
elseif ast.kind == "table_item" then
xs[1] = recurse_node(ast.key, visit_node, visit_type)
xs[2] = recurse_node(ast.value, visit_node, visit_type)
elseif ast.kind == "if" then
xs[1] = recurse_node(ast.exp, visit_node, visit_type)
if cbs.before_statements then
cbs.before_statements(ast, xs)
end
xs[2] = recurse_node(ast.thenpart, visit_node, visit_type)
for i, e in ipairs(ast.elseifs) do
table.insert(xs, recurse_node(e, visit_node, visit_type))
end
if ast.elsepart then
table.insert(xs, recurse_node(ast.elsepart, visit_node, visit_type))
end
elseif ast.kind == "while" then
xs[1] = recurse_node(ast.exp, visit_node, visit_type)
if cbs.before_statements then
cbs.before_statements(ast, xs)
end
xs[2] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "repeat" then
xs[1] = recurse_node(ast.body, visit_node, visit_type)
xs[2] = recurse_node(ast.exp, visit_node, visit_type)
elseif ast.kind == "function" then
xs[1] = recurse_node(ast.args, visit_node, visit_type)
xs[2] = recurse_type(ast.rets, visit_type)
xs[3] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "forin" then
xs[1] = recurse_node(ast.vars, visit_node, visit_type)
xs[2] = recurse_node(ast.exps, visit_node, visit_type)
if cbs.before_statements then
cbs.before_statements(ast)
end
xs[3] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "fornum" then
xs[1] = recurse_node(ast.var, visit_node, visit_type)
xs[2] = recurse_node(ast.from, visit_node, visit_type)
xs[3] = recurse_node(ast.to, visit_node, visit_type)
xs[4] = ast.step and recurse_node(ast.step, visit_node, visit_type)
xs[5] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "elseif" then
xs[1] = recurse_node(ast.exp, visit_node, visit_type)
if cbs.before_statements then
cbs.before_statements(ast, xs)
end
xs[2] = recurse_node(ast.thenpart, visit_node, visit_type)
elseif ast.kind == "else" then
xs[1] = recurse_node(ast.elsepart, visit_node, visit_type)
elseif ast.kind == "return" then
xs[1] = recurse_node(ast.exps, visit_node, visit_type)
elseif ast.kind == "do" then
xs[1] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "cast" then
elseif ast.kind == "local_function" or
ast.kind == "global_function" then
xs[1] = recurse_node(ast.name, visit_node, visit_type)
xs[2] = recurse_node(ast.args, visit_node, visit_type)
xs[3] = recurse_type(ast.rets, visit_type)
xs[4] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "record_function" then
xs[1] = recurse_node(ast.fn_owner, visit_node, visit_type)
xs[2] = recurse_node(ast.name, visit_node, visit_type)
xs[3] = recurse_node(ast.args, visit_node, visit_type)
xs[4] = recurse_type(ast.rets, visit_type)
if cbs.before_statements then
cbs.before_statements(ast, xs)
end
xs[5] = recurse_node(ast.body, visit_node, visit_type)
elseif ast.kind == "paren" then
xs[1] = recurse_node(ast.e1, visit_node, visit_type)
elseif ast.kind == "op" then
xs[1] = recurse_node(ast.e1, visit_node, visit_type)
local p1 = ast.e1.op and ast.e1.op.prec or nil
if ast.op.op == ":" and ast.e1.kind == "string" then
p1 = -999
end
xs[2] = p1
if ast.op.arity == 2 then
if cbs.before_e2 then
cbs.before_e2(ast, xs)
end
if ast.op.op == "is" or ast.op.op == "as" then
xs[3] = recurse_type(ast.e2.casttype, visit_type)
else
xs[3] = recurse_node(ast.e2, visit_node, visit_type)
end
xs[4] = (ast.e2.op and ast.e2.op.prec)
end
elseif ast.kind == "newtype" then
xs[1] = recurse_type(ast.newtype, visit_type)
elseif ast.kind == "variable" or
ast.kind == "argument" or
ast.kind == "identifier" or
ast.kind == "string" or
ast.kind == "number" or
ast.kind == "break" or
ast.kind == "goto" or
ast.kind == "label" or
ast.kind == "nil" or
ast.kind == "..." or
ast.kind == "boolean" then
if ast.decltype then
xs[1] = recurse_type(ast.decltype, visit_type)
end
else
if not ast.kind then
error("wat: " .. inspect(ast))
end
error("unknown node kind " .. ast.kind)
end
return visit_after(ast, ast.kind, visit_node, xs)
end
local tight_op = {
[1] = {
["-"] = true,
["~"] = true,
["#"] = true,
},
[2] = {
["."] = true,
[":"] = true,
},
}
local spaced_op = {
[1] = {
["not"] = true,
},
[2] = {
["or"] = true,
["and"] = true,
["<"] = true,
[">"] = true,
["<="] = true,
[">="] = true,
["~="] = true,
["=="] = true,
["|"] = true,
["~"] = true,
["&"] = true,
["<<"] = true,
[">>"] = true,
[".."] = true,
["+"] = true,
["-"] = true,
["*"] = true,
["/"] = true,
["//"] = true,
["%"] = true,
["^"] = true,
},
}
local PrettyPrintOpts = {}
local default_pretty_print_ast_opts = {
preserve_indent = true,
preserve_newlines = true,
}
local fast_pretty_print_ast_opts = {
preserve_indent = false,
preserve_newlines = true,
}
function tl.pretty_print_ast(ast, mode)
local indent = 0
local opts
if type(mode) == "table" then
opts = mode
elseif mode == true then
opts = fast_pretty_print_ast_opts
else
opts = default_pretty_print_ast_opts
end
local Output = {}
local function increment_indent()
indent = indent + 1
end
if not opts.preserve_indent then
increment_indent = nil
end
local function add(out, s)
table.insert(out, s)
end
local function add_string(out, s)
table.insert(out, s)
if string.find(s, "\n", 1, true) then
for nl in s:gmatch("\n") do
out.h = out.h + 1
end
end
end
local function add_child(out, child, space, indent)
if #child == 0 then
return
end
if child.y < out.y then
out.y = child.y
end
if child.y > out.y + out.h and opts.preserve_newlines then
local delta = child.y - (out.y + out.h)
out.h = out.h + delta
table.insert(out, ("\n"):rep(delta))
else
if space then
table.insert(out, space)
indent = nil
end
end
if indent and opts.preserve_indent then
table.insert(out, (" "):rep(indent))
end
table.insert(out, child)
out.h = out.h + child.h
end
local function concat_output(out)
for i, s in ipairs(out) do
if type(s) == "table" then
out[i] = concat_output(s)
end
end
return table.concat(out)
end
local function print_record_def(typ)
local out = { "{" }
for name, field in pairs(typ.fields) do
if field.typename == "typetype" and is_record_type(field.def) then
table.insert(out, name)
table.insert(out, " = ")
table.insert(out, print_record_def(field.def))
table.insert(out, ", ")
end
end
table.insert(out, "}")
return table.concat(out)
end
local visit_node = {}
visit_node.cbs = {
["statements"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
local space
for i, child in ipairs(children) do
add_child(out, children[i], space, indent)
space = "; "
end
return out
end,
},
["local_declaration"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "local")
add_child(out, children[1], " ")
if children[2] then
table.insert(out, " =")
add_child(out, children[2], " ")
end
return out
end,
},
["local_type"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "local")
add_child(out, children[1], " ")
table.insert(out, " =")
add_child(out, children[2], " ")
return out
end,
},
["global_type"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
add_child(out, children[1], " ")
table.insert(out, " =")
add_child(out, children[2], " ")
return out
end,
},
["global_declaration"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
if children[2] then
add_child(out, children[1])
table.insert(out, " =")
add_child(out, children[2], " ")
end
return out
end,
},
["assignment"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
add_child(out, children[1])
table.insert(out, " =")
add_child(out, children[2], " ")
return out
end,
},
["if"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "if")
add_child(out, children[1], " ")
table.insert(out, " then")
add_child(out, children[2], " ")
indent = indent - 1
for i = 3, #children do
add_child(out, children[i], " ", indent)
end
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["while"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "while")
add_child(out, children[1], " ")
table.insert(out, " do")
add_child(out, children[2], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["repeat"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "repeat")
add_child(out, children[1], " ")
if opts.preserve_indent then
indent = indent - 1
end
add_child(out, { y = node.yend, h = 0, [1] = "until " }, " ", indent)
add_child(out, children[2])
return out
end,
},
["do"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "do")
add_child(out, children[1], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["forin"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "for")
add_child(out, children[1], " ")
table.insert(out, " in")
add_child(out, children[2], " ")
table.insert(out, " do")
add_child(out, children[3], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["fornum"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "for")
add_child(out, children[1], " ")
table.insert(out, " =")
add_child(out, children[2], " ")
table.insert(out, ",")
add_child(out, children[3], " ")
if children[4] then
table.insert(out, ",")
add_child(out, children[4], " ")
end
table.insert(out, " do")
add_child(out, children[5], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["return"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "return")
if #children[1] > 0 then
add_child(out, children[1], " ")
end
return out
end,
},
["break"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "break")
return out
end,
},
["elseif"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "elseif")
add_child(out, children[1], " ")
table.insert(out, " then")
add_child(out, children[2], " ")
return out
end,
},
["else"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "else")
add_child(out, children[1], " ")
return out
end,
},
["variables"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
local space
for i, child in ipairs(children) do
if i > 1 then
table.insert(out, ",")
space = " "
end
add_child(out, child, space)
end
return out
end,
},
["table_literal"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
if #children == 0 then
indent = indent - 1
table.insert(out, "{}")
return out
end
table.insert(out, "{")
local n = #children
for i, child in ipairs(children) do
add_child(out, child, " ", child.y ~= node.y and indent)
if i < n or node.yend ~= node.y then
table.insert(out, ",")
end
end
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "}" }, " ", indent)
return out
end,
},
["table_item"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
if node.key_parsed ~= "implicit" then
if node.key_parsed == "short" then
children[1][1] = children[1][1]:sub(2, -2)
add_child(out, children[1])
table.insert(out, " = ")
else
table.insert(out, "[")
add_child(out, children[1])
table.insert(out, "] = ")
end
end
add_child(out, children[2])
return out
end,
},
["local_function"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "local function")
add_child(out, children[1], " ")
table.insert(out, "(")
add_child(out, children[2])
table.insert(out, ")")
add_child(out, children[4], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["global_function"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "function")
add_child(out, children[1], " ")
table.insert(out, "(")
add_child(out, children[2])
table.insert(out, ")")
add_child(out, children[4], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["record_function"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "function")
add_child(out, children[1], " ")
table.insert(out, node.is_method and ":" or ".")
add_child(out, children[2])
table.insert(out, "(")
if node.is_method then
table.remove(children[3], 1)
if children[3][1] == "," then
table.remove(children[3], 1)
table.remove(children[3], 1)
end
end
add_child(out, children[3])
table.insert(out, ")")
add_child(out, children[5], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["function"] = {
before = increment_indent,
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "function(")
add_child(out, children[1])
table.insert(out, ")")
add_child(out, children[3], " ")
indent = indent - 1
add_child(out, { y = node.yend, h = 0, [1] = "end" }, " ", indent)
return out
end,
},
["cast"] = {},
["paren"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "(")
add_child(out, children[1], "", indent)
table.insert(out, ")")
return out
end,
},
["op"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
if node.op.op == "@funcall" then
add_child(out, children[1], "", indent)
table.insert(out, "(")
add_child(out, children[3], "", indent)
table.insert(out, ")")
elseif node.op.op == "@index" then
add_child(out, children[1], "", indent)
table.insert(out, "[")
add_child(out, children[3], "", indent)
table.insert(out, "]")
elseif node.op.op == "as" then
add_child(out, children[1], "", indent)
elseif node.op.op == "is" then
table.insert(out, "type(")
add_child(out, children[1], "", indent)
table.insert(out, ") == \"")
add_child(out, children[3], "", indent)
table.insert(out, "\"")
elseif spaced_op[node.op.arity][node.op.op] or tight_op[node.op.arity][node.op.op] then
local space = spaced_op[node.op.arity][node.op.op] and " " or ""
if children[2] and node.op.prec > tonumber(children[2]) then
table.insert(children[1], 1, "(")
table.insert(children[1], ")")
end
if node.op.arity == 1 then
table.insert(out, node.op.op)
add_child(out, children[1], space, indent)
elseif node.op.arity == 2 then
add_child(out, children[1], "", indent)
if space == " " then
table.insert(out, " ")
end
table.insert(out, node.op.op)
if children[4] and node.op.prec > tonumber(children[4]) then
table.insert(children[3], 1, "(")
table.insert(children[3], ")")
end
add_child(out, children[3], space, indent)
end
else
error("unknown node op " .. node.op.op)
end
return out
end,
},
["variable"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
add_string(out, node.tk)
return out
end,
},
["newtype"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
if is_record_type(node.newtype.def) then
table.insert(out, print_record_def(node.newtype.def))
else
table.insert(out, "{}")
end
return out
end,
},
["goto"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "goto ")
table.insert(out, node.label)
return out
end,
},
["label"] = {
after = function(node, children)
local out = { y = node.y, h = 0 }
table.insert(out, "::")
table.insert(out, node.label)
table.insert(out, "::")
return out
end,
},
}
local primitive = {
["function"] = "function",
["enum"] = "string",
["boolean"] = "boolean",
["string"] = "string",
["nil"] = "nil",
["number"] = "number",
["thread"] = "thread",
}
local visit_type = {}
visit_type.cbs = {
["string"] = {
after = function(typ, children)
local out = { y = typ.y, h = 0 }
table.insert(out, primitive[typ.typename] or "table")
return out
end,
},
}
visit_type.cbs["typetype"] = visit_type.cbs["string"]
visit_type.cbs["typevar"] = visit_type.cbs["string"]
visit_type.cbs["typearg"] = visit_type.cbs["string"]
visit_type.cbs["function"] = visit_type.cbs["string"]
visit_type.cbs["thread"] = visit_type.cbs["string"]
visit_type.cbs["array"] = visit_type.cbs["string"]
visit_type.cbs["map"] = visit_type.cbs["string"]
visit_type.cbs["arrayrecord"] = visit_type.cbs["string"]
visit_type.cbs["record"] = visit_type.cbs["string"]
visit_type.cbs["enum"] = visit_type.cbs["string"]
visit_type.cbs["boolean"] = visit_type.cbs["string"]
visit_type.cbs["nil"] = visit_type.cbs["string"]
visit_type.cbs["number"] = visit_type.cbs["string"]
visit_type.cbs["union"] = visit_type.cbs["string"]
visit_type.cbs["nominal"] = visit_type.cbs["string"]
visit_type.cbs["bad_nominal"] = visit_type.cbs["string"]
visit_type.cbs["emptytable"] = visit_type.cbs["string"]
visit_type.cbs["table_item"] = visit_type.cbs["string"]
visit_type.cbs["unknown_emptytable_value"] = visit_type.cbs["string"]
visit_type.cbs["tuple"] = visit_type.cbs["string"]
visit_type.cbs["poly"] = visit_type.cbs["string"]
visit_type.cbs["any"] = visit_type.cbs["string"]
visit_type.cbs["unknown"] = visit_type.cbs["string"]
visit_type.cbs["invalid"] = visit_type.cbs["string"]
visit_type.cbs["unresolved"] = visit_type.cbs["string"]
visit_type.cbs["none"] = visit_type.cbs["string"]
visit_node.cbs["values"] = visit_node.cbs["variables"]
visit_node.cbs["expression_list"] = visit_node.cbs["variables"]
visit_node.cbs["argument_list"] = visit_node.cbs["variables"]
visit_node.cbs["identifier"] = visit_node.cbs["variable"]
visit_node.cbs["string"] = visit_node.cbs["variable"]
visit_node.cbs["number"] = visit_node.cbs["variable"]
visit_node.cbs["nil"] = visit_node.cbs["variable"]
visit_node.cbs["boolean"] = visit_node.cbs["variable"]
visit_node.cbs["..."] = visit_node.cbs["variable"]
visit_node.cbs["argument"] = visit_node.cbs["variable"]
local out = recurse_node(ast, visit_node, visit_type)
local code
if opts.preserve_newlines then
code = { y = 1, h = 0 }
add_child(code, out)
else
code = out
end
return concat_output(code)
end
local ANY = a_type({ typename = "any" })
local NONE = a_type({ typename = "none" })
local NIL = a_type({ typename = "nil" })
local NUMBER = a_type({ typename = "number" })
local STRING = a_type({ typename = "string" })
local OPT_NUMBER = a_type({ typename = "number" })
local OPT_STRING = a_type({ typename = "string" })
local VARARG_ANY = a_type({ typename = "any", is_va = true })
local VARARG_STRING = a_type({ typename = "string", is_va = true })
local VARARG_NUMBER = a_type({ typename = "number", is_va = true })
local VARARG_UNKNOWN = a_type({ typename = "unknown", is_va = true })
local VARARG_ALPHA = a_type({ typename = "typevar", typevar = "@a", is_va = true })
local BOOLEAN = a_type({ typename = "boolean" })
local ARG_ALPHA = a_type({ typename = "typearg", typearg = "@a" })
local ARG_BETA = a_type({ typename = "typearg", typearg = "@b" })
local ALPHA = a_type({ typename = "typevar", typevar = "@a" })
local BETA = a_type({ typename = "typevar", typevar = "@b" })
local ARRAY_OF_STRING = a_type({ typename = "array", elements = STRING })
local ARRAY_OF_ALPHA = a_type({ typename = "array", elements = ALPHA })
local MAP_OF_ALPHA_TO_BETA = a_type({ typename = "map", keys = ALPHA, values = BETA })
local TABLE = a_type({ typename = "map", keys = ANY, values = ANY })
local FUNCTION = a_type({ typename = "function", args = { a_type({ typename = "any", is_va = true }) }, rets = { a_type({ typename = "any", is_va = true }) } })
local THREAD = a_type({ typename = "thread" })
local INVALID = a_type({ typename = "invalid" })
local UNKNOWN = a_type({ typename = "unknown" })
local NOMINAL_FILE = a_type({ typename = "nominal", names = { "FILE" } })
local NOMINAL_METATABLE = a_type({ typename = "nominal", names = { "METATABLE" } })
local OS_DATE_TABLE = a_type({
typename = "record",
fields = {
["year"] = NUMBER,
["month"] = NUMBER,
["day"] = NUMBER,
["hour"] = NUMBER,
["min"] = NUMBER,
["sec"] = NUMBER,
["wday"] = NUMBER,
["yday"] = NUMBER,
["isdst"] = BOOLEAN,
},
})
local DEBUG_GETINFO_TABLE = a_type({
typename = "record",
fields = {
["name"] = STRING,
["namewhat"] = STRING,
["source"] = STRING,
["short_src"] = STRING,
["linedefined"] = NUMBER,
["lastlinedefined"] = NUMBER,
["what"] = STRING,
["currentline"] = NUMBER,
["istailcall"] = BOOLEAN,
["nups"] = NUMBER,
["nparams"] = NUMBER,
["isvararg"] = BOOLEAN,
["func"] = ANY,
["activelines"] = a_type({ typename = "map", keys = NUMBER, values = BOOLEAN }),
},
})
local numeric_binop = {
["number"] = {
["number"] = NUMBER,
},
}
local relational_binop = {
["number"] = {
["number"] = BOOLEAN,
},
["string"] = {
["string"] = BOOLEAN,
},
["boolean"] = {
["boolean"] = BOOLEAN,
},
}
local equality_binop = {
["number"] = {
["number"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["string"] = {
["string"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["boolean"] = {
["boolean"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["record"] = {
["emptytable"] = BOOLEAN,
["arrayrecord"] = BOOLEAN,
["record"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["array"] = {
["emptytable"] = BOOLEAN,
["arrayrecord"] = BOOLEAN,
["array"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["arrayrecord"] = {
["emptytable"] = BOOLEAN,
["arrayrecord"] = BOOLEAN,
["record"] = BOOLEAN,
["array"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["map"] = {
["emptytable"] = BOOLEAN,
["map"] = BOOLEAN,
["nil"] = BOOLEAN,
},
["thread"] = {
["thread"] = BOOLEAN,
["nil"] = BOOLEAN,
},
}
local unop_types = {
["#"] = {
["arrayrecord"] = NUMBER,
["string"] = NUMBER,
["array"] = NUMBER,
["map"] = NUMBER,
["emptytable"] = NUMBER,
},
["-"] = {
["number"] = NUMBER,
},
["not"] = {
["string"] = BOOLEAN,
["number"] = BOOLEAN,
["boolean"] = BOOLEAN,
["record"] = BOOLEAN,
["arrayrecord"] = BOOLEAN,
["array"] = BOOLEAN,
["map"] = BOOLEAN,
["emptytable"] = BOOLEAN,
["thread"] = BOOLEAN,
},
}
local binop_types = {
["+"] = numeric_binop,
["-"] = {
["number"] = {
["number"] = NUMBER,
},
},
["*"] = numeric_binop,
["%"] = numeric_binop,
["/"] = numeric_binop,
["^"] = numeric_binop,
["&"] = numeric_binop,
["|"] = numeric_binop,
["<<"] = numeric_binop,
[">>"] = numeric_binop,
["=="] = equality_binop,
["~="] = equality_binop,
["<="] = relational_binop,
[">="] = relational_binop,
["<"] = relational_binop,
[">"] = relational_binop,
["or"] = {
["boolean"] = {
["boolean"] = BOOLEAN,
["function"] = FUNCTION,
},
["number"] = {
["number"] = NUMBER,
["boolean"] = BOOLEAN,
},
["string"] = {
["string"] = STRING,
["boolean"] = BOOLEAN,
["enum"] = STRING,
},
["function"] = {
["function"] = FUNCTION,
["boolean"] = BOOLEAN,
},
["array"] = {
["boolean"] = BOOLEAN,
},
["record"] = {
["boolean"] = BOOLEAN,
},
["arrayrecord"] = {
["boolean"] = BOOLEAN,
},
["map"] = {
["boolean"] = BOOLEAN,
},
["enum"] = {
["string"] = STRING,
},
["thread"] = {
["boolean"] = BOOLEAN,
},
},
[".."] = {
["string"] = {
["string"] = STRING,
["enum"] = STRING,
["number"] = STRING,
},
["number"] = {
["number"] = STRING,
["string"] = STRING,
["enum"] = STRING,
},
["enum"] = {
["number"] = STRING,
["string"] = STRING,
["enum"] = STRING,
},
},
}
local show_type
local function is_unknown(t)
return t.typename == "unknown" or
t.typename == "unknown_emptytable_value"
end
local show_type
local function show_type_base(t, seen)
if seen[t] then
return "..."
end
seen[t] = true
local function show(t)
return show_type(t, seen)
end
if t.typename == "nominal" then
if t.typevals then
local out = { table.concat(t.names, "."), "<" }
local vals = {}
for _, v in ipairs(t.typevals) do
table.insert(vals, show(v))
end
table.insert(out, table.concat(vals, ", "))
table.insert(out, ">")
return table.concat(out)
else
return table.concat(t.names, ".")
end
elseif t.typename == "tuple" then
local out = {}
for _, v in ipairs(t) do
table.insert(out, show(v))
end
return "(" .. table.concat(out, ", ") .. ")"
elseif t.typename == "poly" then
local out = {}
for _, v in ipairs(t.types) do
table.insert(out, show(v))
end
return table.concat(out, " or ")
elseif t.typename == "union" then
local out = {}
for _, v in ipairs(t.types) do
table.insert(out, show(v))
end
return table.concat(out, " | ")
elseif t.typename == "emptytable" then
return "{}"
elseif t.typename == "map" then
return "{" .. show(t.keys) .. " : " .. show(t.values) .. "}"
elseif t.typename == "array" then
return "{" .. show(t.elements) .. "}"
elseif t.typename == "enum" then
return t.names and table.concat(t.names, ".") or "enum"
elseif is_record_type(t) then
local out = {}
for _, k in ipairs(t.field_order) do
local v = t.fields[k]
table.insert(out, k .. ": " .. show(v))
end
return "{" .. table.concat(out, ", ") .. "}"
elseif t.typename == "function" then
local out = {}
table.insert(out, "function(")
local args = {}
if t.is_method then
table.insert(args, "self")
end
for i, v in ipairs(t.args) do
if not t.is_method or i > 1 then
table.insert(args, show(v))
end
end
table.insert(out, table.concat(args, ","))
table.insert(out, ")")
if #t.rets > 0 then
table.insert(out, ":")
local rets = {}
for _, v in ipairs(t.rets) do
table.insert(rets, show(v))
end
table.insert(out, table.concat(rets, ","))
end
return table.concat(out)
elseif t.typename == "number" or
t.typename == "boolean" or
t.typename == "thread" then
return t.typename
elseif t.typename == "string" then
return t.typename ..
(t.tk and " " .. t.tk or "")
elseif t.typename == "typevar" then
return t.typevar
elseif t.typename == "typearg" then
return t.typearg
elseif is_unknown(t) then
return "<unknown type>"
elseif t.typename == "invalid" then
return "<invalid type>"
elseif t.typename == "any" then
return "<any type>"
elseif t.typename == "nil" then
return "nil"
elseif t.typename == "typetype" then
return "type " .. show(t.def)
elseif t.typename == "bad_nominal" then
return table.concat(t.names, ".") .. " (an unknown type)"
else
return inspect(t)
end
end
show_type = function(t, seen)
local ret = show_type_base(t, seen or {})
if t.inferred_at then
ret = ret .. " (inferred at " .. t.inferred_at_file .. ":" .. t.inferred_at.y .. ":" .. t.inferred_at.x .. ": )"
end
return ret
end
local Error = {}
local Result = {}
local function search_for(module_name, suffix, path, tried)
for entry in path:gmatch("[^;]+") do
local slash_name = module_name:gsub("%.", "/")
local filename = entry:gsub("?", slash_name)
local tl_filename = filename:gsub("%.lua$", suffix)
local fd = io.open(tl_filename, "r")
if fd then
return tl_filename, fd, tried
end
table.insert(tried, "no file '" .. tl_filename .. "'")
end
return nil, nil, tried
end
function tl.search_module(module_name, search_dtl)
local found
local tried = {}
local path = os.getenv("TL_PATH") or package.path
if search_dtl then
local found, fd, tried = search_for(module_name, ".d.tl", path, tried)
if found then
return found, fd
end
end
local found, fd, tried = search_for(module_name, ".tl", path, tried)
if found then
return found, fd
end
local found, fd, tried = search_for(module_name, ".lua", path, tried)
if found then
return found, fd
end
return nil, nil, tried
end
local Variable = {}
local function fill_field_order(t)
if t.typename == "record" then
t.field_order = {}
for k, v in pairs(t.fields) do
table.insert(t.field_order, k)
end
table.sort(t.field_order)
end
end
local function require_module(module_name, lax, env, result)
local modules = env.modules
if modules[module_name] then
return modules[module_name], true
end
modules[module_name] = UNKNOWN
local found, fd, tried = tl.search_module(module_name, true)
if found and (lax or found:match("tl$")) then
fd:close()
local _result, err = tl.process(found, env, result)
assert(_result, err)
if not _result.type then
_result.type = BOOLEAN
end
modules[module_name] = _result.type
return _result.type, true
end
return UNKNOWN, found ~= nil
end
local standard_library = {
["..."] = a_type({ typename = "tuple", STRING, STRING, STRING, STRING, STRING }),
["@return"] = a_type({ typename = "tuple", ANY }),
["any"] = a_type({ typename = "typetype", def = ANY }),
["arg"] = ARRAY_OF_STRING,
["assert"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ALPHA }, rets = { ALPHA } }),
a_type({ typename = "function", typeargs = { ARG_ALPHA, ARG_BETA }, args = { ALPHA, BETA }, rets = { ALPHA } }),
},
}),
["collectgarbage"] = a_type({ typename = "function", args = { STRING }, rets = { a_type({ typename = "union", types = { BOOLEAN, NUMBER } }), NUMBER, NUMBER } }),
["dofile"] = a_type({ typename = "function", args = { OPT_STRING }, rets = { VARARG_ANY } }),
["error"] = a_type({ typename = "function", args = { STRING, NUMBER }, rets = {} }),
["getmetatable"] = a_type({ typename = "function", args = { ANY }, rets = { NOMINAL_METATABLE } }),
["ipairs"] = a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA }, rets = {
a_type({ typename = "function", args = {}, rets = { NUMBER, ALPHA } }),
}, }),
["load"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { STRING }, rets = { FUNCTION, STRING } }),
a_type({ typename = "function", args = { STRING, STRING }, rets = { FUNCTION, STRING } }),
a_type({ typename = "function", args = { STRING, STRING, STRING }, rets = { FUNCTION, STRING } }),
a_type({ typename = "function", args = { STRING, STRING, STRING, TABLE }, rets = { FUNCTION, STRING } }),
},
}),
["loadfile"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = {}, rets = { FUNCTION, ANY } }),
a_type({ typename = "function", args = { STRING }, rets = { FUNCTION, ANY } }),
a_type({ typename = "function", args = { STRING, STRING }, rets = { FUNCTION, ANY } }),
a_type({ typename = "function", args = { STRING, STRING, TABLE }, rets = { FUNCTION, ANY } }),
},
}),
["next"] = a_type({
typename = "poly",
types = {
a_type({ typeargs = { ARG_ALPHA, ARG_BETA }, typename = "function", args = { MAP_OF_ALPHA_TO_BETA }, rets = { ALPHA, BETA } }),
a_type({ typeargs = { ARG_ALPHA, ARG_BETA }, typename = "function", args = { MAP_OF_ALPHA_TO_BETA, ALPHA }, rets = { ALPHA, BETA } }),
a_type({ typeargs = { ARG_ALPHA }, typename = "function", args = { ARRAY_OF_ALPHA }, rets = { NUMBER, ALPHA } }),
a_type({ typeargs = { ARG_ALPHA }, typename = "function", args = { ARRAY_OF_ALPHA, ALPHA }, rets = { NUMBER, ALPHA } }),
},
}),
["pairs"] = a_type({ typename = "function", typeargs = { ARG_ALPHA, ARG_BETA }, args = { a_type({ typename = "map", keys = ALPHA, values = BETA }) }, rets = {
a_type({ typename = "function", args = {}, rets = { ALPHA, BETA } }),
}, }),
["pcall"] = a_type({ typename = "function", args = { FUNCTION, VARARG_ANY }, rets = { BOOLEAN, ANY } }),
["xpcall"] = a_type({ typename = "function", args = { FUNCTION, FUNCTION, VARARG_ANY }, rets = { BOOLEAN, ANY } }),
["print"] = a_type({ typename = "function", args = { VARARG_ANY }, rets = {} }),
["rawequal"] = a_type({ typename = "function", args = { ANY, ANY }, rets = { BOOLEAN } }),
["rawget"] = a_type({ typename = "function", args = { TABLE, ANY }, rets = { ANY } }),
["rawlen"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { TABLE }, rets = { NUMBER } }),
a_type({ typename = "function", args = { STRING }, rets = { NUMBER } }),
},
}),
["rawset"] = a_type({
typename = "poly",
types = {
a_type({ typeargs = { ARG_ALPHA, ARG_BETA }, typename = "function", args = { MAP_OF_ALPHA_TO_BETA, ALPHA, BETA }, rets = {} }),
a_type({ typeargs = { ARG_ALPHA }, typename = "function", args = { ARRAY_OF_ALPHA, NUMBER, ALPHA }, rets = {} }),
a_type({ typename = "function", args = { TABLE, ANY, ANY }, rets = {} }),
},
}),
["require"] = a_type({ typename = "function", args = { STRING }, rets = {} }),
["select"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { NUMBER, VARARG_ALPHA }, rets = { ALPHA } }),
a_type({ typename = "function", args = { NUMBER, VARARG_ANY }, rets = { ANY } }),
a_type({ typename = "function", args = { STRING, VARARG_ANY }, rets = { NUMBER } }),
},
}),
["setmetatable"] = a_type({ typeargs = { ARG_ALPHA }, typename = "function", args = { ALPHA, NOMINAL_METATABLE }, rets = { ALPHA } }),
["tonumber"] = a_type({ typename = "function", args = { ANY, NUMBER }, rets = { NUMBER } }),
["tostring"] = a_type({ typename = "function", args = { ANY }, rets = { STRING } }),
["type"] = a_type({ typename = "function", args = { ANY }, rets = { STRING } }),
["FILE"] = a_type({
typename = "typetype",
def = a_type({
typename = "record",
fields = {
["close"] = a_type({ typename = "function", args = { NOMINAL_FILE }, rets = { BOOLEAN, STRING } }),
["flush"] = a_type({ typename = "function", args = { NOMINAL_FILE }, rets = {} }),
["lines"] = a_type({ typename = "function", args = { NOMINAL_FILE, a_type({ typename = "union", types = { STRING, NUMBER }, is_va = true }) }, rets = {
a_type({ typename = "function", args = {}, rets = { VARARG_STRING } }),
}, }),
["read"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { NOMINAL_FILE, STRING }, rets = { STRING, STRING } }),
a_type({ typename = "function", args = { NOMINAL_FILE, NUMBER }, rets = { STRING, STRING } }),
},
}),
["seek"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { NOMINAL_FILE }, rets = { NUMBER, STRING } }),
a_type({ typename = "function", args = { NOMINAL_FILE, STRING }, rets = { NUMBER, STRING } }),
a_type({ typename = "function", args = { NOMINAL_FILE, STRING, NUMBER }, rets = { NUMBER, STRING } }),
},
}),
["setvbuf"] = a_type({ typename = "function", args = { NOMINAL_FILE, STRING, OPT_NUMBER }, rets = {} }),
["write"] = a_type({ typename = "function", args = { NOMINAL_FILE, VARARG_STRING }, rets = { NOMINAL_FILE, STRING } }),
},
}),
}),
["METATABLE"] = a_type({
typename = "typetype",
def = a_type({
typename = "record",
fields = {
["__call"] = FUNCTION,
["__gc"] = a_type({ typename = "function", args = { ANY }, rets = {} }),
["__index"] = ANY,
["__len"] = a_type({ typename = "function", args = { ANY }, rets = { NUMBER } }),
["__mode"] = a_type({ typename = "enum", enumset = { ["k"] = true, ["v"] = true, ["kv"] = true } }),
["__newindex"] = ANY,
["__pairs"] = a_type({ typeargs = { ARG_ALPHA, ARG_BETA }, typename = "function", args = { a_type({ typename = "map", keys = ALPHA, values = BETA }) }, rets = {
a_type({ typename = "function", args = {}, rets = { ALPHA, BETA } }),
}, }),
["__tostring"] = a_type({ typename = "function", args = { ANY }, rets = { STRING } }),
["__name"] = STRING,
["__add"] = FUNCTION,
["__sub"] = FUNCTION,
["__mul"] = FUNCTION,
["__div"] = FUNCTION,
["__idiv"] = FUNCTION,
["__mod"] = FUNCTION,
["__pow"] = FUNCTION,
["__unm"] = FUNCTION,
["__band"] = FUNCTION,
["__bor"] = FUNCTION,
["__bxor"] = FUNCTION,
["__bnot"] = FUNCTION,
["__shl"] = FUNCTION,
["__shr"] = FUNCTION,
["__concat"] = FUNCTION,
["__eq"] = FUNCTION,
["__lt"] = FUNCTION,
["__le"] = FUNCTION,
},
}),
}),
["coroutine"] = a_type({
typename = "record",
fields = {
["create"] = a_type({ typename = "function", args = { FUNCTION }, rets = { THREAD } }),
["close"] = a_type({ typename = "function", args = { THREAD }, rets = { BOOLEAN, STRING } }),
["isyieldable"] = a_type({ typename = "function", args = {}, rets = { BOOLEAN } }),
["resume"] = a_type({ typename = "function", args = { THREAD, VARARG_ANY }, rets = { BOOLEAN, VARARG_ANY } }),
["running"] = a_type({ typename = "function", args = {}, rets = { THREAD, BOOLEAN } }),
["status"] = a_type({ typename = "function", args = { THREAD }, rets = { STRING } }),
["wrap"] = a_type({ typename = "function", args = { FUNCTION }, rets = { FUNCTION } }),
["yield"] = a_type({ typename = "function", args = { VARARG_ANY }, rets = { VARARG_ANY } }),
},
}),
["debug"] = a_type({
typename = "record",
fields = {
["traceback"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { THREAD, STRING, NUMBER }, rets = { STRING } }),
a_type({ typename = "function", args = { STRING, NUMBER }, rets = { STRING } }),
},
}),
["getinfo"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { ANY }, rets = { DEBUG_GETINFO_TABLE } }),
a_type({ typename = "function", args = { ANY, STRING }, rets = { DEBUG_GETINFO_TABLE } }),
a_type({ typename = "function", args = { ANY, ANY, STRING }, rets = { DEBUG_GETINFO_TABLE } }),
},
}),
},
}),
["io"] = a_type({
typename = "record",
fields = {
["close"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = {}, rets = { BOOLEAN, STRING } }),
a_type({ typename = "function", args = { NOMINAL_FILE }, rets = { BOOLEAN, STRING } }),
},
}),
["flush"] = a_type({ typename = "function", args = {}, rets = {} }),
["input"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = {}, rets = { NOMINAL_FILE } }),
a_type({ typename = "function", args = { STRING }, rets = { NOMINAL_FILE } }),
a_type({ typename = "function", args = { NOMINAL_FILE }, rets = { NOMINAL_FILE } }),
},
}),
["lines"] = a_type({ typename = "function", args = { OPT_STRING, a_type({ typename = "union", types = { STRING, NUMBER }, is_va = true }) }, rets = {
a_type({ typename = "function", args = {}, rets = { VARARG_STRING } }),
}, }),
["open"] = a_type({ typename = "function", args = { STRING, STRING }, rets = { NOMINAL_FILE, STRING } }),
["output"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = {}, rets = { NOMINAL_FILE } }),
a_type({ typename = "function", args = { STRING }, rets = { NOMINAL_FILE } }),
a_type({ typename = "function", args = { NOMINAL_FILE }, rets = { NOMINAL_FILE } }),
},
}),
["popen"] = a_type({ typename = "function", args = { STRING, STRING }, rets = { NOMINAL_FILE, STRING } }),
["read"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { NOMINAL_FILE, STRING }, rets = { STRING, STRING } }),
a_type({ typename = "function", args = { NOMINAL_FILE, NUMBER }, rets = { STRING, STRING } }),
},
}),
["stderr"] = NOMINAL_FILE,
["stdin"] = NOMINAL_FILE,
["stdout"] = NOMINAL_FILE,
["tmpfile"] = a_type({ typename = "function", args = {}, rets = { NOMINAL_FILE } }),
["type"] = a_type({ typename = "function", args = { ANY }, rets = { STRING } }),
["write"] = a_type({ typename = "function", args = { VARARG_STRING }, rets = { NOMINAL_FILE, STRING } }),
},
}),
["math"] = a_type({
typename = "record",
fields = {
["abs"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["acos"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["asin"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["atan"] = a_type({
typename = "poly",
a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
}),
["atan2"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["ceil"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["cos"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["cosh"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["deg"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["exp"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["floor"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["fmod"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["frexp"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER, NUMBER } }),
["huge"] = NUMBER,
["ldexp"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["log"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["log10"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["max"] = a_type({ typename = "function", args = { VARARG_NUMBER }, rets = { NUMBER } }),
["maxinteger"] = NUMBER,
["min"] = a_type({ typename = "function", args = { VARARG_NUMBER }, rets = { NUMBER } }),
["mininteger"] = NUMBER,
["modf"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER, NUMBER } }),
["pi"] = NUMBER,
["pow"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["rad"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["random"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["randomseed"] = a_type({ typename = "function", args = { NUMBER }, rets = {} }),
["sin"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["sinh"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["sqrt"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["tan"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["tanh"] = a_type({ typename = "function", args = { NUMBER }, rets = { NUMBER } }),
["tointeger"] = a_type({ typename = "function", args = { ANY }, rets = { NUMBER } }),
["type"] = a_type({ typename = "function", args = { ANY }, rets = { STRING } }),
["ult"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { BOOLEAN } }),
},
}),
["os"] = a_type({
typename = "record",
fields = {
["clock"] = a_type({ typename = "function", args = {}, rets = { NUMBER } }),
["date"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = {}, rets = { STRING } }),
a_type({ typename = "function", args = { STRING, OPT_STRING }, rets = { a_type({ typename = "union", types = { STRING, OS_DATE_TABLE } }) } }),
},
}),
["difftime"] = a_type({ typename = "function", args = { NUMBER, NUMBER }, rets = { NUMBER } }),
["execute"] = a_type({ typename = "function", args = { STRING }, rets = { BOOLEAN, STRING, NUMBER } }),
["exit"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { NUMBER, BOOLEAN }, rets = {} }),
a_type({ typename = "function", args = { BOOLEAN, BOOLEAN }, rets = {} }),
},
}),
["getenv"] = a_type({ typename = "function", args = { STRING }, rets = { STRING } }),
["remove"] = a_type({ typename = "function", args = { STRING }, rets = { BOOLEAN, STRING } }),
["rename"] = a_type({ typename = "function", args = { STRING, STRING }, rets = { BOOLEAN, STRING } }),
["setlocale"] = a_type({ typename = "function", args = { STRING, OPT_STRING }, rets = { STRING } }),
["time"] = a_type({ typename = "function", args = {}, rets = { NUMBER } }),
["tmpname"] = a_type({ typename = "function", args = {}, rets = { STRING } }),
},
}),
["package"] = a_type({
typename = "record",
fields = {
["config"] = STRING,
["cpath"] = STRING,
["loaded"] = a_type({
typename = "map",
keys = STRING,
values = ANY,
}),
["loaders"] = a_type({
typename = "array",
elements = a_type({ typename = "function", args = { STRING }, rets = { ANY } }),
}),
["loadlib"] = a_type({ typename = "function", args = { STRING, STRING }, rets = { FUNCTION } }),
["path"] = STRING,
["preload"] = TABLE,
["searchers"] = a_type({
typename = "array",
elements = a_type({ typename = "function", args = { STRING }, rets = { ANY } }),
}),
["searchpath"] = a_type({ typename = "function", args = { STRING, STRING, OPT_STRING, OPT_STRING }, rets = { STRING, STRING } }),
},
}),
["string"] = a_type({
typename = "record",
fields = {
["byte"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { STRING }, rets = { NUMBER } }),
a_type({ typename = "function", args = { STRING, NUMBER }, rets = { NUMBER } }),
a_type({ typename = "function", args = { STRING, NUMBER, NUMBER }, rets = { VARARG_NUMBER } }),
},
}),
["char"] = a_type({ typename = "function", args = { VARARG_NUMBER }, rets = { STRING } }),
["dump"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { FUNCTION }, rets = { STRING } }),
a_type({ typename = "function", args = { FUNCTION, BOOLEAN }, rets = { STRING } }),
},
}),
["find"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { STRING, STRING }, rets = { NUMBER, NUMBER, VARARG_STRING } }),
a_type({ typename = "function", args = { STRING, STRING, NUMBER }, rets = { NUMBER, NUMBER, VARARG_STRING } }),
a_type({ typename = "function", args = { STRING, STRING, NUMBER, BOOLEAN }, rets = { NUMBER, NUMBER, VARARG_STRING } }),
},
}),
["format"] = a_type({ typename = "function", args = { STRING, VARARG_ANY }, rets = { STRING } }),
["gmatch"] = a_type({ typename = "function", args = { STRING, STRING }, rets = {
a_type({ typename = "function", args = {}, rets = { STRING } }),
}, }),
["gsub"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", args = { STRING, STRING, STRING, NUMBER }, rets = { STRING, NUMBER } }),
a_type({ typename = "function", args = { STRING, STRING, a_type({ typename = "map", keys = STRING, values = STRING }), NUMBER }, rets = { STRING, NUMBER } }),
a_type({ typename = "function", args = { STRING, STRING, a_type({ typename = "function", args = { VARARG_STRING }, rets = { STRING } }) }, rets = { STRING, NUMBER } }),
},
}),
["len"] = a_type({ typename = "function", args = { STRING }, rets = { NUMBER } }),
["lower"] = a_type({ typename = "function", args = { STRING }, rets = { STRING } }),
["match"] = a_type({ typename = "function", args = { STRING, STRING, NUMBER }, rets = { VARARG_STRING } }),
["pack"] = a_type({ typename = "function", args = { STRING, VARARG_ANY }, rets = { STRING } }),
["packsize"] = a_type({ typename = "function", args = { STRING }, rets = { NUMBER } }),
["rep"] = a_type({ typename = "function", args = { STRING, NUMBER }, rets = { STRING } }),
["reverse"] = a_type({ typename = "function", args = { STRING }, rets = { STRING } }),
["sub"] = a_type({ typename = "function", args = { STRING, NUMBER, NUMBER }, rets = { STRING } }),
["unpack"] = a_type({ typename = "function", args = { STRING, STRING, OPT_NUMBER }, rets = { VARARG_ANY } }),
["upper"] = a_type({ typename = "function", args = { STRING }, rets = { STRING } }),
},
}),
["table"] = a_type({
typename = "record",
fields = {
["concat"] = a_type({ typename = "function", args = { ARRAY_OF_STRING, OPT_STRING, OPT_NUMBER, OPT_NUMBER }, rets = { STRING } }),
["insert"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, NUMBER, ALPHA }, rets = {} }),
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, ALPHA }, rets = {} }),
},
}),
["move"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, NUMBER, NUMBER, NUMBER }, rets = { ARRAY_OF_ALPHA } }),
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, NUMBER, NUMBER, NUMBER, ARRAY_OF_ALPHA }, rets = { ARRAY_OF_ALPHA } }),
},
}),
["pack"] = a_type({ typename = "function", args = { VARARG_ANY }, rets = { TABLE } }),
["remove"] = a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, OPT_NUMBER }, rets = { ALPHA } }),
["sort"] = a_type({
typename = "poly",
types = {
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA }, rets = {} }),
a_type({ typename = "function", typeargs = { ARG_ALPHA }, args = { ARRAY_OF_ALPHA, a_type({ typename = "function", args = { ALPHA, ALPHA }, rets = { BOOLEAN } }) }, rets = {} }),
},
}),
["unpack"] = a_type({
typename = "function",
needs_compat53 = true,
typeargs = { ARG_ALPHA },
args = { ARRAY_OF_ALPHA, NUMBER, NUMBER },
rets = { VARARG_ALPHA },
}),
},
}),
["utf8"] = a_type({
typename = "record",
fields = {
["char"] = a_type({ typename = "function", args = { VARARG_NUMBER }, rets = { STRING } }),
["charpattern"] = STRING,
["codepoint"] = a_type({ typename = "function", args = { STRING, OPT_NUMBER, OPT_NUMBER }, rets = { VARARG_NUMBER } }),
["codes"] = a_type({ typename = "function", args = { STRING }, rets = {
a_type({ typename = "function", args = {}, rets = { NUMBER, STRING } }),
}, }),
["len"] = a_type({ typename = "function", args = { STRING, NUMBER, NUMBER }, rets = { NUMBER } }),
["offset"] = a_type({ typename = "function", args = { STRING, NUMBER, NUMBER }, rets = { NUMBER } }),
},
}),
}
for _, t in pairs(standard_library) do
fill_field_order(t)
if t.typename == "typetype" then
fill_field_order(t.def)
end
end
fill_field_order(OS_DATE_TABLE)
fill_field_order(DEBUG_GETINFO_TABLE)
NOMINAL_FILE.found = standard_library["FILE"]
NOMINAL_METATABLE.found = standard_library["METATABLE"]
local compat53_code_cache = {}
local function add_compat53_entries(program, used_set)
if not next(used_set) then
return
end
local used_list = {}
for name, _ in pairs(used_set) do
table.insert(used_list, name)
end
table.sort(used_list)
local compat53_loaded = false
local n = 1
local function load_code(name, text)
local code = compat53_code_cache[name]
if not code then
local tokens = tl.lex(text)
local _
_, code = tl.parse_program(tokens, {}, "@internal")
tl.type_check(code, { lax = false, skip_compat53 = true })
code = code[1]
compat53_code_cache[name] = code
end
table.insert(program, n, code)
n = n + 1
end
for i, name in ipairs(used_list) do
local mod, fn = name:match("([^.]*)%.(.*)")
local errs = {}
local text
local code = compat53_code_cache[name]
if not code then
if name == "table.unpack" then
load_code(name, "local _tl_table_unpack = unpack or table.unpack")
else
if not compat53_loaded then
load_code("compat53", "local _tl_compat53 = ((tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3) and require('compat53.module')")
compat53_loaded = true
end
load_code(name, (("local $NAME = _tl_compat53 and _tl_compat53.$NAME or $NAME"):gsub("$NAME", name)))
end
end
end
program.y = 1
end
local function get_stdlib_compat53(lax)
if lax then
return {
["utf8"] = true,
}
else
return {
["io"] = true,
["math"] = true,
["string"] = true,
["table"] = true,
["utf8"] = true,
["coroutine"] = true,
["os"] = true,
["package"] = true,
["debug"] = true,
["load"] = true,
["loadfile"] = true,
["assert"] = true,
["pairs"] = true,
["ipairs"] = true,
["pcall"] = true,
["xpcall"] = true,
["rawlen"] = true,
}
end
end
local function init_globals(lax)
local globals = {}
local stdlib_compat53 = get_stdlib_compat53(lax)
for name, typ in pairs(standard_library) do
globals[name] = { t = typ, needs_compat53 = stdlib_compat53[name], is_const = true }
end
globals["@is_va"] = { t = VARARG_ANY }
return globals
end
function tl.init_env(lax, skip_compat53)
local env = {
modules = {},
globals = init_globals(lax),
skip_compat53 = skip_compat53,
}
for name, var in pairs(standard_library) do
if var.typename == "record" then
env.modules[name] = var
end
end
return env
end
function tl.type_check(ast, opts)
opts = opts or {}
opts.env = opts.env or tl.init_env(opts.lax, opts.skip_compat53)
local lax = opts.lax
local filename = opts.filename
local result = opts.result or {
syntax_errors = {},
type_errors = {},
unknowns = {},
}
local stdlib_compat53 = get_stdlib_compat53(lax)
local st = { opts.env.globals }
local all_needs_compat53 = {}
local errors = result.type_errors or {}
local unknowns = result.unknowns or {}
local module_type
local function find_var(name)
if name == "_G" then
local globals = {}
for k, v in pairs(st[1]) do
if k:sub(1, 1) ~= "@" then
globals[k] = v.t
end
end
local field_order = {}
for k, _ in pairs(globals) do
table.insert(field_order, k)
end
return a_type({
typename = "record",
field_order = field_order,
fields = globals,
}), false
end
for i = #st, 1, -1 do
local scope = st[i]
if scope[name] then
if i == 1 and scope[name].needs_compat53 then
all_needs_compat53[name] = true
end
local typ = scope[name].t
return typ, scope[name].is_const
end
end
end
local function resolve_typevars(t, seen)
seen = seen or {}
if seen[t] then
return seen[t]
end
local orig_t = t
local clear_tk = false
if t.typename == "typevar" then
local tv = find_var(t.typevar)
if tv then
t = tv
clear_tk = true
else
t = UNKNOWN
end
end
local copy = {}
seen[orig_t] = copy
for k, v in pairs(t) do
local cp = copy
if type(v) == "table" then
cp[k] = resolve_typevars(v, seen)
else
cp[k] = v
end
end
if clear_tk then
copy.tk = nil
end
return copy
end
local function find_type(names, accept_typearg)
local typ = find_var(names[1])
if not typ then
return nil
end
for i = 2, #names do
local nested = typ.fields or (typ.def and typ.def.fields)
if nested then
typ = nested[names[i]]
if typ == nil then
return nil
end
else
break
end
end
if typ then
if accept_typearg and typ.typename == "typearg" then
return typ
end
if is_type(typ) then
return typ
end
end
return nil
end
local function infer_var(emptytable, t, node)
local is_global = (emptytable.declared_at and emptytable.declared_at.kind == "global_declaration")
local nst = is_global and 1 or #st
for i = nst, 1, -1 do
local scope = st[i]
if scope[emptytable.assigned_to] then
scope[emptytable.assigned_to] = {
t = t,
is_const = false,
}
t.inferred_at = node
t.inferred_at_file = filename
end
end
end
local function find_global(name)
local scope = st[1]
if scope[name] then
return scope[name].t, scope[name].is_const
end
end
local function resolve_tuple(t)
if t.typename == "tuple" then
t = t[1]
end
if t == nil then
return NIL
end
return t
end
local function error_in_type(where, msg, ...)
local n = select("#", ...)
if n > 0 then
local showt = {}
for i = 1, n do
local t = select(i, ...)
if t.typename == "invalid" then
return nil
end
showt[i] = show_type(t)
end
msg = msg:format(_tl_table_unpack(showt))
end
return {
y = where.y,
x = where.x,
msg = msg,
filename = where.filename or filename,
}
end
local function type_error(t, msg, ...)
local e = error_in_type(t, msg, ...)
if e then
table.insert(errors, e)
return true
else
return false
end
end
local function node_error(node, msg, ...)
local ok = type_error(node, msg, ...)
node.type = INVALID
return node.type
end
local function terr(t, s, ...)
return { error_in_type(t, s, ...) }
end
local function add_unknown(node, name)
table.insert(unknowns, { y = node.y, x = node.x, msg = name, filename = filename })
end
local function add_var(node, var, valtype, is_const, is_narrowing)
if lax and node and is_unknown(valtype) and (var ~= "self" and var ~= "...") then
add_unknown(node, var)
end
if st[#st][var] and is_narrowing then
if not st[#st][var].is_narrowed then
st[#st][var].narrowed_from = st[#st][var].t
end
st[#st][var].is_narrowed = true
st[#st][var].t = valtype
else
st[#st][var] = { t = valtype, is_const = is_const, is_narrowed = is_narrowing }
end
end
local CompareTypes = {}
local function compare_typevars(t1, t2, comp)
local tv1 = find_var(t1.typevar)
local tv2 = find_var(t2.typevar)
if t1.typevar == t2.typevar then
local has_t1 = not not tv1
local has_t2 = not not tv2
if has_t1 == has_t2 then
return true
end
end
local function cmp(k, v, a, b)
if find_var(k) then
return comp(a, b)
else
add_var(nil, k, resolve_typevars(v))
return true
end
end
if t2.typename == "typevar" then
return cmp(t2.typevar, t1, t1, tv2)
else
return cmp(t1.typevar, t2, tv1, t2)
end
end
local function add_errs_prefixing(src, dst, prefix, node)
if not src then
return
end
for i, err in ipairs(src) do
err.msg = prefix .. err.msg
if node and node.y and (
(err.filename ~= filename) or
(not err.y) or
(node.y > err.y or (node.y == err.y and node.x > err.x))) then
err.y = node.y
err.x = node.x
err.filename = filename
end
table.insert(dst, err)
end
end
local is_a
local TypeGetter = {}
local function match_record_fields(t1, t2, cmp)
cmp = cmp or is_a
local fielderrs = {}
for _, k in ipairs(t1.field_order) do
local f = t1.fields[k]
local t2k = t2(k)
if t2k == nil then
if not lax then
table.insert(fielderrs, error_in_type(f, "unknown field " .. k))
end
else
local match, errs = is_a(f, t2k)
add_errs_prefixing(errs, fielderrs, "record field doesn't match: " .. k .. ": ")
end
end
if #fielderrs > 0 then
return false, fielderrs
end
return true
end
local function match_fields_to_record(t1, t2, cmp)
return match_record_fields(t1, function(k) return t2.fields[k] end, cmp)
end
local function match_fields_to_map(t1, t2)
if not match_record_fields(t1, function(_) return t2.values end) then
return false, { error_in_type(t1, "not all fields have type %s", t2.values) }
end
return true
end
local function arg_check(cmp, a, b, at, n, errs)
local matches, match_errs = cmp(a, b)
if not matches then
add_errs_prefixing(match_errs, errs, "argument " .. n .. ": ", at)
return false
end
return true
end
local same_type
local function has_all_types_of(t1s, t2s)
for _, t1 in ipairs(t1s) do
local found = false
for _, t2 in ipairs(t2s) do
if is_a(t2, t1) then
found = true
break
end
end
if not found then
return false
end
end
return true
end
local function any_errors(all_errs)
if #all_errs == 0 then
return true
else
return false, all_errs
end
end
local function are_same_nominals(t1, t2)
local same_names
if t1.found and t2.found then
same_names = t1.found.typeid == t2.found.typeid
else
local ft1 = t1.found or find_type(t1.names)
local ft2 = t2.found or find_type(t2.names)
if ft1 and ft2 then
same_names = ft1.typeid == ft2.typeid
else
if not ft1 then
type_error(t1, "unknown type %s", t1)
end
if not ft2 then
type_error(t2, "unknown type %s", t2)
end
return false, {}
end
end
if same_names then
if t1.typevals == nil and t2.typevals == nil then
return true
elseif t1.typevals and t2.typevals and #t1.typevals == #t2.typevals then
local all_errs = {}
for i = 1, #t1.typevals do
local ok, errs = same_type(t2.typevals[i], t1.typevals[i])
add_errs_prefixing(errs, all_errs, "type parameter <" .. show_type(t1.typevals[i]) .. ">: ", t1)
end
if #all_errs == 0 then
return true
else
return false, all_errs
end
end
else
return false, terr(t1, "%s is not a %s", t1, t2)
end
end
same_type = function(t1, t2)
assert(type(t1) == "table")
assert(type(t2) == "table")
if t1.typename == "typevar" or t2.typename == "typevar" then
return compare_typevars(t1, t2, same_type)
end
if t1.typename ~= t2.typename then
return false, terr(t1, "got %s, expected %s", t1, t2)
end
if t1.typename == "array" then
return same_type(t1.elements, t2.elements)
elseif t1.typename == "map" then
local all_errs = {}
local k_ok, k_errs = same_type(t1.keys, t2.keys)
if not k_ok then
add_errs_prefixing(k_errs, all_errs, "keys", t1)
end
local v_ok, v_errs = same_type(t1.values, t2.values)
if not v_ok then
add_errs_prefixing(v_errs, all_errs, "values", t1)
end
return any_errors(all_errs)
elseif t1.typename == "union" then
if has_all_types_of(t1.types, t2.types) and
has_all_types_of(t2.types, t1.types) then
return true
else
return false, terr(t1, "got %s, expected %s", t1, t2)
end
elseif t1.typename == "nominal" then
return are_same_nominals(t1, t2)
elseif t1.typename == "record" then
return match_fields_to_record(t1, t2, same_type)
elseif t1.typename == "function" then
if #t1.args ~= #t2.args then
return false, terr(t1, "different number of input arguments: got " .. #t1.args .. ", expected " .. #t2.args)
end
if #t1.rets ~= #t2.rets then
return false, terr(t1, "different number of return values: got " .. #t1.args .. ", expected " .. #t2.args)
end
local all_errs = {}
for i = 1, #t1.args do
arg_check(same_type, t1.args[i], t2.args[i], t1, i, all_errs)
end
for i = 1, #t1.rets do
local ok, errs = same_type(t1.rets[i], t2.rets[i])
add_errs_prefixing(errs, all_errs, "return " .. i, t1)
end
return any_errors(all_errs)
elseif t1.typename == "arrayrecord" then
local ok, errs = same_type(t1.elements, t2.elements)
if not ok then
return ok, errs
end
return match_fields_to_record(t1, t2, same_type)
end
return true
end
local function a_union(types)
local ts = {}
local stack = {}
local i = 1
while types[i] or stack[1] do
local t
if stack[1] then
t = table.remove(stack)
else
t = types[i]
i = i + 1
end
if t.typename == "union" then
for _, s in ipairs(t.types) do
table.insert(stack, s)
end
else
table.insert(ts, t)
end
end
return a_type({
typename = "union",
types = ts,
})
end
local function is_vararg(t)
return t.args and #t.args > 0 and t.args[#t.args].is_va
end
local function combine_errs(...)
local errs
for i = 1, select("#", ...) do
local e = select(i, ...)
if e then
errs = errs or {}
for _, err in ipairs(e) do
table.insert(errs, err)
end
end
end
if not errs then
return true
else
return false, errs
end
end
local resolve_unary = nil
local function is_known_table_type(t)
return (t.typename == "array" or t.typename == "map" or t.typename == "record" or t.typename == "arrayrecord")
end
is_a = function(t1, t2, for_equality)
assert(type(t1) == "table")
assert(type(t2) == "table")
if lax and (is_unknown(t1) or is_unknown(t2)) then
return true
end
if t1.typename == "nil" then
return true
end
if t2.typename ~= "tuple" then
t1 = resolve_tuple(t1)
end
if t2.typename == "tuple" and t1.typename ~= "tuple" then
t1 = a_type({
typename = "tuple",
[1] = t1,
})
end
if t1.typename == "typevar" or t2.typename == "typevar" then
return compare_typevars(t1, t2, is_a)
end
if t2.typename == "any" then
return true
elseif t2.typename == "poly" then
for _, t in ipairs(t2.types) do
if is_a(t1, t, for_equality) then
return true
end
end
return false, terr(t1, "cannot match against any alternatives of the polymorphic type")
elseif t1.typename == "union" and t2.typename == "union" then
if has_all_types_of(t1.types, t2.types) then
return true
else
return false, terr(t1, "got %s, expected %s", t1, t2)
end
elseif t2.typename == "union" then
for _, t in ipairs(t2.types) do
if is_a(t1, t, for_equality) then
return true
end
end
elseif t1.typename == "poly" then
for _, t in ipairs(t1.types) do
if is_a(t, t2, for_equality) then
return true
end
end
return false, terr(t1, "cannot match against any alternatives of the polymorphic type")
elseif t1.typename == "nominal" and t2.typename == "nominal" and #t2.names == 1 and t2.names[1] == "any" then
return true
elseif t1.typename == "nominal" and t2.typename == "nominal" then
return are_same_nominals(t1, t2)
elseif t1.typename == "enum" and t2.typename == "string" then
local ok
if for_equality then
ok = t2.tk and t1.enumset[unquote(t2.tk)]
else
ok = true
end
if ok then
return true
else
return false, terr(t1, "enum is incompatible with %s", t2)
end
elseif t1.typename == "string" and t2.typename == "enum" then
local ok = t1.tk and t2.enumset[unquote(t1.tk)]
if ok then
return true
else
if t1.tk then
return false, terr(t1, "%s is not a member of %s", t1, t2)
else
return false, terr(t1, "string is not a %s", t2)
end
end
elseif t1.typename == "nominal" or t2.typename == "nominal" then
local t1u = resolve_unary(t1)
local t2u = resolve_unary(t2)
local ok, errs = is_a(t1u, t2u, for_equality)
if errs and #errs == 1 then
if errs[1].msg:match("^got ") then
errs = terr(t1, "got %s, expected %s", t1, t2)
end
end
return ok, errs
elseif t1.typename == "emptytable" and is_known_table_type(t2) then
return true
elseif t2.typename == "array" then
if is_array_type(t1) then
if is_a(t1.elements, t2.elements) then
return true
end
elseif t1.typename == "map" then
local _, errs_keys = is_a(t1.keys, NUMBER)
local _, errs_values = is_a(t1.values, t2.elements)
return combine_errs(errs_keys, errs_values)
end
elseif t2.typename == "record" then
if is_record_type(t1) then
return match_fields_to_record(t1, t2)
elseif t1.typename == "typetype" and t1.def.typename == "record" then
return is_a(t1.def, t2, for_equality)
end
elseif t2.typename == "arrayrecord" then
if t1.typename == "array" then
return is_a(t1.elements, t2.elements)
elseif t1.typename == "record" then
return match_fields_to_record(t1, t2)
elseif t1.typename == "arrayrecord" then
if not is_a(t1.elements, t2.elements) then
return false, terr(t1, "array parts have incompatible element types")
end
return match_fields_to_record(t1, t2)
end
elseif t2.typename == "map" then
if t1.typename == "map" then
local _, errs_keys = is_a(t1.keys, t2.keys)
local _, errs_values = is_a(t2.values, t1.values)
if t2.values.typename == "any" then
errs_values = {}
end
return combine_errs(errs_keys, errs_values)
elseif t1.typename == "array" then
local _, errs_keys = is_a(NUMBER, t2.keys)
local _, errs_values = is_a(t1.elements, t2.values)
return combine_errs(errs_keys, errs_values)
elseif is_record_type(t1) then
if not is_a(t2.keys, STRING) then
return false, terr(t1, "can't match a record to a map with non-string keys")
end
if t2.keys.typename == "enum" then
for _, k in ipairs(t1.field_order) do
if not t2.keys.enumset[k] then
return false, terr(t1, "key is not an enum value: " .. k)
end
end
end
return match_fields_to_map(t1, t2)
end
elseif t1.typename == "function" and t2.typename == "function" then
local all_errs = {}
if (not is_vararg(t2)) and #t1.args > #t2.args then
t1.args.typename = "tuple"
t2.args.typename = "tuple"
table.insert(all_errs, error_in_type(t1, "incompatible number of arguments: got " .. #t1.args .. " %s, expected " .. #t2.args .. " %s", t1.args, t2.args))
else
for i = (t1.is_method and 2 or 1), #t1.args do
arg_check(is_a, t1.args[i], t2.args[i] or ANY, nil, i, all_errs)
end
end
local diff_by_va = #t2.rets - #t1.rets == 1 and t2.rets[#t2.rets].is_va
if #t1.rets < #t2.rets and not diff_by_va then
t1.rets.typename = "tuple"
t2.rets.typename = "tuple"
table.insert(all_errs, error_in_type(t1, "incompatible number of returns: got " .. #t1.rets .. " %s, expected " .. #t2.rets .. " %s", t1.rets, t2.rets))
else
local nrets = #t2.rets
if diff_by_va then
nrets = nrets - 1
end
for i = 1, nrets do
local ok, errs = is_a(t1.rets[i], t2.rets[i])
add_errs_prefixing(errs, all_errs, "return " .. i .. ": ")
end
end
if #all_errs == 0 then
return true
else
return false, all_errs
end
elseif lax and ((not for_equality) and t2.typename == "boolean") then
return true
elseif t1.typename == t2.typename then
return true
end
return false, terr(t1, "got %s, expected %s", t1, t2)
end
local function assert_is_a(node, t1, t2, context, name)
t1 = resolve_tuple(t1)
t2 = resolve_tuple(t2)
if lax and (is_unknown(t1) or is_unknown(t2)) then
return
end
if t2.typename == "unknown_emptytable_value" then
if same_type(t2.emptytable_type.keys, NUMBER) then
infer_var(t2.emptytable_type, a_type({ typename = "array", elements = t1 }), node)
else
infer_var(t2.emptytable_type, a_type({ typename = "map", keys = t2.emptytable_type.keys, values = t1 }), node)
end
return
elseif t2.typename == "emptytable" then
if is_known_table_type(t1) then
infer_var(t2, t1, node)
elseif t1.typename ~= "emptytable" then
node_error(node, "in " .. context .. ": " .. (name and (name .. ": ") or "") .. "assigning %s to a variable declared with {}", t1)
end
return
end
local match, match_errs = is_a(t1, t2)
add_errs_prefixing(match_errs, errors, "in " .. context .. ": " .. (name and (name .. ": ") or ""), node)
end
local function close_types(vars)
for name, var in pairs(vars) do
if var.t.typename == "typetype" then
var.t.closed = true
end
end
end
local function begin_scope()
table.insert(st, {})
end
local function end_scope()
local unresolved = st[#st]["@unresolved"]
if unresolved then
local upper = st[#st - 1]["@unresolved"]
if upper then
for name, nodes in pairs(unresolved.t.labels) do
for _, node in ipairs(nodes) do
upper.t.labels[name] = upper.t.labels[name] or {}
table.insert(upper.t.labels[name], node)
end
end
for name, types in pairs(unresolved.t.nominals) do
for _, typ in ipairs(types) do
upper.t.nominals[name] = upper.t.nominals[name] or {}
table.insert(upper.t.nominals[name], typ)
end
end
else
st[#st - 1]["@unresolved"] = unresolved
end
end
close_types(st[#st])
table.remove(st)
end
local type_check_function_call
do
local function try_match_func_args(node, f, args, is_method, argdelta)
local ok = true
local errs = {}
if is_method then
argdelta = -1
elseif not argdelta then
argdelta = 0
end
if f.is_method and not is_method and not (args[1] and is_a(args[1], f.args[1])) then
table.insert(errs, { y = node.y, x = node.x, msg = "invoked method as a regular function: use ':' instead of '.'", filename = filename })
return nil, errs
end
local va = is_vararg(f)
local nargs = va and
math.max(#args, #f.args) or
math.min(#args, #f.args)
for a = 1, nargs do
local arg = args[a]
local farg = f.args[a] or (va and f.args[#f.args])
if arg == nil then
if farg.is_va then
break
end
else
local at = node.e2 and node.e2[a] or node
if not arg_check(is_a, arg, farg, at, (a + argdelta), errs) then
ok = false
break
end
end
end
if ok == true then
f.rets.typename = "tuple"
for a = 1, #args do
local arg = args[a]
local farg = f.args[a] or (va and f.args[#f.args])
if arg.typename == "emptytable" then
infer_var(arg, resolve_typevars(farg), node.e2[a])
end
end
return resolve_typevars(f.rets)
end
return nil, errs
end
local function revert_typeargs(func)
if func.typeargs then
for _, arg in ipairs(func.typeargs) do
if st[#st][arg.typearg] then
st[#st][arg.typearg] = nil
end
end
end
end
local function remove_sorted_duplicates(t)
local prev = nil
for i = #t, 1, -1 do
if t[i] == prev then
table.remove(t, i)
else
prev = t[i]
end
end
end
local function check_call(node, func, args, is_method, argdelta)
assert(type(func) == "table")
assert(type(args) == "table")
if lax and is_unknown(func) then
func = a_type({ typename = "function", args = { VARARG_UNKNOWN }, rets = { VARARG_UNKNOWN } })
end
func = resolve_unary(func)
args = args or {}
local poly = func.typename == "poly" and func or { types = { func } }
local first_errs
local expects = {}
local tried = {}
for i, f in ipairs(poly.types) do
if not tried[i] then
if f.typename ~= "function" then
if lax and is_unknown(f) then
return UNKNOWN
end
return node_error(node, "not a function: %s", f)
end
table.insert(expects, tostring(#f.args or 0))
local va = is_vararg(f)
if #args == (#f.args or 0) or (va and #args > #f.args) then
tried[i] = true
local matched, errs = try_match_func_args(node, f, args, is_method, argdelta)
if matched then
return matched
else
revert_typeargs(f)
end
first_errs = first_errs or errs
end
end
end
for i, f in ipairs(poly.types) do
if not tried[i] then
tried[i] = true
if #args < (#f.args or 0) then
tried[i] = true
local matched, errs = try_match_func_args(node, f, args, is_method, argdelta)
if matched then
return matched
else
revert_typeargs(f)
end
first_errs = first_errs or errs
end
end
end
for i, f in ipairs(poly.types) do
if not tried[i] then
if is_vararg(f) and #args > (#f.args or 0) then
tried[i] = true
local matched, errs = try_match_func_args(node, f, args, is_method, argdelta)
if matched then
return matched
else
revert_typeargs(f)
end
first_errs = first_errs or errs
end
end
end
if not first_errs then
table.sort(expects)
remove_sorted_duplicates(expects)
node_error(node, "wrong number of arguments (given " .. #args .. ", expects " .. table.concat(expects, " or ") .. ")")
else
for _, err in ipairs(first_errs) do
table.insert(errors, err)
end
end
poly.types[1].rets.typename = "tuple"
return resolve_typevars(poly.types[1].rets)
end
type_check_function_call = function(node, func, args, is_method, argdelta)
begin_scope()
local ret = check_call(node, func, args, is_method, argdelta)
end_scope()
return ret
end
end
local unknown_dots = {}
local function add_unknown_dot(node, name)
if not unknown_dots[name] then
unknown_dots[name] = true
add_unknown(node, name)
end
end
local function get_self_type(t)
if t.typename == "typetype" then
return t.def
else
return t
end
end
local function match_record_key(node, tbl, key, orig_tbl)
assert(type(tbl) == "table")
assert(type(key) == "table")
tbl = resolve_unary(tbl)
local type_description = tbl.typename
if tbl.typename == "string" or tbl.typename == "enum" then
tbl = find_var("string")
end
if lax and (is_unknown(tbl) or tbl.typename == "typevar") then
if node.e1.kind == "variable" and node.op.op ~= "@funcall" then
add_unknown_dot(node, node.e1.tk .. "." .. key.tk)
end
return UNKNOWN
end
tbl = get_self_type(tbl)
if tbl.typename == "emptytable" then
elseif is_record_type(tbl) then
assert(tbl.fields, "record has no fields!?")
if key.kind == "string" or key.kind == "identifier" then
if tbl.fields[key.tk] then
return tbl.fields[key.tk]
end
end
else
if is_unknown(tbl) then
if not lax then
node_error(node, "cannot index a value of unknown type")
end
else
node_error(node, "cannot index something that is not a record: %s", tbl)
end
return INVALID
end
if lax then
if node.e1.kind == "variable" and node.op.op ~= "@funcall" then
add_unknown_dot(node, node.e1.tk .. "." .. key.tk)
end
return UNKNOWN
end
local description
if node.e1.kind == "variable" then
description = type_description .. " '" .. node.e1.tk .. "' of type " .. show_type(resolve_tuple(orig_tbl))
else
description = "type " .. show_type(resolve_tuple(orig_tbl))
end
return node_error(key, "invalid key '" .. key.tk .. "' in " .. description)
end
local function widen_in_scope(scope, var)
if scope[var].is_narrowed then
if scope[var].narrowed_from then
scope[var].t = scope[var].narrowed_from
scope[var].narrowed_from = nil
scope[var].is_narrowed = false
else
scope[var] = nil
end
return true
end
return false
end
local function widen_back_var(var)
local widened = false
for i = #st, 1, -1 do
if st[i][var] then
if widen_in_scope(st[i], var) then
widened = true
else
break
end
end
end
return widened
end
local function widen_all_unions()
for i = #st, 1, -1 do
for var, _ in pairs(st[i]) do
widen_in_scope(st[i], var)
end
end
end
local function add_global(node, var, valtype, is_const)
if lax and is_unknown(valtype) and (var ~= "self" and var ~= "...") then
add_unknown(node, var)
end
st[1][var] = { t = valtype, is_const = is_const }
end
local check_typevars
local function check_all_typevars(node, ts)
if ts ~= nil then
for _, arg in ipairs(ts) do
check_typevars(node, arg)
end
end
end
check_typevars = function(node, t)
if t == nil then
return
end
if t.typename == "typevar" then
if not find_var(t.typevar) then
node_error(node, "unknown type variable " .. t.typevar)
end
return
end
check_typevars(node, t.elements)
check_typevars(node, t.keys)
check_typevars(node, t.values)
check_all_typevars(node, t.typeargs)
check_all_typevars(node, t.args)
check_all_typevars(node, t.rets)
end
local function get_rets(rets)
if lax and (#rets == 0) then
return { a_type({ typename = "unknown", is_va = true }) }
end
return rets
end
local function begin_function_scope(node, recurse)
begin_scope()
local args = {}
if node.typeargs then
for i, arg in ipairs(node.typeargs) do
add_var(nil, arg.typearg, arg)
end
end
local is_va = false
for i, arg in ipairs(node.args) do
local t = arg.decltype
if not t then
t = a_type({ typename = "unknown" })
end
if arg.tk == "..." then
is_va = true
t.is_va = true
if i ~= #node.args then
node_error(node, "'...' can only be last argument")
end
end
check_typevars(arg, t)
table.insert(args, t)
add_var(arg, arg.tk, t)
end
add_var(nil, "@is_va", is_va and VARARG_ANY or NIL)
add_var(nil, "@return", node.rets or a_type({ typename = "tuple" }))
if recurse then
add_var(nil, node.name.tk, a_type({
typename = "function",
args = args,
rets = get_rets(node.rets),
}))
end
end
local function fail_unresolved()
local unresolved = st[#st]["@unresolved"]
if unresolved then
st[#st]["@unresolved"] = nil
for name, nodes in pairs(unresolved.t.labels) do
for _, node in ipairs(nodes) do
node_error(node, "no visible label '" .. name .. "' for goto")
end
end
for name, types in pairs(unresolved.t.nominals) do
for _, typ in ipairs(types) do
assert(typ.x)
assert(typ.y)
type_error(typ, "unknown type %s", typ)
end
end
end
end
local function end_function_scope()
fail_unresolved()
end_scope()
end
local function match_typevals(t, def)
if t.typevals and def.typeargs then
if #t.typevals ~= #def.typeargs then
type_error(t, "mismatch in number of type arguments")
return nil
end
begin_scope()
for i, tt in ipairs(t.typevals) do
add_var(nil, def.typeargs[i].typearg, tt)
end
local ret = resolve_typevars(def)
end_scope()
return ret
elseif t.typevals then
type_error(t, "spurious type arguments")
return nil
elseif def.typeargs then
type_error(t, "missing type arguments in %s", def)
return nil
else
return def
end
end
local function resolve_nominal(t)
if t.resolved then
return t.resolved
end
local resolved
local typetype = t.found or find_type(t.names)
if not typetype then
type_error(t, "unknown type %s", t)
elseif is_type(typetype) then
resolved = match_typevals(t, typetype.def)
else
type_error(t, table.concat(t.names, ".") .. " is not a type")
end
if not resolved then
resolved = a_type({ typename = "bad_nominal", names = t.names })
end
t.found = typetype
t.resolved = resolved
return resolved
end
resolve_unary = function(t)
t = resolve_tuple(t)
if t.typename == "nominal" then
return resolve_nominal(t)
end
return t
end
local function flatten_list(list)
local exps = {}
for i = 1, #list - 1 do
table.insert(exps, resolve_unary(list[i]))
end
if #list > 0 then
local last = list[#list]
if last.typename == "tuple" then
for _, val in ipairs(last) do
table.insert(exps, val)
end
else
table.insert(exps, last)
end
end
return exps
end
local function get_assignment_values(vals, wanted)
local ret = {}
if vals == nil then
return ret
end
for i = 1, #vals - 1 do
ret[i] = vals[i]
end
local last = vals[#vals]
if last.typename == "tuple" then
for _, v in ipairs(last) do
table.insert(ret, v)
end
elseif last.is_va and #ret < wanted then
while #ret < wanted do
table.insert(ret, last)
end
else
table.insert(ret, last)
end
return ret
end
local function match_all_record_field_names(node, a, field_names, errmsg)
local t
for _, k in ipairs(field_names) do
local f = a.fields[k]
if not t then
t = f
else
if not same_type(f, t) then
t = nil
break
end
end
end
if t then
return t
else
return node_error(node, errmsg)
end
end
local function type_check_index(node, idxnode, a, b)
local orig_a = a
local orig_b = b
a = resolve_unary(a)
b = resolve_unary(b)
if is_array_type(a) and is_a(b, NUMBER) then
return a.elements
elseif a.typename == "emptytable" then
if a.keys == nil then
a.keys = b
a.keys_inferred_at = node
a.keys_inferred_at_file = filename
else
if not is_a(b, a.keys) then
local inferred = " (type of keys inferred at " .. a.keys_inferred_at_file .. ":" .. a.keys_inferred_at.y .. ":" .. a.keys_inferred_at.x .. ": )"
return node_error(idxnode, "inconsistent index type: %s, expected %s" .. inferred, b, a.keys)
end
end
return a_type({ y = node.y, x = node.x, typename = "unknown_emptytable_value", emptytable_type = a })
elseif a.typename == "map" then
if is_a(b, a.keys) then
return a.values
else
return node_error(idxnode, "wrong index type: %s, expected %s", orig_b, a.keys)
end
elseif node.e2.kind == "string" or node.e2.kind == "enum_item" then
return match_record_key(node, a, { y = node.e2.y, x = node.e2.x, kind = "string", tk = assert(node.e2.conststr) }, orig_a)
elseif is_record_type(a) and b.typename == "enum" then
local field_names = {}
for k, _ in pairs(b.enumset) do
table.insert(field_names, k)
end
table.sort(field_names)
for _, k in ipairs(field_names) do
if not a.fields[k] then
return node_error(idxnode, "enum value '" .. k .. "' is not a field in %s", a)
end
end
return match_all_record_field_names(idxnode, a, field_names,
"cannot index, not all enum values map to record fields of the same type")
elseif lax and is_unknown(a) then
return UNKNOWN
else
if is_a(b, STRING) then
return node_error(idxnode, "cannot index object of type %s with a string, consider using an enum", orig_a)
end
return node_error(idxnode, "cannot index object of type %s with %s", orig_a, orig_b)
end
end
local function expand_type(where, old, new)
if not old then
return new
else
if not is_a(new, old) then
if old.typename == "map" and is_record_type(new) then
if old.keys.typename == "string" then
for _, ftype in pairs(new.fields) do
old.values = expand_type(where, old.values, ftype)
end
else
node_error(where, "cannot determine table literal type")
end
elseif is_record_type(old) and is_record_type(new) then
old.typename = "map"
old.keys = STRING
for _, ftype in pairs(old.fields) do
if not old.values then
old.values = ftype
else
old.values = expand_type(where, old.values, ftype)
end
end
for _, ftype in pairs(new.fields) do
if not old.values then
new.values = ftype
else
new.values = expand_type(where, old.values, ftype)
end
end
old.fields = nil
old.field_order = nil
elseif old.typename == "union" then
new.tk = nil
table.insert(old.types, new)
else
old.tk = nil
new.tk = nil
return a_union({ old, new })
end
end
end
return old
end
local function find_in_scope(exp)
if exp.kind == "variable" then
local t = find_var(exp.tk)
if t.def then
if not t.def.closed and not t.closed then
return t.def
end
end
if not t.closed then
return t
end
elseif exp.kind == "op" and exp.op.op == "." then
local t = find_in_scope(exp.e1)
if not t then
return nil
end
while exp.e2.kind == "op" and exp.e2.op.op == "." do
t = t.fields[exp.e2.e1.tk]
if not t then
return nil
end
exp = exp.e2
end
t = t.fields[exp.e2.tk]
return t
end
end
local facts_and
local facts_or
local facts_not
do
local function join_facts(fss)
local vars = {}
for _, fs in ipairs(fss) do
for _, f in ipairs(fs) do
if not vars[f.var] then
vars[f.var] = {}
end
table.insert(vars[f.var], f)
end
end
return vars
end
local function intersect(xs, ys, same)
local rs = {}
for i = #xs, 1, -1 do
local x = xs[i]
for _, y in ipairs(ys) do
if same(x, y) then
table.insert(rs, x)
break
end
end
end
return rs
end
local function same_type_for_intersect(t, u)
return (same_type(t, u))
end
local function intersect_facts(fs, errnode)
local all_is = true
local types = {}
for i, f in ipairs(fs) do
if f.fact ~= "is" then
all_is = false
break
end
if f.typ.typename == "union" then
if i == 1 then
types = f.typ.types
else
types = intersect(types, f.typ.types, same_type_for_intersect)
end
else
if i == 1 then
types = { f.typ }
else
types = intersect(types, { f.typ }, same_type_for_intersect)
end
end
end
if #types == 0 then
node_error(errnode, "branch is always false")
return false
end
if all_is then
if #types == 1 then
return true, types[1]
else
return true, a_union(types)
end
else
return false
end
end
local function sum_facts(fs)
local all_is = true
local types = {}
for _, f in ipairs(fs) do
if f.fact ~= "is" then
all_is = false
break
end
table.insert(types, f.typ)
end
if all_is then
if #types == 1 then
return true, types[1]
else
return true, a_union(types)
end
else
return false
end
end
local function subtract_types(u1, u2, errt)
local types = {}
for _, rt in ipairs(u1.types or { u1 }) do
local not_present = true
for _, ft in ipairs(u2.types or { u2 }) do
if same_type(rt, ft) then
not_present = false
break
end
end
if not_present then
table.insert(types, rt)
end
end
if #types == 0 then
type_error(errt, "branch is always false")
return INVALID
end
if #types == 1 then
return types[1]
else
return a_union(types)
end
end
facts_and = function(f1, f2, errnode)
if not f1 then
return f2
end
if not f2 then
return f1
end
local out = {}
for v, fs in pairs(join_facts({ f1, f2 })) do
local ok, u = intersect_facts(fs, errnode)
if ok then
table.insert(out, { fact = "is", var = v, typ = u })
else
for _, f in ipairs(fs) do
table.insert(out, f)
end
end
end
return out
end
facts_or = function(f1, f2)
if not f1 or not f2 then
return nil
end
local out = {}
for v, fs in pairs(join_facts({ f1, f2 })) do
local ok, u = sum_facts(fs)
if ok then
table.insert(out, { fact = "is", var = v, typ = u })
else
for _, f in ipairs(fs) do
table.insert(out, f)
end
end
end
return out
end
facts_not = function(f1)
if not f1 then
return nil
end
local out = {}
for v, fs in pairs(join_facts({ f1 })) do
local realtype = find_var(v)
if realtype then
local ok, u = sum_facts(fs)
if ok then
local not_typ = subtract_types(realtype, u, fs[1].typ)
table.insert(out, { fact = "is", var = v, typ = not_typ })
end
end
end
return out
end
end
local function apply_facts(where, facts)
if not facts then
return
end
for _, f in ipairs(facts) do
if f.fact == "is" then
local t = resolve_typevars(f.typ)
t.inferred_at = where
t.inferred_at_file = filename
add_var(nil, f.var, t, nil, true)
end
end
end
local function dismiss_unresolved(name)
local unresolved = st[#st]["@unresolved"]
if unresolved then
if unresolved.t.nominals[name] then
for _, t in ipairs(unresolved.t.nominals[name]) do
resolve_nominal(t)
end
end
unresolved.t.nominals[name] = nil
end
end
local function type_check_funcall(node, a, b, argdelta)
argdelta = argdelta or 0
if node.e1.tk == "rawget" then
if #b == 2 then
local b1 = resolve_unary(b[1])
local b2 = resolve_unary(b[2])
local knode = node.e2[2]
if is_record_type(b1) and knode.conststr then
return match_record_key(node, b1, { y = knode.y, x = knode.x, kind = "string", tk = assert(knode.conststr) }, b1)
else
return type_check_index(node, knode, b1, b2)
end
else
node_error(node, "rawget expects two arguments")
end
elseif node.e1.tk == "print_type" then
print(show_type(b))
return BOOLEAN
elseif node.e1.tk == "require" then
if #b == 1 then
if node.e2[1].kind == "string" then
local module_name = assert(node.e2[1].conststr)
local t, found = require_module(module_name, lax, opts.env, result)
if not found then
node_error(node, "module not found: '" .. module_name .. "'")
elseif not lax and is_unknown(t) then
node_error(node, "no type information for required module: '" .. module_name .. "'")
end
return t
else
node_error(node, "don't know how to resolve a dynamic require")
end
else
node_error(node, "require expects one literal argument")
end
elseif node.e1.tk == "pcall" then
local ftype = table.remove(b, 1)
local fe2 = {}
for i = 2, #node.e2 do
table.insert(fe2, node.e2[i])
end
local fnode = {
y = node.y,
x = node.x,
typename = "op",
op = { op = "@funcall" },
e1 = node.e2[1],
e2 = fe2,
}
local rets = type_check_funcall(fnode, ftype, b, argdelta + 1)
if rets.typename ~= "tuple" then
rets = a_type({ typename = "tuple", rets })
end
table.insert(rets, 1, BOOLEAN)
return rets
elseif node.e1.op and node.e1.op.op == ":" then
local func = node.e1.type
if func.typename == "function" or func.typename == "poly" then
table.insert(b, 1, node.e1.e1.type)
return type_check_function_call(node, func, b, true)
else
if lax and (is_unknown(func)) then
if node.e1.e1.kind == "variable" then
add_unknown_dot(node, node.e1.e1.tk .. "." .. node.e1.e2.tk)
end
return VARARG_UNKNOWN
else
return INVALID
end
end
else
return type_check_function_call(node, a, b, false, argdelta)
end
return UNKNOWN
end
local visit_node = {}
visit_node.cbs = {
["statements"] = {
before = function()
begin_scope()
end,
after = function(node, children)
if #st == 2 then
fail_unresolved()
end
if not node.is_repeat then
end_scope()
end
node.type = NONE
end,
},
["local_type"] = {
before = function(node)
add_var(node.var, node.var.tk, node.value.newtype, node.var.is_const)
end,
after = function(node, children)
dismiss_unresolved(node.var.tk)
node.type = NONE
end,
},
["global_type"] = {
before = function(node)
add_global(node.var, node.var.tk, node.value.newtype, node.var.is_const)
end,
after = function(node, children)
local existing, existing_is_const = find_global(node.var.tk)
local var = node.var
if existing then
if existing_is_const == true and not var.is_const then
node_error(var, "global was previously declared as <const>: " .. var.tk)
end
if existing_is_const == false and var.is_const then
node_error(var, "global was previously declared as not <const>: " .. var.tk)
end
if not same_type(existing, node.value.newtype) then
node_error(var, "cannot redeclare global with a different type: previous type of " .. var.tk .. " is %s", existing)
end
end
dismiss_unresolved(var.tk)
node.type = NONE
end,
},
["local_declaration"] = {
after = function(node, children)
local vals = get_assignment_values(children[2], #node.vars)
for i, var in ipairs(node.vars) do
local decltype = node.decltype and node.decltype[i]
local infertype = vals and vals[i]
if lax and infertype and infertype.typename == "nil" then
infertype = nil
end
if decltype and infertype then
assert_is_a(node.vars[i], infertype, decltype, "local declaration", var.tk)
end
local t = decltype or infertype
if t == nil then
t = a_type({ typename = "unknown" })
if not lax then
if node.exps then
node_error(node.vars[i], "assignment in declaration did not produce an initial value for variable '" .. var.tk .. "'")
else
node_error(node.vars[i], "variable '" .. var.tk .. "' has no type or initial value")
end
end
elseif t.typename == "emptytable" then
t.declared_at = node
t.assigned_to = var.tk
end
assert(var)
add_var(var, var.tk, t, var.is_const)
dismiss_unresolved(var.tk)
end
node.type = NONE
end,
},
["global_declaration"] = {
after = function(node, children)
local vals = get_assignment_values(children[2], #node.vars)
for i, var in ipairs(node.vars) do
local decltype = node.decltype and node.decltype[i]
local infertype = vals and vals[i]
if lax and infertype and infertype.typename == "nil" then
infertype = nil
end
if decltype and infertype then
assert_is_a(node.vars[i], infertype, decltype, "global declaration", var.tk)
end
local t = decltype or infertype
local existing, existing_is_const = find_global(var.tk)
if existing then
if infertype and existing_is_const then
node_error(var, "cannot reassign to <const> global: " .. var.tk)
end
if existing_is_const == true and not var.is_const then
node_error(var, "global was previously declared as <const>: " .. var.tk)
end
if existing_is_const == false and var.is_const then
node_error(var, "global was previously declared as not <const>: " .. var.tk)
end
if not same_type(existing, t) then
node_error(var, "cannot redeclare global with a different type: previous type of " .. var.tk .. " is %s", existing)
end
else
if t == nil then
t = a_type({ typename = "unknown" })
elseif t.typename == "emptytable" then
t.declared_at = node
t.assigned_to = var.tk
end
add_global(var, var.tk, t, var.is_const)
dismiss_unresolved(var.tk)
end
end
node.type = NONE
end,
},
["assignment"] = {
after = function(node, children)
local vals = get_assignment_values(children[2], #children[1])
local exps = flatten_list(vals)
for i, vartype in ipairs(children[1]) do
local varnode = node.vars[i]
if varnode.is_const then
node_error(varnode, "cannot assign to <const> variable")
end
if varnode.kind == "variable" then
if widen_back_var(varnode.tk) then
vartype = find_var(varnode.tk)
end
end
if vartype then
local val = exps[i]
if resolve_unary(vartype).typename == "typetype" then
node_error(varnode, "cannot reassign a type")
elseif val then
assert_is_a(varnode, val, vartype, "assignment")
if varnode.kind == "variable" and vartype.typename == "union" then
add_var(varnode, varnode.tk, val, false, true)
end
else
node_error(varnode, "variable is not being assigned a value")
end
else
node_error(varnode, "unknown variable")
end
end
node.type = NONE
end,
},
["do"] = {
after = function(node, children)
node.type = NONE
end,
},
["if"] = {
before_statements = function(node)
begin_scope()
apply_facts(node.exp, node.exp.facts)
end,
after = function(node, children)
end_scope()
node.type = NONE
end,
},
["elseif"] = {
before = function(node)
end_scope()
begin_scope()
end,
before_statements = function(node)
local f = facts_not(node.parent_if.exp.facts)
for e = 1, node.elseif_n - 1 do
f = facts_and(f, facts_not(node.parent_if.elseifs[e].exp.facts), node)
end
f = facts_and(f, node.exp.facts, node)
apply_facts(node.exp, f)
end,
after = function(node, children)
node.type = NONE
end,
},
["else"] = {
before = function(node)
end_scope()
begin_scope()
local f = facts_not(node.parent_if.exp.facts)
for _, elseifnode in ipairs(node.parent_if.elseifs) do
f = facts_and(f, facts_not(elseifnode.exp.facts), node)
end
apply_facts(node, f)
end,
after = function(node, children)
node.type = NONE
end,
},
["while"] = {
before = function()
widen_all_unions()
end,
before_statements = function(node)
begin_scope()
apply_facts(node.exp, node.exp.facts)
end,
after = function(node, children)
end_scope()
node.type = NONE
end,
},
["label"] = {
before = function(node)
widen_all_unions()
local label_id = "::" .. node.label .. "::"
if st[#st][label_id] then
node_error(node, "label '" .. node.label .. "' already defined at " .. filename)
end
local unresolved = st[#st]["@unresolved"]
if unresolved then
unresolved.t.labels[node.label] = nil
end
node.type = a_type({ y = node.y, x = node.x, typename = "none" })
add_var(node, label_id, node.type)
end,
},
["goto"] = {
after = function(node, children)
if not find_var("::" .. node.label .. "::") then
local unresolved = st[#st]["@unresolved"] and st[#st]["@unresolved"].t
if not unresolved then
unresolved = { typename = "unresolved", labels = {}, nominals = {} }
add_var(node, "@unresolved", unresolved)
end
unresolved.labels[node.label] = unresolved.labels[node.label] or {}
table.insert(unresolved.labels[node.label], node)
end
node.type = NONE
end,
},
["repeat"] = {
before = function()
widen_all_unions()
end,
after = function(node, children)
end_scope()
node.type = NONE
end,
},
["forin"] = {
before = function()
begin_scope()
end,
before_statements = function(node)
local exp1 = node.exps[1]
local exp1type = resolve_tuple(exp1.type)
if exp1type.typename == "function" then
if exp1.op and exp1.op.op == "@funcall" then
local t = resolve_unary(exp1.e2.type)
if exp1.e1.tk == "pairs" and not (t.typename == "map" or t.typename == "record") then
if not (lax and is_unknown(t)) then
node_error(exp1, "attempting pairs loop on something that's not a map or record: %s", exp1.e2.type)
end
elseif exp1.e1.tk == "ipairs" and not is_array_type(t) then
if not (lax and (is_unknown(t) or t.typename == "emptytable")) then
node_error(exp1, "attempting ipairs loop on something that's not an array: %s", exp1.e2.type)
end
end
end
local last
for i, v in ipairs(node.vars) do
local r = exp1type.rets[i]
if not r then
if last and last.is_va then
r = last
else
r = UNKNOWN
end
end
add_var(v, v.tk, r)
last = r
end
else
if not (lax and is_unknown(exp1type)) then
node_error(exp1, "expression in for loop does not return an iterator")
end
end
end,
after = function(node, children)
end_scope()
node.type = NONE
end,
},
["fornum"] = {
before = function(node)
begin_scope()
add_var(nil, node.var.tk, NUMBER)
end,
after = function(node, children)
end_scope()
node.type = NONE
end,
},
["return"] = {
after = function(node, children)
local rets = assert(find_var("@return"))
local nrets = #rets
local vatype
if nrets > 0 then
vatype = rets[nrets].is_va and rets[nrets]
end
if #children[1] > nrets and (not lax) and not vatype then
rets.typename = "tuple"
children[1].typename = "tuple"
node_error(node, "excess return values, expected " .. #rets .. " %s, got " .. #children[1] .. " %s", rets, children[1])
end
for i = 1, #children[1] do
local expected = rets[i] or vatype
if expected then
expected = resolve_unary(expected)
local where = (node.exps[i] and node.exps[i].x) and
node.exps[i] or
node.exps
assert(where and where.x)
assert_is_a(where, children[1][i], expected, "return value")
end
end
if #st == 2 then
module_type = resolve_unary(children[1])
end
node.type = NONE
end,
},
["variables"] = {
after = function(node, children)
node.type = children
local n = #children
if n > 0 and children[n].typename == "tuple" then
local tuple = children[n]
for i, c in ipairs(tuple) do
children[n + i - 1] = c
end
end
node.type.typename = "tuple"
end,
},
["table_literal"] = {
after = function(node, children)
node.type = a_type({
y = node.y,
x = node.x,
typename = "emptytable",
})
local is_record = false
local is_array = false
local is_map = false
for i, child in ipairs(children) do
assert(child.typename == "table_item")
if child.kname then
is_record = true
if not node.type.fields then
node.type.fields = {}
node.type.field_order = {}
end
node.type.fields[child.kname] = child.vtype
table.insert(node.type.field_order, child.kname)
elseif child.ktype.typename == "number" then
is_array = true
if i == #children and node[i].key_parsed == "implicit" and child.vtype.typename == "tuple" then
for _, c in ipairs(child.vtype) do
node.type.elements = expand_type(node, node.type.elements, c)
end
else
node.type.elements = expand_type(node, node.type.elements, child.vtype)
end
if not node.type.elements then
node_error(node, "cannot determine type of array elements")
is_array = false
end
else
is_map = true
node.type.keys = expand_type(node, node.type.keys, child.ktype)
node.type.values = expand_type(node, node.type.values, child.vtype)
end
end
if is_array and is_map then
node_error(node, "cannot determine type of table literal")
elseif is_record and is_array then
node.type.typename = "arrayrecord"
elseif is_record and is_map then
if node.type.keys.typename == "string" then
node.type.typename = "map"
for _, ftype in pairs(node.type.fields) do
node.type.values = expand_type(node, node.type.values, ftype)
end
node.type.fields = nil
node.type.field_order = nil
else
node_error(node, "cannot determine type of table literal")
end
elseif is_array then
node.type.typename = "array"
elseif is_record then
node.type.typename = "record"
elseif is_map then
node.type.typename = "map"
end
end,
},
["table_item"] = {
after = function(node, children)
local kname = node.key.conststr
local ktype = children[1]
local vtype = children[2]
if node.decltype then
vtype = node.decltype
assert_is_a(node.value, children[2], node.decltype, "table item")
end
node.type = a_type({
y = node.y,
x = node.x,
typename = "table_item",
kname = kname,
ktype = ktype,
vtype = vtype,
})
end,
},
["local_function"] = {
before = function(node)
begin_function_scope(node, true)
end,
after = function(node, children)
end_function_scope()
local rets = get_rets(children[3])
add_var(nil, node.name.tk, a_type({
typename = "function",
args = children[2],
rets = rets,
}))
node.type = NONE
end,
},
["global_function"] = {
before = function(node)
begin_function_scope(node, true)
end,
after = function(node, children)
end_function_scope()
add_global(nil, node.name.tk, a_type({
typename = "function",
args = children[2],
rets = get_rets(children[3]),
}))
node.type = NONE
end,
},
["record_function"] = {
before = function(node)
begin_function_scope(node)
end,
before_statements = function(node, children)
if node.is_method then
local rtype = get_self_type(children[1])
children[3][1] = rtype
add_var(nil, "self", rtype)
end
local rtype = resolve_unary(get_self_type(children[1]))
if rtype.typename == "emptytable" then
rtype.typename = "record"
end
if is_record_type(rtype) then
local fn_type = a_type({
y = node.y,
x = node.x,
typename = "function",
is_method = node.is_method,
args = children[3],
rets = get_rets(children[4]),
})
local ok = false
if lax then
ok = true
elseif rtype.fields and rtype.fields[node.name.tk] and is_a(fn_type, rtype.fields[node.name.tk]) then
ok = true
elseif find_in_scope(node.fn_owner) == rtype then
ok = true
end
if ok then
rtype.fields = rtype.fields or {}
rtype.field_order = rtype.field_order or {}
rtype.fields[node.name.tk] = fn_type
table.insert(rtype.field_order, node.name.tk)
else
local name = tl.pretty_print_ast(node.fn_owner, { preserve_indent = true, preserve_newlines = false })
node_error(node, "cannot add undeclared function '" .. node.name.tk .. "' outside of the scope where '" .. name .. "' was originally declared")
end
else
if (not lax) or (rtype.typename ~= "unknown") then
node_error(node, "not a module: %s", rtype)
end
end
end,
after = function(node, children)
end_function_scope()
node.type = NONE
end,
},
["function"] = {
before = function(node)
begin_function_scope(node)
end,
after = function(node, children)
end_function_scope()
node.type = a_type({
y = node.y,
x = node.x,
typename = "function",
args = children[1],
rets = children[2],
})
end,
},
["cast"] = {
after = function(node, children)
node.type = node.casttype
end,
},
["paren"] = {
after = function(node, children)
node.type = resolve_unary(children[1])
end,
},
["op"] = {
before = function(node)
begin_scope()
end,
before_e2 = function(node)
if node.op.op == "and" then
apply_facts(node, node.e1.facts)
elseif node.op.op == "or" then
apply_facts(node, facts_not(node.e1.facts))
end
end,
after = function(node, children)
end_scope()
local a = children[1]
local b = children[3]
local orig_a = a
local orig_b = b
local ua = a and resolve_unary(a)
local ub = b and resolve_unary(b)
if node.op.op == "@funcall" then
node.type = type_check_funcall(node, a, b)
elseif node.op.op == "@index" then
node.type = type_check_index(node, node.e2, a, b)
elseif node.op.op == "as" then
node.type = b
elseif node.op.op == "is" then
if node.e1.kind == "variable" then
node.facts = { { fact = "is", var = node.e1.tk, typ = b } }
else
node_error(node, "can only use 'is' on variables")
end
node.type = BOOLEAN
elseif node.op.op == "." then
a = ua
if a.typename == "map" then
if is_a(a.keys, STRING) or is_a(a.keys, ANY) then
node.type = a.values
else
node_error(node, "cannot use . index, expects keys of type %s", a.keys)
end
else
node.type = match_record_key(node, a, { y = node.e2.y, x = node.e2.x, kind = "string", tk = node.e2.tk }, orig_a)
if node.type.needs_compat53 and not opts.skip_compat53 then
local key = node.e1.tk .. "." .. node.e2.tk
node.kind = "variable"
node.tk = "_tl_" .. node.e1.tk .. "_" .. node.e2.tk
all_needs_compat53[key] = true
end
end
elseif node.op.op == ":" then
node.type = match_record_key(node, node.e1.type, node.e2, orig_a)
elseif node.op.op == "not" then
node.facts = facts_not(node.e1.facts)
node.type = BOOLEAN
elseif node.op.op == "and" then
node.facts = facts_and(node.e1.facts, node.e2.facts, node)
node.type = resolve_tuple(b)
elseif node.op.op == "or" and b.typename == "emptytable" then
node.facts = nil
node.type = resolve_tuple(a)
elseif node.op.op == "or" and same_type(ua, ub) then
node.facts = facts_or(node.e1.facts, node.e2.facts)
node.type = resolve_tuple(a)
elseif node.op.op == "or" and b.typename == "nil" then
node.facts = nil
node.type = resolve_tuple(a)
elseif node.op.op == "or" and
((ua.typename == "enum" and ub.typename == "string" and is_a(ub, ua)) or
(ua.typename == "string" and ub.typename == "enum" and is_a(ua, ub))) then
node.facts = nil
node.type = (ua.typename == "enum" and ua or ub)
elseif node.op.op == "or" and
(a.typename == "nominal" or a.typename == "map") and
is_record_type(b) and
is_a(b, a) then
node.facts = nil
node.type = resolve_tuple(a)
elseif node.op.op == "==" or node.op.op == "~=" then
if is_a(a, b, true) or is_a(b, a, true) then
node.type = BOOLEAN
else
if lax and (is_unknown(a) or is_unknown(b)) then
node.type = UNKNOWN
else
node_error(node, "types are not comparable for equality: %s and %s", a, b)
end
end
elseif node.op.arity == 1 and unop_types[node.op.op] then
a = ua
local types_op = unop_types[node.op.op]
node.type = types_op[a.typename]
if not node.type then
if lax and is_unknown(a) then
node.type = UNKNOWN
else
node_error(node, "cannot use operator '" .. node.op.op:gsub("%%", "%%%%") .. "' on type %s", orig_a)
end
end
elseif node.op.arity == 2 and binop_types[node.op.op] then
if node.op.op == "or" then
node.facts = facts_or(node.e1.facts, node.e2.facts)
end
a = ua
b = ub
local types_op = binop_types[node.op.op]
node.type = types_op[a.typename] and types_op[a.typename][b.typename]
if not node.type then
if lax and (is_unknown(a) or is_unknown(b)) then
node.type = UNKNOWN
else
node_error(node, "cannot use operator '" .. node.op.op:gsub("%%", "%%%%") .. "' for types %s and %s", orig_a, orig_b)
end
end
else
error("unknown node op " .. node.op.op)
end
end,
},
["variable"] = {
after = function(node, children)
if node.tk == "..." then
local va_sentinel = find_var("@is_va")
if not va_sentinel or va_sentinel.typename == "nil" then
node.type = UNKNOWN
node_error(node, "cannot use '...' outside a vararg function")
end
end
node.type, node.is_const = find_var(node.tk)
if node.type == nil then
node.type = a_type({ typename = "unknown" })
if lax then
add_unknown(node, node.tk)
else
node_error(node, "unknown variable: " .. node.tk)
end
end
end,
},
["identifier"] = {
after = function(node, children)
node.type = NONE
end,
},
["newtype"] = {
after = function(node, children)
node.type = node.newtype
end,
},
}
visit_node.cbs["break"] = visit_node.cbs["do"]
visit_node.cbs["values"] = visit_node.cbs["variables"]
visit_node.cbs["expression_list"] = visit_node.cbs["variables"]
visit_node.cbs["argument_list"] = visit_node.cbs["variables"]
visit_node.cbs["argument"] = visit_node.cbs["variable"]
visit_node.cbs["string"] = {
after = function(node, children)
node.type = a_type({
y = node.y,
x = node.x,
typename = node.kind,
tk = node.tk,
})
return node.type
end,
}
visit_node.cbs["number"] = visit_node.cbs["string"]
visit_node.cbs["nil"] = visit_node.cbs["string"]
visit_node.cbs["boolean"] = visit_node.cbs["string"]
visit_node.cbs["..."] = visit_node.cbs["variable"]
visit_node.after = {
after = function(node, children)
assert(type(node.type) == "table", node.kind .. " did not produce a type")
assert(type(node.type.typename) == "string", node.kind .. " type does not have a typename")
return node.type
end,
}
local visit_type = {
cbs = {
["string"] = {
after = function(typ, children)
return typ
end,
},
["function"] = {
before = function(typ, children)
begin_scope()
end,
after = function(typ, children)
end_scope()
return typ
end,
},
["record"] = {
before = function(typ, children)
begin_scope()
for name, typ in pairs(typ.fields) do
if typ.typename == "typetype" then
typ.typename = "nestedtype"
add_var(nil, name, typ)
end
end
end,
after = function(typ, children)
end_scope()
for name, typ in pairs(typ.fields) do
if typ.typename == "nestedtype" then
typ.typename = "typetype"
end
end
return typ
end,
},
["typearg"] = {
after = function(typ, children)
add_var(nil, typ.typearg, a_type({
y = typ.y,
x = typ.x,
typename = "typearg",
typearg = typ.typearg,
}))
return typ
end,
},
["nominal"] = {
after = function(typ, children)
local t = find_type(typ.names, true)
if t then
if t.typename == "typearg" then
typ.names = nil
typ.typename = "typevar"
typ.typevar = t.typearg
else
typ.found = t
end
else
local name = typ.names[1]
local unresolved = find_var("@unresolved")
if not unresolved then
unresolved = { typename = "unresolved", labels = {}, nominals = {} }
add_var(nil, "@unresolved", unresolved)
end
unresolved.nominals[name] = unresolved.nominals[name] or {}
table.insert(unresolved.nominals[name], typ)
end
return typ
end,
},
["union"] = {
after = function(typ, children)
local n_table_types = 0
local n_function_types = 0
local n_string_enum = 0
for _, t in ipairs(typ.types) do
t = resolve_unary(t)
if table_types[t.typename] then
n_table_types = n_table_types + 1
if n_table_types > 1 then
type_error(typ, "cannot discriminate a union between multiple table types: %s", typ)
break
end
elseif t.typename == "function" then
n_function_types = n_function_types + 1
if n_function_types > 1 then
type_error(typ, "cannot discriminate a union between multiple function types: %s", typ)
break
end
elseif t.typename == "string" or t.typename == "enum" then
n_string_enum = n_string_enum + 1
if n_string_enum > 1 then
type_error(typ, "cannot discriminate a union between multiple string/enum types: %s", typ)
break
end
end
end
return typ
end,
},
},
after = {
after = function(typ, children, ret)
assert(type(ret) == "table", typ.typename .. " did not produce a type")
assert(type(ret.typename) == "string", "type node does not have a typename")
return ret
end,
},
}
visit_type.cbs["typetype"] = visit_type.cbs["string"]
visit_type.cbs["nestedtype"] = visit_type.cbs["string"]
visit_type.cbs["typevar"] = visit_type.cbs["string"]
visit_type.cbs["array"] = visit_type.cbs["string"]
visit_type.cbs["map"] = visit_type.cbs["string"]
visit_type.cbs["arrayrecord"] = visit_type.cbs["string"]
visit_type.cbs["enum"] = visit_type.cbs["string"]
visit_type.cbs["boolean"] = visit_type.cbs["string"]
visit_type.cbs["nil"] = visit_type.cbs["string"]
visit_type.cbs["number"] = visit_type.cbs["string"]
visit_type.cbs["thread"] = visit_type.cbs["string"]
visit_type.cbs["bad_nominal"] = visit_type.cbs["string"]
visit_type.cbs["emptytable"] = visit_type.cbs["string"]
visit_type.cbs["table_item"] = visit_type.cbs["string"]
visit_type.cbs["unknown_emptytable_value"] = visit_type.cbs["string"]
visit_type.cbs["tuple"] = visit_type.cbs["string"]
visit_type.cbs["poly"] = visit_type.cbs["string"]
visit_type.cbs["any"] = visit_type.cbs["string"]
visit_type.cbs["unknown"] = visit_type.cbs["string"]
visit_type.cbs["invalid"] = visit_type.cbs["string"]
visit_type.cbs["unresolved"] = visit_type.cbs["string"]
visit_type.cbs["none"] = visit_type.cbs["string"]
recurse_node(ast, visit_node, visit_type)
close_types(st[1])
local redundant = {}
local lastx, lasty = 0, 0
table.sort(errors, function(a, b)
return ((a.filename and b.filename) and a.filename < b.filename) or
(a.filename == b.filename and ((a.y < b.y) or (a.y == b.y and a.x < b.x)))
end)
for i, err in ipairs(errors) do
if err.x == lastx and err.y == lasty then
table.insert(redundant, i)
end
lastx, lasty = err.x, err.y
end
for i = #redundant, 1, -1 do
table.remove(errors, redundant[i])
end
if not opts.skip_compat53 then
add_compat53_entries(ast, all_needs_compat53)
end
return errors, unknowns, module_type
end
function tl.process(filename, env, result, preload_modules)
local fd, err = io.open(filename, "r")
if not fd then
return nil, "could not open " .. filename .. ": " .. err
end
local input, err = fd:read("*a")
fd:close()
if not input then
return nil, "could not read " .. filename .. ": " .. err
end
local basename, extension = filename:match("(.*)%.([a-z]+)$")
extension = extension and extension:lower()
local is_lua
if extension == "tl" then
is_lua = false
elseif extension == "lua" then
is_lua = true
else
is_lua = input:match("^#![^\n]*lua[^\n]*\n")
end
result, err = tl.process_string(input, is_lua, env, result, preload_modules, filename)
if err then
return nil, err
end
return result
end
function tl.process_string(input, is_lua, env, result, preload_modules,
filename)
env = env or tl.init_env(is_lua)
result = result or {
syntax_errors = {},
type_errors = {},
unknowns = {},
}
preload_modules = preload_modules or {}
filename = filename or ""
local tokens, errs = tl.lex(input)
if errs then
for i, err in ipairs(errs) do
table.insert(result.syntax_errors, {
y = err.y,
x = err.x,
msg = "invalid token '" .. err.tk .. "'",
filename = filename,
})
end
end
local i, program = tl.parse_program(tokens, result.syntax_errors, filename)
if #result.syntax_errors > 0 then
return result
end
for _, name in ipairs(preload_modules) do
local module_type = require_module(name, is_lua, env, result)
if module_type == UNKNOWN then
return nil, string.format("Error: could not preload module '%s'", name)
end
end
local error, unknown
local opts = {
lax = is_lua,
filename = filename,
env = env,
result = result,
skip_compat53 = env.skip_compat53,
}
error, unknown, result.type = tl.type_check(program, opts)
result.ast = program
result.env = env
return result
end
function tl.gen(input, env)
env = env or tl.init_env()
local result, err = tl.process_string(input, false, env)
if err then
return nil, nil
end
if not result.ast then
return nil, result
end
return tl.pretty_print_ast(result.ast), result
end
local function tl_package_loader(module_name)
local found_filename, fd, tried = tl.search_module(module_name, false)
if found_filename then
local input = fd:read("*a")
fd:close()
local errs = {}
local _, program = tl.parse_program(tl.lex(input), errs, module_name)
if #errs > 0 then
error(module_name .. ":" .. errs[1].y .. ":" .. errs[1].x .. ": " .. errs[1].msg)
end
local code = tl.pretty_print_ast(program, true)
local chunk, err = load(code, module_name, "t")
if chunk then
return function()
local ret = chunk()
package.loaded[module_name] = ret
return ret
end
else
error("Internal Compiler Error: Teal generator produced invalid Lua. Please report a bug at https://github.com/teal-language/tl")
end
end
return table.concat(tried, "\n\t")
end
function tl.loader()
if package.searchers then
table.insert(package.searchers, 2, tl_package_loader)
else
table.insert(package.loaders, 2, tl_package_loader)
end
end
function tl.load(input, chunkname, mode, env)
local tokens = tl.lex(input)
local errs = {}
local i, program = tl.parse_program(tokens, errs, chunkname)
if #errs > 0 then
return nil, (chunkname or "") .. ":" .. errs[1].y .. ":" .. errs[1].x .. ": " .. errs[1].msg
end
local code = tl.pretty_print_ast(program, true)
return load(code, chunkname, mode, env)
end
return tl
|