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
use crate::parser::ast::*;
use crate::errors::{CompileError, SourceFile, SourceLocation, find_similar_keyword, ENGLISH_KEYWORDS};
use std::collections::{HashMap, HashSet};
const FD_MAX: i64 = 2_147_483_647;
#[derive(Debug, Default)]
pub struct Dependencies {
pub uses_io: bool,
pub uses_heap: bool,
pub uses_strings: bool,
pub uses_args: bool,
pub uses_funcs: bool,
}
#[cfg(test)]
mod buffer_append_copy_analysis_tests {
use super::*;
use crate::lexer::Lexer;
use crate::parser::Parser;
fn analyze_input(input: &str) -> Analyzer {
let mut lexer = Lexer::new(input);
let tokens = lexer.tokenize();
let mut parser = Parser::new(tokens);
let mut program = parser.parse().expect("input should parse");
let mut analyzer = Analyzer::new().with_source("test.en", input);
analyzer.analyze(&mut program);
analyzer
}
#[test]
fn append_requires_buffer_source_when_destination_is_buffer() {
let input = r#"
a buffer called dst is "hello".
a number called n is 7.
append n to dst.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Buffer append requires")),
"expected buffer-append type error, got: {:?}",
analyzer.errors
);
}
#[test]
fn quoted_condition_unknown_variable_inside_function_is_reported() {
let input = r#"
To mutate,
if 'missing' then,
Print "ok".
'mutate'.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Unknown variable: missing")),
"expected unknown-variable error, got: {:?}",
analyzer.errors
);
}
#[test]
fn quoted_condition_top_level_global_inside_function_is_allowed() {
let input = r#"
a boolean called counter is true.
To bump,
if 'counter' then,
Print "ok".
'bump'.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: counter")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn copy_requires_buffers_for_both_operands() {
let input = r#"
a buffer called dst is "hello".
a number called n is 7.
copy n to dst.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Copy source must be a buffer")),
"expected copy-source type error, got: {:?}",
analyzer.errors
);
}
#[test]
fn clear_requires_buffer_operand() {
let input = r#"
a number called n is 7.
clear n.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Clear target must be a buffer")),
"expected clear-target type error, got: {:?}",
analyzer.errors
);
}
#[test]
fn append_allows_format_string_when_destination_is_buffer() {
let input = r#"
a number called n is 7.
a buffer called dst is "".
append "N={n:04}" to dst.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Buffer append requires")),
"unexpected buffer-append error(s): {:?}",
analyzer.errors
);
}
#[test]
fn copy_allows_format_string_source() {
let input = r#"
a number called n is 7.
a buffer called dst is "".
copy "N={n:04}" to dst.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Copy source must be a buffer") && !e.message.contains("Copy source must be a buffer or format/literal text")),
"unexpected copy-source error(s): {:?}",
analyzer.errors
);
}
#[test]
fn file_open_rejects_float_path_literal() {
let input = r#"
open a file for reading called source at 1.5.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Open path must be either a text path")),
"expected open-path type error, got: {:?}",
analyzer.errors
);
}
#[test]
fn file_open_rejects_boolean_path_literal() {
let input = r#"
open a file for reading called source at true.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Open path must be either a text path")),
"expected open-path type error, got: {:?}",
analyzer.errors
);
}
#[test]
fn file_open_rejects_fd_literal_out_of_range() {
let input = r#"
open a file for reading called source at -1.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("File descriptor out of range")),
"expected fd-range error, got: {:?}",
analyzer.errors
);
}
#[test]
fn file_open_accepts_string_path_and_fd_literal() {
let input = r#"
open a file for reading called source at "./data.txt".
open a file for writing called output at 1.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Open path must be either a text path") && !e.message.contains("File descriptor out of range")),
"unexpected open-path errors: {:?}",
analyzer.errors
);
}
#[test]
fn treating_rejects_mismatched_match_and_replacement_types() {
let input = r#"
print each filename from arguments's all treating "-" as 0.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Treating match and replacement must be the same type")),
"expected treating type mismatch error, got: {:?}",
analyzer.errors
);
}
#[test]
fn treating_allows_same_type_substitution() {
let input = r#"
print each filename from arguments's all treating "-" as "/dev/stdin".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Treating match and replacement must be the same type")),
"unexpected treating type mismatch error(s): {:?}",
analyzer.errors
);
}
}
#[cfg(test)]
mod guard_env_tests {
use super::*;
use crate::lexer::Lexer;
use crate::parser::Parser;
fn analyze_input(input: &str) -> Analyzer {
let mut lexer = Lexer::new(input);
let tokens = lexer.tokenize();
let mut parser = Parser::new(tokens);
let mut program = parser.parse().expect("input should parse");
let mut analyzer = Analyzer::new().with_source("test.en", input);
analyzer.analyze(&mut program);
analyzer
}
#[test]
fn variable_declared_under_same_guard_is_available_under_same_guard_later() {
let input = r#"
if "number lines" then,
a number called 'line number' is 1.
if "number lines" then,
Print "{line number:6}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: line number")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn variable_declared_under_different_guard_is_not_available() {
let input = r#"
if "number lines" then,
a number called 'line number' is 1.
if "verbose" then,
Print "{line number:6}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Unknown variable: line number")),
"expected unknown-variable error, got: {:?}",
analyzer.errors
);
}
#[test]
fn guarded_variable_is_available_in_nested_while_for_repeat_blocks() {
let input = r#"
if "number lines" then,
a number called 'line number' is 1.
if "number lines" then,
while true,
for each item in arguments's all,
repeat 1 times,
Print "{line number:6}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: line number")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn variable_declared_under_same_and_condition_is_available() {
let input = r#"
if "number lines" and "verbose" then,
a number called 'line number' is 1.
if "number lines" and "verbose" then,
Print "{line number:6}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: line number")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn variable_declared_under_same_not_condition_is_available() {
let input = r#"
if not "number lines" then,
a number called 'line number' is 1.
if not "number lines" then,
Print "{line number:6}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: line number")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn unknown_variable_inside_function_is_reported() {
let input = r#"
To 'show',
Print "{missing}".
'show'.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Unknown variable: missing")),
"expected unknown-variable error, got: {:?}",
analyzer.errors
);
}
#[test]
fn top_level_global_variable_is_available_inside_function() {
let input = r#"
A text called 'Program Version' is "0.1.3".
To 'show',
Print "{Program Version}".
'show'.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown variable: Program Version")),
"unexpected unknown-variable errors: {:?}",
analyzer.errors
);
}
#[test]
fn function_local_variable_is_not_available_at_top_level() {
let input = r#"
To 'make',
a number called temp is 1.
Print "{temp}".
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Unknown variable: temp") || e.message.contains("Unknown identifier 'temp'")),
"expected unknown-variable error, got: {:?}",
analyzer.errors
);
}
#[test]
fn branch_local_identifier_named_like_keyword_is_not_false_positive() {
let input = r#"
If arguments's count is greater than 1 then,
a text called arg1 is arguments's first,
Print the arg1.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.all(|e| !e.message.contains("Unknown identifier 'arg1'") && !e.message.contains("Unknown variable: arg1")),
"unexpected arg1 errors: {:?}",
analyzer.errors
);
}
#[test]
fn flag_schema_after_non_schema_code_is_allowed() {
let input = r#"
Print "hello".
a flag called verbose is "-v" or "--verbose", it is a boolean.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer.errors.is_empty(),
"expected no errors for schema after non-schema code, got: {:?}",
analyzer.errors
);
}
#[test]
fn flag_schema_after_explicit_parse_is_rejected() {
let input = r#"
a flag called verbose is "-v" or "--verbose", it is a boolean.
parse flags.
a flag called debug is "-d" or "--debug", it is a boolean.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Cannot declare new flags after 'parse flags.'")),
"expected post-parse schema error, got: {:?}",
analyzer.errors
);
}
#[test]
fn duplicate_parse_flags_statement_is_rejected() {
let input = r#"
a flag called verbose is "-v" or "--verbose", it is a boolean.
parse flags.
parse flags.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Duplicate 'parse flags.' statement")),
"expected duplicate-parse error, got: {:?}",
analyzer.errors
);
}
#[test]
fn flag_usage_before_explicit_parse_is_rejected() {
let input = r#"
a flag called verbose is "-v" or "--verbose", it is a boolean.
Print "{verbose}".
parse flags.
"#;
let analyzer = analyze_input(input);
assert!(
analyzer
.errors
.iter()
.any(|e| e.message.contains("Flag variable 'verbose' is used before flags are parsed")),
"expected pre-parse usage error, got: {:?}",
analyzer.errors
);
}
}
pub struct Analyzer {
pub deps: Dependencies,
pub variables: HashSet<String>,
pub functions: HashSet<String>,
/// Assembly symbol -> the function name that claimed it. Two names that
/// differ only in characters the mangler folds to `_` ("my.helper" and
/// "my helper") would emit one label and silently share a body.
mangled_functions: std::collections::HashMap<String, String>,
pub used_identifiers: HashSet<String>, // Track all identifiers seen
typo_candidates: HashSet<String>,
pub errors: Vec<CompileError>,
source_file: Option<SourceFile>,
guarded_scopes: HashMap<String, HashSet<String>>,
symbol_error_counts: HashMap<String, usize>,
/// Where each concretely-typed variable was first declared, captured at
/// declaration time for the type-lock check's "note: declared here"
/// (a variable's type is fixed at declaration and never changes).
declared_locations: HashMap<String, SourceLocation>,
active_guards: Vec<String>,
in_function_scope: bool,
block_depth: usize,
global_variables: HashSet<String>,
flag_variables: HashSet<String>,
buffer_variables: HashSet<String>,
list_variables: HashSet<String>,
map_variables: HashSet<String>,
file_variables: HashSet<String>,
timer_variables: HashSet<String>,
/// Variables holding a raw heap pointer from `Allocate`. They are not
/// buffers (no length/capacity header), but `Free` must accept them -
/// that is the whole point of Allocate.
allocated_variables: HashSet<String>,
/// Declared/inferred scalar category (Integer/Float/String/Boolean) for
/// non-buffer, non-list, non-file, non-timer variables. Vox is dynamically
/// typed - a variable's runtime category is whatever its last assignment
/// stored - so this map is updated on every VarDecl and Assignment to stay
/// current. It lets the arithmetic type check distinguish a text variable
/// (must be cast with `as a number`/`as a float` before arithmetic) from a
/// numeric one, which the buffer/list/flag sets alone cannot do.
scalar_types: HashMap<String, Type>,
function_param_counts: HashMap<String, usize>,
/// Names declared as the dynamic `value` type (value parameters and `a
/// value called x` locals). A bare `value` is not usable in arithmetic
/// without an explicit type check (stage 1c predicate); the arithmetic
/// operand check uses this set to reject unguarded use with a clear error.
value_typed_names: HashSet<String>,
/// Lists proven heterogeneous from their own literal initializer at
/// declaration time (plan 294 finding 18) - e.g. `a list called data is
/// [42, "hello"].`. Deliberately narrower than codegen's `mixed_lists`
/// pre-scan: this only looks at a direct `ListLit` initializer, not
/// aliasing through other variables or widening via later `Append`s.
/// That asymmetry is safe in the direction it's used (a `for each` loop
/// variable over a list this set doesn't catch keeps today's existing,
/// unchanged behaviour rather than being wrongly tightened), but it
/// means a list built up entirely through `Append` calls of differing
/// types is not detected as mixed here the way it would be by codegen.
list_mixed: HashSet<String>,
/// A map's value type, proven from its own literal initializer when
/// every value shares one provable type (plan 294 findings 4, 14) -
/// e.g. `{"k": 42}` is a map of number. `Type::Map` is otherwise never
/// given a value type anywhere in the analyzer, so a mismatched read
/// (`a text called s is m's "k".` where `m`'s values are numbers) was
/// unprovable and silently passed the type lock. Absent (not `None`
/// stored, just no entry) for a map whose literal has mixed value
/// types, an empty map, or a non-literal initializer - `arithmetic_
/// operand_type` then returns `None` for a read from it, same
/// "can't prove it, so allow" policy as everywhere else in this file.
/// Narrower than a full type system: only the map's own declaration
/// site is consulted, not aliasing or later `Set <map>'s "k" to
/// <value>` writes that could widen it.
map_value_type: HashMap<String, Type>,
loop_depth: usize,
/// True when compiling `--shared`. A shared library has no `_start`, so a
/// top-level executable statement would be generated into the discarded
/// main body and silently dropped. Reject such statements up front rather
/// than mislead the author.
shared_mode: bool,
/// The identity of the library whose function definitions surround the
/// statement currently being analyzed, set by `Library` declarations as
/// the walk proceeds. The per-function tables (`functions`,
/// `function_param_counts`, `mangled_functions`) are keyed by the
/// `<lib>_<ver>_<func>` mangled label, so a call resolves only against the
/// current library's functions: a name defined in a DIFFERENT library of
/// the same .so is not in this library's key set and stays the existing
/// "Unknown function" error (cross-library calls are out of scope for A2).
/// `None` outside shared mode, where the key is plain `mangle_symbol(name)`.
current_library: Option<(String, String)>,
/// Set right after analyzing a function whose body a blank line force-
/// closed early. Consulted by errors in the top-level statements that
/// follow, since that's where such a function's "missing" params actually
/// surface as errors. Cleared as soon as the next FunctionDef or Library
/// starts analysis, bounding it to just the orphaned statements in between.
pending_blank_line_truncation: Option<(String, Vec<String>, SourceLocation)>,
// (function_name, its parameter names, the blank line's location)
/// Stage A4: functions imported by `see '<lib>' version "<ver>" from
/// "...lib".`, resolved against the filesystem by the driver (parse +
/// .dynsym verification) and handed here for name resolution and call
/// checking. A call resolves local-first (a local definition SHADOWS a
/// same-named import, with a warning naming the library), then by import
/// (exactly one exporting <lib,version>), then ambiguity (two imports
/// exporting the same name — an error by design, never a pick).
imports: Vec<crate::lib_file::ImportedFunction>,
/// Non-fatal diagnostics (currently: local-definitions-shadow-imports).
/// Printed by the driver with a `warning:` prefix; they never stop a
/// build, but shadowing is never silent either.
pub warnings: Vec<String>,
}
#[derive(Clone, Default)]
struct AnalysisEnv {
always: HashSet<String>,
guarded: HashMap<String, HashSet<String>>,
}
/// A short, human-readable name for a statement kind, used in the shared-mode
/// top-level diagnostic. Only called for statements that are NOT one of the
/// three allowed top-level forms (FunctionDef/LibraryDecl/See).
fn shared_top_level_label(stmt: &Statement) -> &'static str {
match stmt {
Statement::Print { .. } => "print statement",
Statement::VarDecl { .. } => "variable declaration",
Statement::Assignment { .. } => "assignment",
Statement::If { .. } => "if statement",
Statement::While { .. } => "while loop",
Statement::ForRange { .. } | Statement::ForEach { .. } | Statement::Repeat { .. } => "loop",
Statement::FunctionCall { .. } => "function call",
Statement::Exit { .. } => "exit statement",
Statement::OnError { .. } => "on error handler",
Statement::FlagSchemaDecl { .. } | Statement::ParseFlags => "flag declaration",
_ => "statement",
}
}
impl Analyzer {
pub fn new() -> Self {
Analyzer {
deps: Dependencies::default(),
variables: HashSet::new(),
functions: HashSet::new(),
mangled_functions: std::collections::HashMap::new(),
used_identifiers: HashSet::new(),
typo_candidates: HashSet::new(),
errors: Vec::new(),
source_file: None,
guarded_scopes: HashMap::new(),
symbol_error_counts: HashMap::new(),
declared_locations: HashMap::new(),
active_guards: Vec::new(),
in_function_scope: false,
block_depth: 0,
global_variables: HashSet::new(),
flag_variables: HashSet::new(),
buffer_variables: HashSet::new(),
list_variables: HashSet::new(),
map_variables: HashSet::new(),
file_variables: HashSet::new(),
timer_variables: HashSet::new(),
allocated_variables: HashSet::new(),
scalar_types: HashMap::new(),
function_param_counts: HashMap::new(),
value_typed_names: HashSet::new(),
list_mixed: HashSet::new(),
map_value_type: HashMap::new(),
loop_depth: 0,
shared_mode: false,
current_library: None,
pending_blank_line_truncation: None,
imports: Vec::new(),
warnings: Vec::new(),
}
}
pub fn with_source(mut self, filename: &str, content: &str) -> Self {
self.source_file = Some(SourceFile::new(filename, content));
self
}
pub fn with_shared_mode(mut self, enabled: bool) -> Self {
self.shared_mode = enabled;
self
}
/// Register the functions imported by the program's `see ... from
/// "*.lib"` statements (already parsed and .dynsym-verified by the
/// driver). Names are authorship-level here: `imports` is matched by the
/// authored name, and the `<lib>_<ver>_<func>` label only matters to the
/// codegen, which gets the same list.
pub fn with_imports(mut self, imports: Vec<crate::lib_file::ImportedFunction>) -> Self {
self.imports = imports;
self
}
/// The key under which a function DEFINED in the current library is filed
/// in the per-function tables: the `<lib>_<ver>_<func>` mangled label in
/// shared mode (with an identity set), else `mangle_symbol(name)`. This is
/// the same rule codegen's `function_label` uses, so the two agree on a
/// function's identity and a call that the analyzer accepts also resolves
/// at the call site. Reads `current_library`, which the statement walk sets
/// as it passes each `Library` declaration.
fn func_key(&self, name: &str) -> String {
crate::codegen::make_function_label(self.shared_mode, self.current_library.as_ref(), name)
}
pub fn analyze(&mut self, program: &mut Program) {
// A shared library has no `_start`, so top-level executable statements
// would be generated into the discarded main body and silently dropped.
// Reject them before any other analysis so the author gets one clear
// diagnostic instead of a confusing cascade. Only function definitions,
// `Library`, and `see` may appear at the top level of a library.
if self.shared_mode {
for stmt in &program.statements {
if !matches!(
stmt,
Statement::FunctionDef { .. } | Statement::LibraryDecl { .. } | Statement::See { .. }
) {
self.push_error(
format!(
"Top-level {} is not allowed in a shared library: only function \
definitions, 'Library', and 'see' may appear at the top level.",
shared_top_level_label(stmt)
),
// No source location: `Statement` carries no span (see
// plan 210 P3). The only location mechanism here is
// `find_symbol_location`, a text search keyed on a
// symbol name; a top-level print/if/while/exit has no
// name, and even the name-bearing kinds (assignment,
// call) would resolve to the first textual occurrence
// of that name anywhere in the file — usually inside a
// function body, i.e. a misleading line. A real fix
// needs spans threaded into the Statement AST (the
// parser has token positions but discards them), which
// is separate work.
None,
);
return;
}
}
// A `--shared` compile with no `Library` declaration has no
// identity: there is no mangling (so two libraries in one .so
// could not both define `greet`) and no name/version for the
// `.lib` A3 writes. Reject it before codegen, naming the
// missing declaration so the author knows exactly what to add.
if !program
.statements
.iter()
.any(|s| matches!(s, Statement::LibraryDecl { .. }))
{
self.push_error(
"A shared library must declare its identity with a `Library` \
declaration giving its name and version — without one there is \
no mangling and no `.lib`. Add `Library name version \
\"x.y\".` before the function definitions and rebuild with \
--shared."
.to_string(),
// No source location: this reports an ABSENCE of a
// declaration, so there is no offending statement to anchor
// `find_symbol_location` on (plan 210 P3). A spanned AST
// would let this point at the file's first line; until then
// it stays a message-only diagnostic, deliberately.
None,
);
return;
}
// A `--shared` compile with no function definitions exports
// nothing, so the version script main.rs writes comes out as
// `{ global: local:*; };` — empty between `global:` and
// `local:`. `ld` rejects that with "syntax error in VERSION
// script", which tells the author nothing about what they
// actually did wrong. Reject it here, at the same standard as
// the top-level-statement diagnostic above, before codegen ever
// writes the script.
if !program
.statements
.iter()
.any(|s| matches!(s, Statement::FunctionDef { .. }))
{
self.push_error(
"A shared library must export at least one function, but this \
file defines none. Add a function definition, or drop --shared \
to build an executable."
.to_string(),
// No source location: this reports an ABSENCE of function
// definitions, so there is no offending statement and no
// symbol to anchor `find_symbol_location` on (plan 210 P3).
// Spanning the Statement AST would let this point at the
// file/first line; until then it stays a message-only
// diagnostic, deliberately.
None,
);
return;
}
}
// First pass: collect function definitions, global declarations, and flag schemas.
let mut explicit_parse_seen = false;
// Definite declarations - including names declared in EVERY branch
// of an if/otherwise chain - behave as globals: they exist on all
// control-flow paths, so functions may reference them and code
// after the branch may use them. Names declared in only SOME
// branches stay out of this set; the guard tracking below owns
// those and reports cross-guard usage.
for (name, kind) in collect_definite_decls(&program.statements) {
self.global_variables.insert(name.clone());
match kind {
DefiniteDeclKind::Buffer => { self.buffer_variables.insert(name); }
DefiniteDeclKind::List => { self.list_variables.insert(name); }
DefiniteDeclKind::Map => { self.map_variables.insert(name); }
DefiniteDeclKind::File => { self.file_variables.insert(name); }
DefiniteDeclKind::Plain => {}
}
}
// Track the library identity as we walk so each function is filed under
// its OWN `<lib>_<ver>_<func>` key (a local, not `self.current_library`,
// so this pre-pass does not disturb the identity the second-pass walk
// manages). This scopes `functions`/`function_param_counts`: two
// libraries in one .so each defining `greet` get distinct keys, so a
// call in library A does not match library B's `greet`.
let mut current_lib: Option<(String, String)> = None;
for stmt in &program.statements {
match stmt {
Statement::LibraryDecl { name, version } => {
current_lib = Some((name.clone(), version.clone()));
}
Statement::FunctionDef { name, params, .. } => {
let key = crate::codegen::make_function_label(
self.shared_mode,
current_lib.as_ref(),
name,
);
self.functions.insert(key.clone());
self.function_param_counts.insert(key, params.len());
}
Statement::FlagSchemaDecl { name, .. } => {
self.flag_variables.insert(name.clone());
self.global_variables.insert(name.clone());
if explicit_parse_seen {
self.push_error(
"Cannot declare new flags after 'parse flags.'".to_string(),
Some(name),
);
}
}
Statement::ParseFlags => {
if explicit_parse_seen {
self.push_error("Duplicate 'parse flags.' statement".to_string(), None);
}
explicit_parse_seen = true;
}
_ => {}
}
}
// Stage A4 shadow rule: a local definition wins over a same-named
// import — but never silently. Warn once per (function, library)
// pair, naming the shadowed library, so adding a `see` can never
// redirect an existing call without a diagnostic. Order-independent:
// functions and imports are both fully collected before this runs.
if !self.imports.is_empty() {
let mut warned: HashSet<(String, String, String)> = HashSet::new();
for stmt in &program.statements {
if let Statement::FunctionDef { name, .. } = stmt {
for imp in &self.imports {
if imp.name != *name {
continue;
}
let key = (name.clone(), imp.lib.clone(), imp.version.clone());
if warned.insert(key) {
self.warnings.push(format!(
"'{}' is defined in this program and also exported by \
library \"{}\" version \"{}\"; the local definition wins — \
calls to '{}' resolve to it, not to the library.",
name, imp.lib, imp.version, name
));
}
}
}
}
}
let parse_point = if explicit_parse_seen {
program
.statements
.iter()
.position(|s| matches!(s, Statement::ParseFlags))
.map(|i| i + 1)
.unwrap_or(0)
} else {
program
.statements
.iter()
.rposition(|s| matches!(s, Statement::FlagSchemaDecl { .. }))
.map(|i| i + 1)
.unwrap_or(0)
};
for stmt in program.statements.iter().take(parse_point) {
if matches!(stmt, Statement::FlagSchemaDecl { .. } | Statement::ParseFlags) {
continue;
}
if let Some(flag_name) = self.statement_uses_flag(stmt) {
self.push_error(
format!("Flag variable '{}' is used before flags are parsed", flag_name),
Some(&flag_name),
);
}
}
self.variables = self.global_variables.clone();
// Second pass: analyze all statements
for stmt in &program.statements {
self.analyze_statement(stmt);
}
// Third pass: check for typos in unknown identifiers
self.check_for_typos();
program.uses_io = self.deps.uses_io;
program.uses_heap = self.deps.uses_heap;
program.uses_strings = self.deps.uses_strings;
program.uses_args = self.deps.uses_args;
}
fn check_for_typos(&mut self) {
let unknown: Vec<String> = self.typo_candidates.iter().cloned().collect();
let mut typo_errors = Vec::new();
for id in unknown {
// Skip if this identifier already has an error
if self.errors.iter().any(|e| e.message.contains(&id)) {
continue;
}
// Skip common internal identifiers
if id.starts_with('_') || id == "stdin" || id == "stdout" || id == "stderr" {
continue;
}
if let Some(suggestion) = find_similar_keyword(&id, ENGLISH_KEYWORDS) {
let mut err = CompileError::new(&format!("Unknown identifier '{}'", id))
.with_suggestion(&suggestion);
if let Some(loc) = self.find_symbol_location(&id, 0) {
err = err.with_location(loc);
}
typo_errors.push(err);
}
}
// Prepend typo errors so they appear first
typo_errors.append(&mut self.errors);
self.errors = typo_errors;
}
fn track_identifier(&mut self, name: &str) {
self.used_identifiers.insert(name.to_string());
}
fn track_typo_candidate(&mut self, name: &str) {
self.typo_candidates.insert(name.to_string());
}
fn expr_uses_flag(&self, expr: &Expr) -> Option<String> {
match expr {
Expr::Identifier(name) => {
if self.flag_variables.contains(name) {
Some(name.clone())
} else {
None
}
}
Expr::FormatString { parts } => {
for part in parts {
match part {
FormatPart::Variable { name, .. } => {
if self.flag_variables.contains(name) {
return Some(name.clone());
}
}
FormatPart::Expression { expr, .. } => {
if let Some(name) = self.expr_uses_flag(expr) {
return Some(name);
}
}
FormatPart::Literal(_) => {}
}
}
None
}
Expr::BinaryOp { left, right, .. } => self.expr_uses_flag(left).or_else(|| self.expr_uses_flag(right)),
Expr::UnaryOp { operand, .. } => self.expr_uses_flag(operand),
Expr::Range { start, end, .. } => self.expr_uses_flag(start).or_else(|| self.expr_uses_flag(end)),
Expr::PropertyCheck { value, .. } => self.expr_uses_flag(value),
Expr::TypeCheck { value, .. } => self.expr_uses_flag(value),
Expr::FunctionCall { args, .. } => args.iter().find_map(|a| self.expr_uses_flag(a)),
Expr::ListLit { elements } => elements.iter().find_map(|e| self.expr_uses_flag(e)),
Expr::MapLit { pairs } => pairs.iter().find_map(|(k, v)| {
self.expr_uses_flag(k).or_else(|| self.expr_uses_flag(v))
}),
Expr::MapAccess { key, .. } => self.expr_uses_flag(key),
Expr::ListAccess { list, index } => self.expr_uses_flag(list).or_else(|| self.expr_uses_flag(index)),
Expr::ByteAccess { buffer, index } => self.expr_uses_flag(buffer).or_else(|| self.expr_uses_flag(index)),
Expr::ElementAccess { list, index } => self.expr_uses_flag(list).or_else(|| self.expr_uses_flag(index)),
Expr::Cast { value, .. } => self.expr_uses_flag(value),
Expr::DurationCast { value, .. } => self.expr_uses_flag(value),
Expr::TreatingAs { value, match_value, replacement } => self
.expr_uses_flag(value)
.or_else(|| self.expr_uses_flag(match_value))
.or_else(|| self.expr_uses_flag(replacement)),
Expr::ArgumentAt { index } => self.expr_uses_flag(index),
Expr::EnvironmentVariable { name } => self.expr_uses_flag(name),
Expr::EnvironmentVariableAt { index } => self.expr_uses_flag(index),
Expr::EnvironmentVariableExists { name } => self.expr_uses_flag(name),
_ => None,
}
}
fn statement_uses_flag(&self, stmt: &Statement) -> Option<String> {
match stmt {
Statement::Print { value, .. } => self.expr_uses_flag(value),
Statement::VarDecl { value, .. } => value.as_ref().and_then(|v| self.expr_uses_flag(v)),
Statement::Assignment { value, .. } => self.expr_uses_flag(value),
Statement::If { condition, then_block, else_if_blocks, else_block } => {
self.expr_uses_flag(condition)
.or_else(|| then_block.iter().find_map(|s| self.statement_uses_flag(s)))
.or_else(|| else_if_blocks.iter().find_map(|(c, b)| self.expr_uses_flag(c).or_else(|| b.iter().find_map(|s| self.statement_uses_flag(s)))))
.or_else(|| else_block.as_ref().and_then(|b| b.iter().find_map(|s| self.statement_uses_flag(s))))
}
Statement::While { condition, body } => self
.expr_uses_flag(condition)
.or_else(|| body.iter().find_map(|s| self.statement_uses_flag(s))),
Statement::ForRange { range, body, .. } => self
.expr_uses_flag(range)
.or_else(|| body.iter().find_map(|s| self.statement_uses_flag(s))),
Statement::ForEach { collection, body, .. } => self
.expr_uses_flag(collection)
.or_else(|| body.iter().find_map(|s| self.statement_uses_flag(s))),
Statement::Repeat { count, body } => self
.expr_uses_flag(count)
.or_else(|| body.iter().find_map(|s| self.statement_uses_flag(s))),
Statement::Return { value, .. } => value.as_ref().and_then(|v| self.expr_uses_flag(v)),
Statement::Exit { code } => self.expr_uses_flag(code),
Statement::Allocate { size, .. } => self.expr_uses_flag(size),
Statement::ByteSet { index, value, .. } => self.expr_uses_flag(index).or_else(|| self.expr_uses_flag(value)),
Statement::ElementSet { index, value, .. } => self.expr_uses_flag(index).or_else(|| self.expr_uses_flag(value)),
Statement::MapSet { key, value, .. } => self.expr_uses_flag(key).or_else(|| self.expr_uses_flag(value)),
Statement::ListAppend { value, .. } => self.expr_uses_flag(value),
Statement::FileOpen { path, .. } => self.expr_uses_flag(path),
Statement::FileWrite { value, .. } => self.expr_uses_flag(value),
Statement::OnError { actions } => actions.iter().find_map(|a| self.statement_uses_flag(a)),
Statement::BufferResize { new_size, .. } => self.expr_uses_flag(new_size),
Statement::FunctionCall { args, .. } => args.iter().find_map(|a| self.expr_uses_flag(a)),
Statement::Wait { duration, .. } => self.expr_uses_flag(duration),
_ => None,
}
}
/// Core of `find_write_site_location`/`find_bind_site_location`: search
/// `patterns` in order, skipping `exclude_line` (the declaration, when
/// known) and requiring a left word boundary so a shorter name doesn't
/// match as a suffix of a longer one (symbol "x", pattern "x is "
/// matching inside "max is " - each pattern's own trailing space
/// already enforces the right boundary). `guard_against_called`
/// additionally excludes a match immediately preceded by "called " -
/// the canonical declaration syntax `a <type> called X is <value>.`
/// contains `X is ` right after it, so an "X is "-shaped pattern needs
/// this guard as a second line of defence alongside `exclude_line`
/// (which only covers the *recorded* declaration line, e.g. if a
/// declaration and something else ever shared one line). A
/// construct-specific pattern that legitimately targets "called X"
/// itself (`FileOpen`'s own syntax) must pass `false` here so it does
/// not exclude its own match.
/// Search `patterns` (each expected to contain `symbol` as a
/// substring) for the statement that binds/writes `symbol`, returning
/// the location of `symbol` itself within the match - not the
/// pattern's own start. That distinction matters: a pattern like
/// `"Set {symbol} to "` has the symbol sitting *inside* it, offset by
/// `len("Set ")`, so anchoring on the pattern's start would draw the
/// caret under `Set` while claiming to point at the variable. Boundary
/// checks (word boundary on both sides of `symbol`, and optionally
/// "not immediately preceded by `called `") are applied around the
/// symbol's own span for the same reason - a boundary check anchored on
/// the pattern's start protects the wrong substring whenever the symbol
/// isn't at offset 0.
fn find_pattern_location(
&self,
symbol: &str,
patterns: &[String],
occurrence: usize,
exclude_line: Option<usize>,
guard_against_called: bool,
) -> Option<SourceLocation> {
let source = self.source_file.as_ref()?;
for pattern in patterns {
let Some(name_offset) = pattern.find(symbol) else {
continue;
};
let mut seen = 0usize;
for (idx, line) in source.content.lines().enumerate() {
let line_no = idx + 1;
if Some(line_no) == exclude_line {
continue;
}
let mut search_from = 0usize;
while let Some(rel) = line[search_from..].find(pattern.as_str()) {
let pat_col = search_from + rel;
let name_col = pat_col + name_offset;
let name_end = name_col + symbol.len();
let left_ok = name_col == 0 || {
let prev = line.as_bytes()[name_col - 1];
!(prev.is_ascii_alphanumeric() || prev == b'_')
};
let right_ok = line
.as_bytes()
.get(name_end)
.is_none_or(|b| !(b.is_ascii_alphanumeric() || *b == b'_'));
let excluded_by_called = guard_against_called && line[..pat_col].ends_with("called ");
if left_ok && right_ok && !excluded_by_called {
if seen == occurrence {
return Some(SourceLocation::new(&source.filename, line_no, name_col + 1, line));
}
seen += 1;
}
search_from = pat_col + 1;
}
}
}
None
}
/// Like `find_symbol_location`, but for pointing at the specific
/// statement that *writes* to `symbol` (`Set symbol to ...` / `symbol is
/// ...` / `the symbol is ...`), not just any occurrence of the name.
/// `find_symbol_location`'s own preference order (`{symbol` first, for
/// format-string interpolation) is wrong here: a name that also appears
/// in an unrelated `Print "{n}"` elsewhere in the file would anchor the
/// type-lock error there instead of at the offending assignment.
fn find_write_site_location(&self, symbol: &str, occurrence: usize) -> Option<SourceLocation> {
let decl_line = self.declared_locations.get(symbol).map(|l| l.line);
let write_patterns = [
format!("Set {} to ", symbol),
format!("the {} is ", symbol),
format!("{} is ", symbol),
];
self.find_pattern_location(symbol, &write_patterns, occurrence, decl_line, true)
.or_else(|| self.find_symbol_location(symbol, occurrence))
}
/// Like `find_write_site_location`, for a statement that *binds* `name`
/// through some construct-specific syntax rather than `is`/`to`
/// (a for-range/for-each loop header, `open ... called X`, `Allocate N
/// for X`). `patterns` are the construct's own syntax fragments
/// (e.g. `"each {name} "`, `"called {name} "`); `guard_against_called`
/// should be `false` when a pattern itself targets `"called X"`; a
/// caller doing that must instead disambiguate the declaration via
/// `exclude_line`.
fn find_bind_site_location(
&self,
symbol: &str,
patterns: &[String],
occurrence: usize,
guard_against_called: bool,
) -> Option<SourceLocation> {
let decl_line = self.declared_locations.get(symbol).map(|l| l.line);
self.find_pattern_location(symbol, patterns, occurrence, decl_line, guard_against_called)
.or_else(|| self.find_symbol_location(symbol, occurrence))
}
/// Where `name` was declared, for `declared_locations`. Deliberately
/// does NOT use `find_symbol_location`: that function prefers `{name`
/// (format-string interpolation) as its first pattern, which is right
/// for "where is this name used" but wrong here - a `Print "{src}"`
/// anywhere in the file would outrank the actual `a text called src
/// is ...` declaration, since interpolation is usually textually
/// earlier or just as likely to hit occurrence 0. Tries the `called
/// NAME` declaration syntax first (typed declarations, `Allocate`,
/// `FileOpen`, ...), then falls back to bare/loop-header forms that
/// have no `called` keyword at all (`NAME is <value>.`, `each NAME `).
fn find_declaration_location(&self, name: &str) -> Option<SourceLocation> {
let called_patterns = [format!("called {} is", name), format!("called {} ", name)];
self.find_pattern_location(name, &called_patterns, 0, None, false)
.or_else(|| {
let bare_patterns = [format!("{} is ", name), format!("each {} ", name)];
self.find_pattern_location(name, &bare_patterns, 0, None, false)
})
.or_else(|| self.find_symbol_location(name, 0))
}
fn find_symbol_location(&self, symbol: &str, occurrence: usize) -> Option<SourceLocation> {
let source = self.source_file.as_ref()?;
let preferred_patterns = [
format!("{{{}", symbol),
format!("\"{}\"", symbol),
symbol.to_string(),
];
for pattern in preferred_patterns {
let mut seen = 0usize;
for (idx, line) in source.content.lines().enumerate() {
if let Some(column) = line.find(&pattern) {
if seen == occurrence {
return Some(SourceLocation::new(
&source.filename,
idx + 1,
column + 1,
line,
));
}
seen += 1;
}
}
}
None
}
fn push_error(&mut self, message: String, symbol: Option<&str>) {
self.push_error_with_hint(message, symbol, None);
}
fn push_error_with_hint(&mut self, message: String, symbol: Option<&str>, hint: Option<&str>) {
let mut err = CompileError::new(&message);
if let Some(name) = symbol {
let occurrence = *self.symbol_error_counts.get(name).unwrap_or(&0);
if let Some(loc) = self.find_symbol_location(name, occurrence) {
err = err.with_location(loc);
}
self.symbol_error_counts.insert(name.to_string(), occurrence + 1);
}
if let Some(h) = hint {
err = err.with_hint(h);
}
self.errors.push(err);
}
fn push_unknown_variable(&mut self, name: &str) {
let hint = self.pending_blank_line_truncation.as_ref().and_then(|(func, params, loc)| {
if params.iter().any(|p| p == name) {
Some(format!(
"a blank line ended `{}`'s body early at line {} — a paragraph break closes all open clauses, including the enclosing function, so `{}` is no longer in scope here",
func, loc.line, name
))
} else {
None
}
});
self.push_error_with_hint(format!("Unknown variable: {}", name), Some(name), hint.as_deref());
}
/// Validate that a function call supplies exactly the number of
/// arguments the function declares. A mismatch previously compiled
/// to undefined runtime behaviour: too few arguments read stale
/// register values (silently using 0 or garbage), while too many
/// were silently dropped.
fn validate_function_call_args(&mut self, name: &str, args: &[Expr]) {
if let Some(&expected) = self.function_param_counts.get(&self.func_key(name)) {
if args.len() != expected {
self.push_error(
format!(
"Function '{}' expects {} argument{} but was called with {}.",
name,
expected,
if expected == 1 { "" } else { "s" },
args.len()
),
Some(name),
);
}
}
}
/// How a call to `name` resolves under Stage A4's import rules.
/// Local-first is deliberate: adding an unrelated `see` must never
/// silently redirect an existing call, so a local definition shadows a
/// same-named import (a pre-pass warning names the shadowed library).
/// Two imports exporting the same name are ambiguous by identity — a
/// re-see of the SAME <lib,version> is one import, but two different
/// libraries, or two versions of one library, are two.
fn imported_providers(&self, name: &str) -> Vec<&crate::lib_file::ImportedFunction> {
let mut providers: Vec<&crate::lib_file::ImportedFunction> = Vec::new();
for imp in &self.imports {
if imp.name != name {
continue;
}
if !providers
.iter()
.any(|p| p.lib == imp.lib && p.version == imp.version)
{
providers.push(imp);
}
}
providers
}
fn is_local_function(&self, name: &str) -> bool {
self.functions.contains(&self.func_key(name))
}
/// Plan 270 G4: a bare or quoted identifier in *expression* position
/// that names a zero-argument function is a call, not a variable lookup.
/// True iff `name` resolves to a callable declaring zero parameters — a
/// local function (looked up via `func_key`, so shared-mode mangling
/// matches the definition) or a single unambiguous import. A name that is
/// a variable in scope is decided by the caller *before* consulting this;
/// a variable shadows a same-named zero-arg function.
fn is_zero_arg_function(&self, name: &str) -> bool {
if self.is_local_function(name) {
return self.function_param_counts.get(&self.func_key(name)) == Some(&0);
}
// An imported function: only treat as a zero-arg call when exactly one
// library exports it (the same single-provider rule `check_function_call`
// applies); an ambiguous name is left for an explicit call to report.
let providers = self.imported_providers(name);
providers.len() == 1 && providers[0].params.is_empty()
}
/// Resolve and validate a call site shared by `Statement::FunctionCall`
/// and `Expr::FunctionCall`: local definition, then a single import (with
/// the same arity message as any other call, plus argument-type checks,
/// which an import needs at the call site because it has no body to fail
/// in), then ambiguity, then the existing unknown-function error.
fn check_function_call(&mut self, name: &str, args: &[Expr]) {
let providers = self.imported_providers(name);
if self.is_local_function(name) {
self.validate_function_call_args(name, args);
} else if providers.len() == 1 {
let import = providers[0].clone();
self.validate_import_call_args(&import, name, args);
} else if providers.len() > 1 {
let both = providers
.iter()
.map(|p| format!("library \"{}\" version \"{}\"", p.lib, p.version))
.collect::<Vec<_>>()
.join(" and ");
self.push_error(
format!(
"Call to '{}' is ambiguous: it is exported by {}. Vox never picks \
one by import order or by highest version — resolve it by defining \
a local '{}' (which shadows the imports, with a warning), or by \
renaming one library's export.",
name, both, name
),
Some(name),
);
} else {
let mut err = format!("Unknown function: {}", name);
if let Some(suggestion) = find_similar_keyword(name, ENGLISH_KEYWORDS) {
err.push_str(&format!(" (did you mean '{}'?)", suggestion));
}
self.push_error(err, Some(name));
}
}
/// Arity and argument-type validation for a call to an imported function.
/// The arity message is the same one any Vox call gets. Type validation
/// is static-only: an argument whose category is provably incompatible
/// with the declared parameter type is an error (an import has no body
/// whose arithmetic check would catch it, so the call site is the only
/// place it can be caught); a dynamically-typed argument is trusted, as
/// it is for local calls.
fn validate_import_call_args(
&mut self,
imp: &crate::lib_file::ImportedFunction,
name: &str,
args: &[Expr],
) {
let expected = imp.params.len();
if args.len() != expected {
self.push_error(
format!(
"Function '{}' expects {} argument{} but was called with {}.",
name,
expected,
if expected == 1 { "" } else { "s" },
args.len()
),
Some(name),
);
return;
}
for (i, arg) in args.iter().enumerate() {
let (pname, ptype) = &imp.params[i];
let Some(actual) = self.static_expr_category(arg) else {
continue; // dynamically typed — trusted, as local calls are
};
if !Self::param_accepts(ptype, &actual) {
self.push_error(
format!(
"Function '{}' (library \"{}\" version \"{}\") expects a {} \
for argument {} (\"{}\") but was called with {}.",
name,
imp.lib,
imp.version,
Self::type_noun(ptype),
i + 1,
pname,
Self::type_noun(&actual)
),
Some(name),
);
}
}
}
/// The provable type category of an argument expression, if there is one:
/// literals always, identifiers only when their tracked category is
/// definite. Anything dynamic (a `value`, a call result, an expression)
/// is `None` and skipped by the import type check.
fn static_expr_category(&self, e: &Expr) -> Option<Type> {
match e {
Expr::IntegerLit(_) => Some(Type::Integer),
Expr::FloatLit(_) => Some(Type::Float),
Expr::StringLit(_) => Some(Type::String),
Expr::BoolLit(_) => Some(Type::Boolean),
Expr::Identifier(name) => {
if let Some(t) = self.scalar_types.get(name) {
return Some(t.clone());
}
if self.buffer_variables.contains(name.as_str()) {
Some(Type::Buffer)
} else if self.list_variables.contains(name.as_str()) {
Some(Type::List(Box::new(Type::Unknown)))
} else if self.map_variables.contains(name.as_str()) {
Some(Type::Map(Box::new(Type::Unknown)))
} else if self.file_variables.contains(name.as_str()) {
Some(Type::File)
} else {
None
}
}
_ => None,
}
}
/// Whether a statically-known argument category may go to a parameter of
/// the declared type. Booleans ride as numbers in the ABI (0/1) and file
/// parameters accept number-like handles, so the rejects are the true
/// category clashes: pointers where scalars are expected and the reverse.
fn param_accepts(param: &Type, actual: &Type) -> bool {
use Type::*;
match param {
Integer | Float => !matches!(actual, String | File | Buffer | List(_) | Map(_)),
String => matches!(actual, String),
Boolean => !matches!(actual, String | File | Buffer | List(_) | Map(_)),
File => !matches!(actual, String | Boolean | Buffer | List(_) | Map(_)),
Buffer => matches!(actual, Buffer),
List(_) => matches!(actual, List(_)),
Map(_) => matches!(actual, Map(_)),
// A `value` parameter takes any category (its tag rides alongside).
Value | Void | Unknown | Time | Timer => true,
}
}
fn type_noun(t: &Type) -> &'static str {
match t {
Type::Integer | Type::Float => "number",
Type::String => "text",
Type::Boolean => "boolean",
Type::File => "file",
Type::Buffer => "buffer",
Type::List(_) => "list",
Type::Map(_) => "map",
Type::Value => "value",
_ => "value",
}
}
fn current_env(&self) -> AnalysisEnv {
AnalysisEnv {
always: self.variables.clone(),
guarded: self.guarded_scopes.clone(),
}
}
fn apply_env(&mut self, env: &AnalysisEnv) {
self.variables = env.always.clone();
self.guarded_scopes = env.guarded.clone();
}
fn is_variable_available(&self, name: &str) -> bool {
if self.variables.contains(name) {
return true;
}
self.active_guards.iter().any(|guard| {
self.guarded_scopes
.get(guard)
.map(|vars| vars.contains(name))
.unwrap_or(false)
})
}
fn declare_variable_in_current_scope(&mut self, name: &str) {
if name.starts_with('_') {
self.push_error(
format!(
"Variable name '{}' starts with '_', which is reserved for \
the Vox runtime; choose a name without the leading underscore.",
name
),
Some(name),
);
}
if self.active_guards.is_empty() {
self.variables.insert(name.to_string());
} else {
for guard in &self.active_guards {
self.guarded_scopes
.entry(guard.clone())
.or_default()
.insert(name.to_string());
}
}
}
fn merge_continuing_envs(&self, envs: &[AnalysisEnv], fallback: &AnalysisEnv) -> AnalysisEnv {
if envs.is_empty() {
return fallback.clone();
}
let mut merged_always = envs[0].always.clone();
for env in envs.iter().skip(1) {
merged_always.retain(|name| env.always.contains(name));
}
let mut merged_guarded: HashMap<String, HashSet<String>> = HashMap::new();
for env in envs {
for (guard, vars) in &env.guarded {
merged_guarded
.entry(guard.clone())
.or_default()
.extend(vars.iter().cloned());
}
}
AnalysisEnv {
always: merged_always,
guarded: merged_guarded,
}
}
fn simple_guard_key(condition: &Expr) -> Option<String> {
match condition {
Expr::Identifier(name) => Some(name.clone()),
Expr::StringLit(name) => Some(name.clone()),
Expr::UnaryOp { op: UnaryOperator::Not, operand } => {
Self::simple_guard_key(operand).map(|k| format!("not ({})", k))
}
Expr::BinaryOp { left, op, right } => {
let connector = match op {
BinaryOperator::And => "and",
BinaryOperator::Or => "or",
_ => return None,
};
let left_key = Self::simple_guard_key(left)?;
let right_key = Self::simple_guard_key(right)?;
Some(format!("({}) {} ({})", left_key, connector, right_key))
}
_ => None,
}
}
fn maybe_activate_true_guard(&mut self, name: &str, var_type: &Option<Type>, value: &Option<Expr>) {
if self.block_depth == 0 {
return;
}
let is_bool_typed = var_type
.as_ref()
.map(|t| matches!(t, Type::Boolean))
.unwrap_or(true);
let is_true = matches!(value, Some(Expr::BoolLit(true)));
if is_bool_typed && is_true {
if !self.active_guards.iter().any(|g| g == name) {
self.active_guards.push(name.to_string());
}
self.guarded_scopes
.entry(name.to_string())
.or_default()
.insert(name.to_string());
}
}
fn analyze_block_in_scope(&mut self, block: &[Statement], input_env: &AnalysisEnv, active_guard: Option<&str>) -> (AnalysisEnv, bool) {
let saved_env = self.current_env();
let saved_guards = self.active_guards.clone();
let saved_block_depth = self.block_depth;
self.apply_env(input_env);
self.block_depth += 1;
if let Some(guard) = active_guard {
self.active_guards.push(guard.to_string());
}
let mut terminates = false;
for stmt in block {
self.analyze_statement(stmt);
if self.statement_always_terminates(stmt) {
terminates = true;
break;
}
}
let resulting_env = self.current_env();
self.block_depth = saved_block_depth;
self.active_guards = saved_guards;
self.apply_env(&saved_env);
(resulting_env, terminates)
}
fn block_always_terminates(&self, block: &[Statement]) -> bool {
for stmt in block {
if self.statement_always_terminates(stmt) {
return true;
}
}
false
}
fn is_buffer_variable(&self, name: &str) -> bool {
self.buffer_variables.contains(name)
}
fn is_list_variable(&self, name: &str) -> bool {
self.list_variables.contains(name)
}
fn is_map_variable(&self, name: &str) -> bool {
self.map_variables.contains(name)
}
/// A "scalar" variable holds a raw 64-bit value (a number, a boolean
/// flag, or a unix timestamp) rather than a pointer or handle. Number
/// and time properties read the raw slot, so applying them to a
/// buffer/list/file/timer loads a pointer or fd and yields garbage.
fn is_scalar_variable(&self, name: &str) -> bool {
!self.is_buffer_variable(name)
&& !self.is_list_variable(name)
&& !self.is_map_variable(name)
&& !self.file_variables.contains(name)
&& !self.timer_variables.contains(name)
&& !self.allocated_variables.contains(name)
}
/// Resolve a named reference (an `Identifier` or a quoted-name `StringLit`)
/// to its tracked category. Buffer/list/file/timer/flag are detected from
/// their dedicated sets; otherwise the dynamic `scalar_types` map supplies
/// the current number/float/text/boolean category. Returns None for an
/// unknown or untracked name (treated as "allow" by the arithmetic check to
/// avoid false positives).
fn named_value_type(&self, name: &str) -> Option<Type> {
if self.is_buffer_variable(name) {
Some(Type::Buffer)
} else if self.is_list_variable(name) {
Some(Type::List(Box::new(Type::Unknown)))
} else if self.is_map_variable(name) {
Some(Type::Map(Box::new(Type::Unknown)))
} else if self.file_variables.contains(name) {
Some(Type::File)
} else if self.timer_variables.contains(name) {
Some(Type::Timer)
} else if self.flag_variables.contains(name) {
Some(Type::Boolean)
} else {
self.scalar_types.get(name).cloned()
}
}
/// Classify an expression's value category for the arithmetic type check.
/// Returns the type, or None when it cannot be determined statically
/// (function calls, property/element/byte access) - None means "allow",
/// biasing against false positives. A bare text literal or a text variable
/// resolves to `Type::String`; a cast resolves to its target type, so
/// `s as a number` is accepted while bare `s` (text) is rejected.
fn arithmetic_operand_type(&self, expr: &Expr) -> Option<Type> {
match expr {
Expr::IntegerLit(_)
| Expr::LastError
| Expr::ArgumentCount
| Expr::EnvironmentVariableCount => Some(Type::Integer),
Expr::FloatLit(_) => Some(Type::Float),
Expr::BoolLit(_) => Some(Type::Boolean),
Expr::StringLit(s) => {
// A quoted name may reference a variable; otherwise this is a
// bare text literal, which is not valid in arithmetic.
if self.value_typed_names.contains(s) {
Some(Type::Value)
} else {
self.named_value_type(s).or(Some(Type::String))
}
}
Expr::FormatString { .. } => Some(Type::String),
Expr::Identifier(name) => {
// A `value`-typed name is dynamic: reject it from arithmetic
// until the author checks its type with a predicate (stage 1c).
if self.value_typed_names.contains(name) {
Some(Type::Value)
} else {
self.named_value_type(name)
}
}
Expr::Cast { target_type, .. } => Some(target_type.clone()),
Expr::DurationCast { .. } => Some(Type::Integer),
Expr::UnaryOp { op, operand } => match op {
UnaryOperator::Negate => self.arithmetic_operand_type(operand),
UnaryOperator::Not => Some(Type::Boolean),
},
Expr::BinaryOp { op, left, right } => match op {
BinaryOperator::Equal
| BinaryOperator::NotEqual
| BinaryOperator::Greater
| BinaryOperator::Less
| BinaryOperator::GreaterEqual
| BinaryOperator::LessEqual
| BinaryOperator::And
| BinaryOperator::Or => Some(Type::Boolean),
_ => {
// Arithmetic result: float if either operand is float, else
// integer. Nested operands are checked separately when
// analyze_expr recurses into them.
if matches!(self.arithmetic_operand_type(left), Some(Type::Float))
|| matches!(self.arithmetic_operand_type(right), Some(Type::Float))
{
Some(Type::Float)
} else {
Some(Type::Integer)
}
}
},
// Plan 294 findings 4, 14: only resolvable when the map's own
// literal initializer proved a single value type (see
// `map_value_type`) - a map declared with a non-literal
// initializer, an empty literal, or a literal with mixed value
// types falls through to `None`, same "can't prove it, allow
// it" policy as everywhere else in this function.
Expr::MapAccess { map, .. } => self.map_value_type.get(map).cloned(),
_ => None,
}
}
/// A short, human-readable label for an operand, used in error messages.
fn operand_label(&self, expr: &Expr) -> String {
match expr {
Expr::Identifier(name) => name.clone(),
Expr::StringLit(s) => {
if self.is_variable_available(s) {
s.clone()
} else {
format!("\"{}\"", s)
}
}
_ => "this value".to_string(),
}
}
/// Reject text/buffer/list/file/timer operands in arithmetic. Without an
/// explicit cast these compile to pointer/handle arithmetic and produce
/// garbage at runtime; a cast (`s as a number`) routes through atoi/atof
/// and is accepted because `arithmetic_operand_type` resolves it to a
/// numeric type.
fn check_arithmetic_operand(&mut self, expr: &Expr) {
// `nothing` has no numeric value. It is not a `Type` (tag 6 exists
// only at runtime), so it is matched here rather than through
// `arithmetic_operand_type`. Unchecked it compiles to its payload, 0,
// so `total add missing` silently yields `total` - a wrong number that
// looks right, which is the failure this whole track exists to stop.
// Operands that only turn out to be nothing at runtime cannot be
// caught here; those set the error flag instead (see
// `emit_nothing_operand_check` in codegen).
if matches!(expr, Expr::NothingLit) {
self.push_error(
"Cannot use nothing in arithmetic; check it with 'is nothing' first."
.to_string(),
None,
);
return;
}
let Some(ty) = self.arithmetic_operand_type(expr) else {
return;
};
let label = self.operand_label(expr);
let msg = match ty {
Type::String => format!(
"Cannot use text {} in arithmetic; cast it first with 'as a number' or 'as a float'.",
label
),
Type::Buffer => format!(
"Cannot use buffer {} in arithmetic; cast it with 'as a number' to read its content.",
label
),
Type::List(_) => format!("Cannot use list {} in arithmetic.", label),
Type::Map(_) => format!("Cannot use map {} in arithmetic.", label),
Type::File => format!("Cannot use file {} in arithmetic.", label),
Type::Timer => format!("Cannot use timer {} in arithmetic.", label),
// Deliberately naming no escape hatch, after two rounds of
// getting this wrong: "check its type with 'is a number'
// first" was a dead end (a type-predicate guard does not
// narrow the type inside its own body - still rejected there
// too), and "convert it explicitly with 'as a number'" was
// ALSO a dead end once finding 21's fix made exactly that cast
// a compile error (plan 294 finding 21 - casting a
// dynamically-tagged value doesn't dispatch on the runtime tag
// in codegen, so it used to silently compute garbage; rejecting
// it was the fix, but this message kept sending people to it
// anyway). This is the value-typed case by construction - it
// is the ONLY way this branch fires - so every occurrence of
// this message hits both dead ends the same way, every time.
// There is currently no supported way to use a dynamically-
// tagged value in arithmetic; say only that, since a plausible-
// sounding but unverified alternative is worse than none (that
// is exactly how the previous two wordings went wrong).
Type::Value => format!(
"Cannot use a value {} in arithmetic: its type is only known at runtime, and arithmetic on a dynamically-tagged value is not currently supported.",
label
),
_ => return,
};
self.push_error(msg, None);
}
/// Arithmetic/bitwise operators require numeric operands. Comparisons and
/// logical and/or are excluded (they are valid across types and handled
/// elsewhere).
fn is_arithmetic_op(&self, op: &BinaryOperator) -> bool {
matches!(
op,
BinaryOperator::Add
| BinaryOperator::Subtract
| BinaryOperator::Multiply
| BinaryOperator::Divide
| BinaryOperator::Modulo
| BinaryOperator::BitAnd
| BinaryOperator::BitOr
| BinaryOperator::BitXor
| BinaryOperator::ShiftLeft
| BinaryOperator::ShiftRight
)
}
fn expr_integer_literal_value(&self, expr: &Expr) -> Option<i64> {
match expr {
Expr::IntegerLit(value) => Some(*value),
Expr::UnaryOp {
op: UnaryOperator::Negate,
operand,
} => {
if let Expr::IntegerLit(value) = operand.as_ref() {
value.checked_neg()
} else {
None
}
}
_ => None,
}
}
fn validate_function_condition_variable_refs(&mut self, expr: &Expr) {
if !self.in_function_scope {
return;
}
match expr {
Expr::StringLit(name) => {
self.track_identifier(name);
if !self.is_variable_available(name) {
self.push_unknown_variable(name);
}
}
Expr::UnaryOp {
op: UnaryOperator::Not,
operand,
} => {
self.validate_function_condition_variable_refs(operand);
}
Expr::BinaryOp { left, right, .. } => {
self.validate_function_condition_variable_refs(left);
self.validate_function_condition_variable_refs(right);
}
_ => {}
}
}
fn infer_simple_expr_type(&self, expr: &Expr) -> Option<Type> {
match expr {
Expr::IntegerLit(_) | Expr::LastError | Expr::ArgumentCount | Expr::EnvironmentVariableCount => Some(Type::Integer),
Expr::FloatLit(_) => Some(Type::Float),
Expr::StringLit(_) | Expr::FormatString { .. }
| Expr::ArgumentName | Expr::ArgumentFirst | Expr::ArgumentSecond | Expr::ArgumentLast
| Expr::ArgumentAt { .. } | Expr::EnvironmentVariable { .. }
| Expr::EnvironmentVariableFirst | Expr::EnvironmentVariableLast
| Expr::EnvironmentVariableAt { .. } => Some(Type::String),
Expr::BoolLit(_) | Expr::ArgumentEmpty | Expr::EnvironmentVariableEmpty | Expr::EnvironmentVariableExists { .. }
| Expr::PropertyCheck { .. } | Expr::TypeCheck { .. } => Some(Type::Boolean),
Expr::ListLit { .. } | Expr::ArgumentAll | Expr::ArgumentRaw => Some(Type::List(Box::new(Type::Unknown))),
Expr::MapLit { .. } => Some(Type::Map(Box::new(Type::Unknown))),
Expr::Identifier(name) => {
if self.is_buffer_variable(name) {
Some(Type::Buffer)
} else if self.is_list_variable(name) {
Some(Type::List(Box::new(Type::Unknown)))
} else if self.is_map_variable(name) {
Some(Type::Map(Box::new(Type::Unknown)))
} else if self.flag_variables.contains(name) {
Some(Type::Boolean)
} else {
None
}
}
Expr::BinaryOp { op, left, right } => {
match op {
BinaryOperator::Equal | BinaryOperator::NotEqual
| BinaryOperator::Greater | BinaryOperator::Less
| BinaryOperator::GreaterEqual | BinaryOperator::LessEqual
| BinaryOperator::And | BinaryOperator::Or => Some(Type::Boolean),
_ => {
let left_ty = self.infer_simple_expr_type(left);
let right_ty = self.infer_simple_expr_type(right);
if matches!(left_ty, Some(Type::Float)) || matches!(right_ty, Some(Type::Float)) {
Some(Type::Float)
} else if matches!(left_ty, Some(Type::Integer)) && matches!(right_ty, Some(Type::Integer)) {
Some(Type::Integer)
} else {
None
}
}
}
}
Expr::UnaryOp { op, operand } => {
match op {
UnaryOperator::Negate => self.infer_simple_expr_type(operand),
UnaryOperator::Not => Some(Type::Boolean),
}
}
Expr::Cast { target_type, .. } => Some(target_type.clone()),
Expr::DurationCast { .. } => Some(Type::Integer),
Expr::TreatingAs { value, .. } => self.infer_simple_expr_type(value),
_ => None,
}
}
fn treating_types_compatible(&self, left: &Type, right: &Type) -> bool {
matches!(
(left, right),
(Type::Integer, Type::Integer)
| (Type::Float, Type::Float)
| (Type::String, Type::String)
| (Type::Boolean, Type::Boolean)
| (Type::Buffer, Type::Buffer)
| (Type::File, Type::File)
| (Type::Time, Type::Time)
| (Type::Timer, Type::Timer)
| (Type::List(_), Type::List(_))
| (Type::Map(_), Type::Map(_))
)
}
/// Classify a list-literal element for the finding-18 homogeneity
/// check. `None` means "can't prove a single tag" (an identifier,
/// function call, property/element access, `nothing`, ...) and is
/// treated as mixed by the caller - matching codegen's own
/// `TagInfo::Unknowable` policy of widening to mixed rather than
/// guessing when a value's tag can't be proven statically.
fn list_element_kind(&self, expr: &Expr) -> Option<Type> {
match expr {
Expr::StringLit(_) => Some(Type::String),
Expr::IntegerLit(_) => Some(Type::Integer),
Expr::FloatLit(_) => Some(Type::Float),
Expr::BoolLit(_) => Some(Type::Boolean),
Expr::ListLit { .. } => Some(Type::List(Box::new(Type::Unknown))),
Expr::MapLit { .. } => Some(Type::Map(Box::new(Type::Unknown))),
_ => None,
}
}
/// True iff a list literal's elements don't all share one provable
/// type - see `list_element_kind` and `list_mixed`.
fn list_literal_is_mixed(&self, elements: &[Expr]) -> bool {
let mut seen: Option<Type> = None;
for e in elements {
let Some(t) = self.list_element_kind(e) else {
return true;
};
match &seen {
None => seen = Some(t),
Some(prev) if !self.treating_types_compatible(prev, &t) => return true,
Some(_) => {}
}
}
false
}
/// The single provable value type shared by every pair in a map
/// literal (keys are always text and don't factor in), or `None` for
/// an empty map, a mixed one, or a value that isn't a simple literal.
/// See `map_value_type`'s doc comment for how this is used and its
/// limits.
fn map_literal_value_type(&self, pairs: &[(Expr, Expr)]) -> Option<Type> {
let mut seen: Option<Type> = None;
for (_, v) in pairs {
let t = self.list_element_kind(v)?;
match &seen {
None => seen = Some(t),
Some(prev) if !self.treating_types_compatible(prev, &t) => return None,
Some(_) => {}
}
}
seen
}
fn type_name(&self, ty: &Type) -> &'static str {
match ty {
Type::Integer => "number",
Type::Float => "float",
Type::String => "text",
Type::Boolean => "boolean",
Type::List(_) => "list",
Type::Map(_) => "map",
Type::Buffer => "buffer",
Type::File => "file",
Type::Time => "time",
Type::Timer => "timer",
Type::Value => "value",
Type::Void => "void",
Type::Unknown => "unknown",
}
}
/// Render a value expression back into Vox source syntax, for the
/// "help: convert it explicitly" suggestion. Only handles the simple
/// literal/identifier shapes that are common in a mismatched assignment;
/// anything else falls back to a generic placeholder rather than
/// fabricating source that wouldn't parse.
fn render_value_hint(&self, expr: &Expr) -> String {
match expr {
Expr::StringLit(s) => format!("\"{}\"", s),
Expr::IntegerLit(n) => n.to_string(),
Expr::FloatLit(n) => n.to_string(),
Expr::BoolLit(b) => if *b { "true".to_string() } else { "false".to_string() },
Expr::Identifier(name) => name.clone(),
_ => "<value>".to_string(),
}
}
/// Type-lock check: a concretely-typed variable's type is fixed at
/// declaration and never changes (the language owner's fix for the
/// whole "tracked type disagrees with runtime type" bug family - see
/// the plan 293 writeup). Reports a compile error naming the variable,
/// its declared type, the mismatched type, and the exact cast that
/// fixes it when `value`'s type is statically known to differ from
/// `name`'s declared type. Returns true iff an error was reported.
///
/// Deliberately permissive (returns false, i.e. "allow") when:
/// - `name` is `value`-typed (`self.value_typed_names`): that is the
/// language's sanctioned dynamic-type mechanism and must keep
/// accepting varying types.
/// - `name`'s declared type can't be resolved (untracked/unknown name -
/// some other check, e.g. unknown-variable, owns that case).
/// - `value`'s type can't be determined statically (function calls,
/// property/element access, etc.) - this mirrors the existing
/// `arithmetic_operand_type`/`check_arithmetic_operand` policy of
/// biasing against false positives when static inference runs out,
/// rather than requiring a full type-inference pass this task did not
/// ask for.
/// - `value`'s type resolves to `Type::Value` (a dynamically-typed
/// source flowing into a concretely-typed destination): the runtime
/// type isn't known until runtime, so this can't be verified
/// statically either, and there is no sanctioned narrowing syntax to
/// demand here.
/// - `name` is a buffer: `X is <value>.` / `Set X to <value>.` on a
/// buffer is a content write (format the value's text into the
/// buffer), not a type change - a buffer legitimately accepts a
/// number, text, or another buffer's contents this way, already
/// special-cased throughout the analyzer/codegen (e.g. the
/// `is_buffer_variable` exclusions the old `Statement::Assignment`
/// arm used before this check replaced it). Locking buffers here
/// would reject `a buffer called b is "".` / `b is 42.`, which must
/// keep working.
fn check_type_lock(&mut self, name: &str, value: &Expr) -> bool {
if self.value_typed_names.contains(name) || self.is_buffer_variable(name) {
return false;
}
let Some(declared) = self.named_value_type(name) else {
return false;
};
let Some(actual) = self.arithmetic_operand_type(value) else {
return false;
};
if matches!(actual, Type::Value) {
return false;
}
if self.treating_types_compatible(&declared, &actual) {
return false;
}
let occurrence = *self.symbol_error_counts.get(name).unwrap_or(&0);
let mut err = CompileError::new(&format!(
"cannot assign {} to '{}', which is a {}",
self.type_name(&actual),
name,
self.type_name(&declared)
));
if let Some(loc) = self.find_write_site_location(name, occurrence) {
err = err.with_underline_note(name.len().max(1), &format!("this assigns {}", self.typed_phrase(&actual)));
err = err.with_location(loc);
}
self.symbol_error_counts.insert(name.to_string(), occurrence + 1);
if let Some(decl_loc) = self.declared_locations.get(name) {
err = err.with_note_line(&format!(
"'{}' was declared as a {} at {}:{}:{}",
name,
self.type_name(&declared),
decl_loc.file,
decl_loc.line,
decl_loc.column
));
} else {
err = err.with_note_line(&format!("'{}' was declared as a {}", name, self.type_name(&declared)));
}
// Canonical Vox cast phrasing (LANGUAGE.md): `as a number` / `as a
// float` / `as a boolean` / `as a buffer`, but `as text` - no
// article - specifically for text.
let cast_target = if matches!(declared, Type::String) {
"text".to_string()
} else {
format!("a {}", self.type_name(&declared))
};
err = err.with_help_line(&format!(
"convert it explicitly: {} is {} as {}.",
name,
self.render_value_hint(value),
cast_target
));
self.errors.push(err);
// Poison the tracked type after reporting: the assignment was
// rejected, so `name` never actually took on the new type, but
// leaving the OLD type in place would make later, unrelated uses of
// `name` in this same (already-failing) compile cascade into a
// second, confusing error about the mistake that was just rejected
// (e.g. `z is s add 1` after a rejected `Set s to 7` re-flagging `s`
// as text in arithmetic). The program never reaches codegen once
// `self.errors` is non-empty, so this only affects which additional
// diagnostics get reported, not correctness.
self.scalar_types.remove(name);
true
}
/// `a {} number` / `text` / etc. - the article Vox's own cast syntax
/// uses (`as a number`, but `as text` with none). Shared by
/// `check_type_lock` and `bind_variable_type` so both error shapes
/// agree.
fn typed_phrase(&self, ty: &Type) -> String {
if matches!(ty, Type::String) {
"text".to_string()
} else {
format!("a {}", self.type_name(ty))
}
}
/// Statement-level binder for constructs that put a new runtime value
/// into `name` WITHOUT going through `Statement::Assignment`/`VarDecl`
/// - a for-range/for-each loop header, `open ... called X`, `Allocate N
/// for X`. A binding is not an assignment, but plan 294's audit found
/// six such sites still segfault under a rule enforced only on
/// assignment, because each one rebinds an existing name to a new
/// runtime value without updating (or checking) its tracked type. Same
/// rule, same rejection: if `name` is already declared with a type
/// incompatible with `new_type`, this is a compile error. If `name` is
/// new, this call IS the declaration - `new_type` becomes its locked
/// type, exactly as a `VarDecl` would set it.
///
/// `construct`/`bind_verb` describe the site in the error text (e.g.
/// "this for-range loop" / "counts with"). `patterns` locate the
/// binding statement for the caret, tried in order via
/// `find_bind_site_location`; `guard_against_called` must be `false`
/// when a pattern itself targets literal `"called X"` syntax (so it
/// does not exclude its own match - see that function's docs).
///
/// Exempt exactly like `check_type_lock`: `value`-typed names (the
/// sanctioned dynamic mechanism) and buffers (binding into a buffer is
/// a content write, not a type change).
fn bind_variable_type(
&mut self,
name: &str,
new_type: Type,
construct: &str,
bind_verb: &str,
patterns: &[String],
guard_against_called: bool,
) -> bool {
if self.value_typed_names.contains(name) || self.is_buffer_variable(name) {
return false;
}
let Some(declared) = self.named_value_type(name) else {
// A brand-new name: this binding is the declaration.
if matches!(new_type, Type::Integer | Type::Float | Type::Boolean | Type::String) {
self.scalar_types.insert(name.to_string(), new_type);
}
if !self.declared_locations.contains_key(name) {
if let Some(loc) = self.find_declaration_location(name) {
self.declared_locations.insert(name.to_string(), loc);
}
}
return false;
};
if self.treating_types_compatible(&declared, &new_type) {
return false;
}
let occurrence = *self.symbol_error_counts.get(name).unwrap_or(&0);
let mut err = CompileError::new(&format!(
"cannot bind '{}' to {} in {}; '{}' is already declared as {}",
name,
self.typed_phrase(&new_type),
construct,
name,
self.typed_phrase(&declared)
));
if let Some(loc) = self.find_bind_site_location(name, patterns, occurrence, guard_against_called) {
err = err.with_underline_note(
name.len().max(1),
&format!("this {} {}", bind_verb, self.typed_phrase(&new_type)),
);
err = err.with_location(loc);
}
self.symbol_error_counts.insert(name.to_string(), occurrence + 1);
if let Some(decl_loc) = self.declared_locations.get(name) {
err = err.with_note_line(&format!(
"'{}' was declared as {} at {}:{}:{}",
name,
self.typed_phrase(&declared),
decl_loc.file,
decl_loc.line,
decl_loc.column
));
} else {
err = err.with_note_line(&format!("'{}' was declared as {}", name, self.typed_phrase(&declared)));
}
err = err.with_help_line(&format!(
"use a different name here, or declare '{}' as {} instead",
name,
self.typed_phrase(&new_type)
));
self.errors.push(err);
self.scalar_types.remove(name);
true
}
fn validate_treating_expr(&mut self, value: &Expr, match_value: &Expr, replacement: &Expr) {
if let (Some(match_ty), Some(replacement_ty)) = (
self.infer_simple_expr_type(match_value),
self.infer_simple_expr_type(replacement),
) {
if !self.treating_types_compatible(&match_ty, &replacement_ty) {
self.push_error(
format!(
"Treating match and replacement must be the same type (got {} vs {}).",
self.type_name(&match_ty),
self.type_name(&replacement_ty)
),
None,
);
}
}
if let (Some(value_ty), Some(match_ty)) = (
self.infer_simple_expr_type(value),
self.infer_simple_expr_type(match_value),
) {
if !self.treating_types_compatible(&value_ty, &match_ty) {
self.push_error(
format!(
"Treating value and match must be the same type (got {} vs {}).",
self.type_name(&value_ty),
self.type_name(&match_ty)
),
None,
);
}
}
}
fn validate_file_open_path(&mut self, path: &Expr) {
const OPEN_PATH_GUIDANCE: &str = "Open path must be either a text path like \"/path/to/file\" or a file descriptor number (0 = stdin, 1 = stdout, 2 = stderr).";
if let Some(fd) = self.expr_integer_literal_value(path) {
if !(0..=FD_MAX).contains(&fd) {
self.push_error(
format!(
"File descriptor out of range after 'at': {}. Valid range is 0..{} (0 = stdin).",
fd, FD_MAX
),
None,
);
}
return;
}
match path {
Expr::StringLit(_) | Expr::FormatString { .. } => {}
Expr::Identifier(name) => {
if self.is_buffer_variable(name) || self.is_list_variable(name) {
self.push_error(OPEN_PATH_GUIDANCE.to_string(), Some(name));
}
}
Expr::FloatLit(_)
| Expr::BoolLit(_)
| Expr::ListLit { .. }
| Expr::Range { .. }
| Expr::PropertyCheck { .. }
| Expr::TypeCheck { .. } => {
self.push_error(OPEN_PATH_GUIDANCE.to_string(), None);
}
Expr::Cast { target_type, .. } => {
if !matches!(target_type, Type::Integer | Type::String) {
self.push_error(OPEN_PATH_GUIDANCE.to_string(), None);
}
}
_ => {}
}
}
fn statement_always_terminates(&self, stmt: &Statement) -> bool {
match stmt {
Statement::Return { .. } | Statement::Exit { .. } => true,
Statement::If { then_block, else_if_blocks, else_block, .. } => {
if !self.block_always_terminates(then_block) {
return false;
}
for (_, block) in else_if_blocks {
if !self.block_always_terminates(block) {
return false;
}
}
if let Some(block) = else_block {
self.block_always_terminates(block)
} else {
false
}
}
_ => false,
}
}
fn analyze_statement(&mut self, stmt: &Statement) {
match stmt {
Statement::Print { value, .. } => {
self.deps.uses_io = true;
self.analyze_expr(value);
if matches!(value, Expr::StringLit(_)) {
self.deps.uses_strings = true;
}
}
Statement::VarDecl { name, var_type, value } => {
// `Set x to <value>.` / `Create x to <value>.` parse into
// this same statement with `var_type: None` regardless of
// whether `x` is brand-new or already exists (no explicit
// type keyword follows `Set`/`Create`). Only the
// already-declared case is a reassignment that the type
// lock applies to; a genuinely new `x` is a real
// declaration and must infer/lock its type as usual.
let was_already_declared = self.is_variable_available(name);
// A second explicitly-typed declaration of an
// already-declared name is a redeclaration, not scoping:
// Vox has no block-level lexical scoping today - If/While/
// etc. bodies share the enclosing scope's slots, so there
// is no separate slot for an inner declaration to occupy
// and no scope exit to restore the outer type at. Without
// this check, `a text called n is "abc".` inside an
// untaken `If` branch permanently overwrote the outer
// `number` n's tracked type regardless of whether the
// branch ever ran (plan 294 finding 12 - this is the
// declaration-arm counterpart to what the type lock
// already does for reassignment). A conflicting rebind is
// rejected exactly like `Statement::Assignment`/`Set`
// reusing an incompatible name; a same-type redeclaration
// (or a genuinely new name) is unaffected - `bind_variable_
// type` no-ops on either.
let redeclaration_conflict = if let (true, Some(vt)) = (was_already_declared, var_type.as_ref()) {
self.bind_variable_type(
name,
vt.clone(),
"this declaration",
"declares as",
&[format!("called {} ", name)],
false,
)
} else {
false
};
self.declare_variable_in_current_scope(name);
if redeclaration_conflict {
if let Some(v) = value {
self.analyze_expr(v);
}
return;
}
// Register the declared type in the type-specific sets,
// mirroring the top-level pre-pass. That pre-pass only
// walks program.statements and never descends into
// function bodies, so without this a `a buffer called x
// is "..."` INSIDE a function was never recorded as a
// buffer and property/byte access on it was rejected.
// (`a buffer called x is N bytes in size.` parses as
// BufferDecl - a different statement whose arm already
// registers - which is why only the initializer form
// failed.)
if let Some(Type::Buffer) = var_type {
self.buffer_variables.insert(name.clone());
}
if let Some(Type::List(_)) = var_type {
self.list_variables.insert(name.clone());
// Plan 294 finding 18: a `for each` loop variable over
// a list this proves heterogeneous must be dynamically
// typed (see the ForEach arm) rather than silently
// allowing arithmetic that only some elements support.
if let Some(Expr::ListLit { elements }) = value {
if self.list_literal_is_mixed(elements) {
self.list_mixed.insert(name.clone());
}
}
}
if let Some(Type::Map(_)) = var_type {
self.map_variables.insert(name.clone());
// Plan 294 findings 4, 14: a homogeneous map literal's
// value type is provable, which makes a mismatched read
// from it a statically-detectable type-lock violation
// instead of a silently-allowed "can't prove it" case.
if let Some(Expr::MapLit { pairs }) = value {
if let Some(t) = self.map_literal_value_type(pairs) {
self.map_value_type.insert(name.clone(), t);
}
}
}
if let Some(Type::Value) = var_type {
// A declared `a value called x` is dynamic, like a value
// parameter: bare arithmetic on it is rejected until the
// author checks its type with a predicate.
self.value_typed_names.insert(name.clone());
}
self.maybe_activate_true_guard(name, var_type, value);
if let Some(v) = value {
self.analyze_expr(v);
}
// Track the scalar category (number/float/text/boolean) for
// the arithmetic type check. Numeric/boolean declarations are
// recorded from the declared type (preferring the initializer's
// type when it is clearly numeric). A text declaration is only
// pinned as text when the initializer is positively text - a
// function-call or property initializer of unknown type might
// return a number, and pinning it as text would wrongly reject
// later arithmetic on it.
if let Some(vt) = var_type {
match vt {
Type::Integer | Type::Float | Type::Boolean => {
let t = value
.as_ref()
.and_then(|v| self.arithmetic_operand_type(v))
.unwrap_or_else(|| vt.clone());
self.scalar_types.insert(name.clone(), t);
}
Type::String => {
let is_text = value
.as_ref()
.map(|v| matches!(self.arithmetic_operand_type(v), Some(Type::String)))
.unwrap_or(false);
if is_text {
self.scalar_types.insert(name.clone(), Type::String);
} else {
self.scalar_types.remove(name);
}
}
_ => {}
}
} else if was_already_declared {
// `Set n to <value>.` on an already-declared `n`: a
// reassignment wearing a declaration's syntax. Enforce
// the lock exactly like `Statement::Assignment` does,
// instead of leaving scalar_types untouched (which is
// how this exact case used to silently retype, or
// silently do nothing, depending on the value's shape).
if let Some(v) = value.as_ref() {
self.check_type_lock(name, v);
}
}
// Record the declaration site the first time we see a real
// type for `name`, regardless of `was_already_declared`: a
// global pre-pass (`self.variables = self.global_variables
// .clone()` before the main walk, fed by
// `collect_definite_decls`) makes every top-level name
// "already available" from the very first statement, so
// `was_already_declared` is always true here for a
// top-level declaration and can't be used to gate this.
if !self.declared_locations.contains_key(name) {
if let Some(loc) = self.find_declaration_location(name) {
self.declared_locations.insert(name.clone(), loc);
}
}
}
Statement::FlagSchemaDecl { name, value_type, default, .. } => {
self.deps.uses_args = true;
self.declare_variable_in_current_scope(name);
if let Some(v) = default {
self.analyze_expr(v);
// The default must match the flag's declared value
// type. A mismatch previously compiled and produced
// garbage at runtime: a number flag defaulted to
// text printed the string's address, and a boolean
// flag defaulted to a number printed the integer.
let expected = match value_type {
FlagValueType::Boolean => Type::Boolean,
FlagValueType::Number => Type::Integer,
FlagValueType::Text => Type::String,
};
if let Some(actual) = self.infer_simple_expr_type(v) {
if !self.treating_types_compatible(&expected, &actual) {
self.push_error(
format!(
"Flag '{}' is a {} but its default is a {}.",
name,
self.type_name(&expected),
self.type_name(&actual)
),
Some(name),
);
}
}
}
}
Statement::ParseFlags => {
self.deps.uses_args = true;
}
Statement::Assignment { name, value } => {
// A variable's type is fixed at declaration and never
// changes (the fix for the whole "tracked type disagrees
// with runtime type" bug family). `name is <value>.` is
// ambiguous on its own between "declare a brand-new
// variable" (valid at top level) and "reassign an existing
// one" - which it is decides whether this write gets
// type-checked at all, so capture it before the auto-declare
// below can change the answer.
let was_already_declared = self.is_variable_available(name);
if !was_already_declared {
if self.in_function_scope {
self.push_unknown_variable(name);
} else {
self.declare_variable_in_current_scope(name);
}
}
if matches!(value, Expr::FormatString { .. })
&& self.is_variable_available(name)
&& !self.is_buffer_variable(name)
{
self.push_error(
format!("Format-string assignment requires a buffer destination: {}", name),
Some(name),
);
}
self.analyze_expr(value);
if was_already_declared {
// Reassignment of an existing name: enforce the lock
// instead of relabelling scalar_types to match. On a
// mismatch, check_type_lock has already reported the
// error; either way the declared type never changes
// here.
self.check_type_lock(name, value);
} else {
// A brand-new name introduced by bare `name is <value>.`
// (valid at top level; the function-scope case above
// already reported "unknown variable") is a genuine
// declaration - infer and lock its type, exactly like an
// explicit `a <type> called name is <value>.` would.
if !self.is_buffer_variable(name)
&& !self.is_list_variable(name)
&& !self.is_map_variable(name)
&& !self.file_variables.contains(name.as_str())
&& !self.timer_variables.contains(name.as_str())
{
match self.arithmetic_operand_type(value) {
Some(t) => {
self.scalar_types.insert(name.clone(), t);
}
None => {
self.scalar_types.remove(name);
}
}
}
if !self.declared_locations.contains_key(name) {
if let Some(loc) = self.find_declaration_location(name) {
self.declared_locations.insert(name.clone(), loc);
}
}
}
}
Statement::If { condition, then_block, else_if_blocks, else_block } => {
self.validate_function_condition_variable_refs(condition);
self.analyze_expr(condition);
// Branches are analyzed with the same incoming scope.
// Declarations inside one branch do not become visible in sibling
// branches. After the if-statement, only variables that are
// definitely available on all continuing paths remain visible.
let branch_env = self.current_env();
let mut continuing_envs: Vec<AnalysisEnv> = Vec::new();
let guard_key = Self::simple_guard_key(condition);
let (then_env, then_terminates) = self.analyze_block_in_scope(
then_block,
&branch_env,
guard_key.as_deref(),
);
if !then_terminates {
continuing_envs.push(then_env);
}
for (cond, block) in else_if_blocks {
let saved_env = self.current_env();
self.apply_env(&branch_env);
self.validate_function_condition_variable_refs(cond);
self.analyze_expr(cond);
self.apply_env(&saved_env);
let (elif_env, elif_terminates) = self.analyze_block_in_scope(block, &branch_env, None);
if !elif_terminates {
continuing_envs.push(elif_env);
}
}
if let Some(block) = else_block {
let (else_env, else_terminates) = self.analyze_block_in_scope(block, &branch_env, None);
if !else_terminates {
continuing_envs.push(else_env);
}
} else {
// No else means the original incoming scope can continue unchanged.
continuing_envs.push(branch_env.clone());
}
let merged_env = self.merge_continuing_envs(&continuing_envs, &branch_env);
self.apply_env(&merged_env);
}
Statement::While { condition, body } => {
self.validate_function_condition_variable_refs(condition);
self.analyze_expr(condition);
self.loop_depth += 1;
for s in body {
self.analyze_statement(s);
}
self.loop_depth -= 1;
}
Statement::ForRange { variable, range, body } => {
self.variables.insert(variable.clone());
// A range loop variable steps over integers - reusing a
// name already declared with a different type is a rebind,
// same rule as `Set`/`is` (plan 294 finding 2: this used to
// leave the old label in place and segfault when the
// formatter dereferenced the loop counter as a pointer).
self.bind_variable_type(
variable,
Type::Integer,
"this for-range loop",
"counts with",
&[format!("each {} ", variable)],
true,
);
self.analyze_expr(range);
self.loop_depth += 1;
for s in body {
self.analyze_statement(s);
}
self.loop_depth -= 1;
}
Statement::ForEach { variable, collection, body } => {
self.variables.insert(variable.clone());
// The element category is unknown (lists may be mixed), so a
// label left over from a previous use of this name - e.g. a
// text variable reused as the loop variable over a numeric
// list - must not linger and falsely reject arithmetic on the
// loop variable inside the body.
self.scalar_types.remove(variable);
// Plan 294 finding 18: over a list PROVEN heterogeneous (see
// `list_mixed`/`list_literal_is_mixed`), the loop variable
// genuinely holds a different type each iteration - no
// fixed type is correct, so route it into the same
// dynamic/`value` mechanism a declared `a value called x`
// uses, demanding an explicit check before arithmetic
// instead of silently allowing it on whatever type the
// element turns out not to be. A list this narrower,
// single-pass check can't prove mixed (see `list_mixed`'s
// own doc comment on what it does not catch) keeps today's
// existing behaviour unchanged.
let list_name = match collection {
Expr::Identifier(n) | Expr::StringLit(n) => Some(n.as_str()),
_ => None,
};
let is_mixed = match (list_name, collection) {
(Some(n), _) => self.list_mixed.contains(n),
(None, Expr::ListLit { elements }) => self.list_literal_is_mixed(elements),
(None, _) => false,
};
if is_mixed {
self.value_typed_names.insert(variable.clone());
} else {
self.value_typed_names.remove(variable.as_str());
}
self.analyze_expr(collection);
self.loop_depth += 1;
for s in body {
self.analyze_statement(s);
}
self.loop_depth -= 1;
}
Statement::Repeat { count, body } => {
self.analyze_expr(count);
self.loop_depth += 1;
for s in body {
self.analyze_statement(s);
}
self.loop_depth -= 1;
}
Statement::Return { value, .. } => {
// `Return` is only meaningful inside a function. At top
// level the codegen still emits a function epilogue
// (leave/ret) which is undefined from _start, so reject
// it here rather than produce broken output.
if !self.in_function_scope {
let hint = self.pending_blank_line_truncation.as_ref().map(|(func, _, loc)| {
format!(
"a blank line ended `{}`'s body early at line {} — a paragraph break closes all open clauses, so this Return is no longer inside it",
func, loc.line
)
});
self.push_error_with_hint(
"Return is only valid inside a function".to_string(),
None,
hint.as_deref(),
);
}
if let Some(v) = value {
self.analyze_expr(v);
}
}
Statement::Allocate { name, size } => {
self.deps.uses_heap = true;
self.variables.insert(name.clone());
self.allocated_variables.insert(name.clone());
// The variable now holds a raw pointer, rendered as a
// number when printed - a rebind like any other (plan 294
// finding 17: codegen used to leave a stale text label in
// place, formatting the fresh allocation as a C string).
self.bind_variable_type(
name,
Type::Integer,
"this Allocate statement",
"allocates",
&[format!("for {}", name)],
true,
);
self.analyze_expr(size);
}
Statement::Free { name } => {
self.deps.uses_heap = true;
if !self.is_variable_available(name) {
self.push_error(format!("Freeing unknown variable: {}", name), Some(name));
} else if !self.is_buffer_variable(name)
&& !self.is_list_variable(name)
&& !self.allocated_variables.contains(name.as_str())
{
self.push_error(
format!("Free requires a buffer or list: {}", name),
Some(name),
);
}
}
Statement::FunctionCall { name, args } => {
self.deps.uses_funcs = true; // Track that functions are used
self.check_function_call(name, args);
for arg in args {
self.analyze_expr(arg);
}
}
Statement::FunctionDef { name, params, body, body_ended_early, .. } => {
self.pending_blank_line_truncation = None;
// A leading underscore is the runtime's namespace (see
// docs/SYMBOL_MANGLING.md). A function name emits a label
// verbatim, so `To _str_eq ...` redefines a coreasm symbol
// and the author gets NASM's "label `_str_eq' inconsistently
// redefined" - an assembler diagnostic about a symbol they
// never wrote. Reject it here, in their terms.
if name.starts_with('_') {
self.push_error(
format!(
"Function name '{}' starts with '_', which is reserved for \
the Vox runtime; choose a name without the leading underscore.",
name
),
Some(name),
);
}
// Names that differ only in characters the mangler folds to
// '_' would emit the same label, so one body would silently
// win. Reject rather than miscompile. The check is scoped by
// library: the key is the full `<lib>_<ver>_<func>` label, so
// "my.helper" and "my helper" in the SAME library collide (and
// are flagged), while the same two names in DIFFERENT libraries
// of one .so produce distinct labels and are both fine — that
// is the whole point of the mangling.
let symbol = self.func_key(name);
match self.mangled_functions.get(&symbol) {
Some(prev) if prev != name => {
self.push_error(
format!(
"Functions '{}' and '{}' both become the assembly symbol \
'{}'; rename one so they stay distinct.",
prev, name, symbol
),
Some(name),
);
}
_ => {
self.mangled_functions.insert(symbol, name.clone());
}
}
self.functions.insert(self.func_key(name));
self.function_param_counts
.insert(self.func_key(name), params.len());
self.deps.uses_funcs = true; // Track that functions are used
// Functions can access top-level globals, but locals declared inside
// the function must not leak back into top-level scope.
let saved_env = self.current_env();
let saved_guards = self.active_guards.clone();
let saved_block_depth = self.block_depth;
let saved_in_function_scope = self.in_function_scope;
// Type labels are scoped like the variables themselves: a
// parameter (or body-local declaration) named like a
// top-level variable must not relabel it for the code after
// the function - a text parameter "x" would otherwise make
// top-level arithmetic on a number "x" a false error.
let saved_scalar_types = self.scalar_types.clone();
let saved_buffer_variables = self.buffer_variables.clone();
let saved_list_variables = self.list_variables.clone();
let saved_map_variables = self.map_variables.clone();
let saved_file_variables = self.file_variables.clone();
let saved_timer_variables = self.timer_variables.clone();
let saved_allocated_variables = self.allocated_variables.clone();
let saved_value_typed_names = self.value_typed_names.clone();
self.variables = self.global_variables.clone();
self.guarded_scopes.clear();
self.active_guards.clear();
self.in_function_scope = true;
self.block_depth = 0;
// Add function parameters to function scope. Buffer/list/file
// typed parameters must also be recorded in their
// type-specific sets, exactly like a VarDecl/BufferDecl at
// top level would - otherwise `param's size`/`empty`/`full`
// (and other buffer/list/file-only properties) incorrectly
// report "requires a buffer, list, or file variable" for
// the parameter itself. This previously only appeared to
// work when a same-named top-level variable of the correct
// type happened to already exist elsewhere in the program.
for (param_name, param_type) in params {
self.variables.insert(param_name.clone());
match param_type {
Type::Buffer => { self.buffer_variables.insert(param_name.clone()); }
Type::List(_) => { self.list_variables.insert(param_name.clone()); }
Type::Map(_) => { self.map_variables.insert(param_name.clone()); }
Type::File => { self.file_variables.insert(param_name.clone()); }
Type::Integer | Type::Float | Type::String | Type::Boolean => {
self.scalar_types.insert(param_name.clone(), param_type.clone());
}
Type::Value => {
// A `value` parameter is dynamic: it carries a
// runtime tag but is not statically a number/text,
// so bare arithmetic on it must be rejected (the
// author guards with a stage-1c predicate first).
self.value_typed_names.insert(param_name.clone());
}
_ => {}
}
}
for s in body {
self.analyze_statement(s);
}
self.block_depth = saved_block_depth;
self.active_guards = saved_guards;
self.in_function_scope = saved_in_function_scope;
self.scalar_types = saved_scalar_types;
self.buffer_variables = saved_buffer_variables;
self.list_variables = saved_list_variables;
self.map_variables = saved_map_variables;
self.file_variables = saved_file_variables;
self.timer_variables = saved_timer_variables;
self.allocated_variables = saved_allocated_variables;
self.value_typed_names = saved_value_typed_names;
self.apply_env(&saved_env);
self.pending_blank_line_truncation = body_ended_early.as_ref().map(|loc| {
(name.clone(), params.iter().map(|(n, _)| n.clone()).collect(), loc.clone())
});
}
Statement::Increment { name } | Statement::Decrement { name } => {
if !self.is_variable_available(name) {
self.push_unknown_variable(name);
} else if self.is_buffer_variable(name)
|| self.is_list_variable(name)
|| self.is_map_variable(name)
|| self.file_variables.contains(name.as_str())
|| self.flag_variables.contains(name.as_str())
|| self.timer_variables.contains(name.as_str())
|| matches!(self.named_value_type(name), Some(Type::String))
{
// Increment/Decrement compile to an integer `inc/dec
// qword` on the variable's stack slot. Applied to a
// buffer/list/file variable that slot holds a pointer
// (which gets corrupted), to a timer it holds a 56-byte
// struct (also corrupted), and to a boolean flag it
// yields 2, 3, ... instead of a boolean. Reject these
// rather than emit undefined behaviour.
//
// A declared-text variable is the same defect the type
// lock elsewhere in this file exists to close, but this
// one is not a type CHANGE - tracking is correct, `name`
// really is text - so the lock doesn't see it (plan 294
// findings 5/15): the pointer just gets walked one byte
// at a time with no relationship to the string's bounds
// until it wanders off the mapping.
//
// Deliberately NOT rejecting `value`-typed names here:
// unlike bare arithmetic, Increment/Decrement on a
// `value` holding a number already worked correctly
// (inc/dec on its raw integer payload) before this
// check existed, and rejecting it would remove working
// behaviour outside findings 5/15, which are both about
// text. If `value` should eventually be rejected too,
// that is a separate decision, not folded in here.
let kw = if matches!(stmt, Statement::Increment { .. }) {
"Increment"
} else {
"Decrement"
};
// Built directly rather than via `push_error` so the
// pointer lands on the `Increment`/`Decrement` line
// itself: `push_error`'s `find_symbol_location` prefers
// `{name` (format-string interpolation) as its first
// pattern, which would anchor on an unrelated
// `Print "{s}"` elsewhere in the same program instead.
let occurrence = *self.symbol_error_counts.get(name).unwrap_or(&0);
let mut err = CompileError::new(&format!("{} requires a number variable: {}", kw, name));
let patterns = [format!("{} {}", kw, name)];
if let Some(loc) = self.find_bind_site_location(name, &patterns, occurrence, true) {
err = err.with_underline_note(name.len().max(1), "not a number here");
err = err.with_location(loc);
}
self.symbol_error_counts.insert(name.to_string(), occurrence + 1);
self.errors.push(err);
}
}
Statement::Break | Statement::Continue => {
// Break/Continue are loop-control constructs. Outside a
// loop the codegen silently emits nothing, so the author's
// intent is lost with no signal - reject it at compile time.
if self.loop_depth == 0 {
let kw = if matches!(stmt, Statement::Break) { "Break" } else { "Continue" };
self.push_error(
format!("{} is only valid inside a loop", kw),
None,
);
}
}
// File I/O statements
Statement::BufferDecl { name, size } => {
self.variables.insert(name.clone());
self.buffer_variables.insert(name.clone());
self.analyze_expr(size);
self.deps.uses_heap = true;
}
Statement::ByteSet { buffer, index, value } => {
self.track_identifier(buffer);
self.analyze_expr(index);
self.analyze_expr(value);
if !self.is_variable_available(buffer) {
self.push_error(format!("Unknown buffer: {}", buffer), Some(buffer));
} else if !self.is_buffer_variable(buffer) {
self.push_error(
format!("Byte set target must be a buffer: {}", buffer),
Some(buffer),
);
}
}
Statement::ElementSet { list, index, value } => {
self.track_identifier(list);
self.analyze_expr(index);
self.analyze_expr(value);
if !self.is_variable_available(list) {
self.push_error(format!("Unknown list: {}", list), Some(list));
} else if !self.is_list_variable(list) {
self.push_error(
format!("Element set target must be a list: {}", list),
Some(list),
);
}
}
// Set <map>'s "<key>" to <value>: insert or replace. The map may
// reallocate on growth; codegen stores the returned pointer back
// into the variable (mirroring ListAppend). Keys are text.
Statement::MapSet { map, key, value } => {
self.track_identifier(map);
self.analyze_expr(key);
self.analyze_expr(value);
if !self.is_variable_available(map) {
self.push_error(format!("Unknown map: {}", map), Some(map));
} else if !self.is_map_variable(map) {
self.push_error(
format!("Map set target must be a map: {}", map),
Some(map),
);
}
if let Some(Type::String) = self.infer_simple_expr_type(key) {
// ok: text key
} else {
self.push_error(
"Map keys must be text".to_string(),
Some(map),
);
}
}
Statement::ListAppend { list, value } => {
self.track_identifier(list);
self.analyze_expr(value);
if self.is_buffer_variable(list) {
match value {
Expr::Identifier(source) => {
if !self.is_variable_available(source) {
self.push_error(format!("Unknown buffer: {}", source), Some(source));
} else if !self.is_buffer_variable(source)
&& self.named_value_type(source) != Some(Type::String)
{
self.push_error(
format!("Buffer append requires a buffer source: {}", source),
Some(source),
);
}
}
Expr::StringLit(_) | Expr::FormatString { .. } => {
// Allowed: append text/format output into destination buffer.
}
_ => {
self.push_error(
"Buffer append requires a buffer source or format/literal text".to_string(),
Some(list),
);
}
}
} else if self.is_list_variable(list) {
// Valid list append path.
} else if !self.is_variable_available(list) {
self.push_error(format!("Unknown variable: {}", list), Some(list));
} else {
self.push_error(
format!("Append target must be a buffer or list: {}", list),
Some(list),
);
}
}
Statement::BufferCopy { source, destination } => {
if let Expr::Identifier(source_name) = source {
self.track_identifier(source_name);
}
self.track_identifier(destination);
self.analyze_expr(source);
match source {
Expr::Identifier(source_name) => {
if !self.is_variable_available(source_name) {
self.push_error(format!("Unknown buffer: {}", source_name), Some(source_name));
} else if !self.is_buffer_variable(source_name) {
self.push_error(
format!("Copy source must be a buffer: {}", source_name),
Some(source_name),
);
}
}
Expr::StringLit(_) | Expr::FormatString { .. } => {
// Allowed: copy literal/format output into destination buffer.
}
_ => {
self.push_error(
"Copy source must be a buffer or format/literal text".to_string(),
Some(destination),
);
}
}
if !self.is_variable_available(destination) {
self.push_error(format!("Unknown buffer: {}", destination), Some(destination));
} else if !self.is_buffer_variable(destination) {
self.push_error(
format!("Copy destination must be a buffer: {}", destination),
Some(destination),
);
}
}
Statement::BufferClear { name } => {
self.track_identifier(name);
if !self.is_variable_available(name) {
self.push_error(format!("Unknown buffer: {}", name), Some(name));
} else if !self.is_buffer_variable(name) {
self.push_error(
format!("Clear target must be a buffer: {}", name),
Some(name),
);
}
}
Statement::FileOpen { name, path, .. } => {
// `open ... called X` binds X to a file descriptor - a
// rebind like any other if X already exists with an
// incompatible type (plan 294 finding 3: this used to leave
// a stale text label in place and dereference the fd as a
// string pointer). Checked before registering `name` as a
// file below, so it sees the pre-existing declared type.
self.bind_variable_type(
name,
Type::File,
"this open statement",
"opens as",
&[format!("called {} ", name)],
false,
);
self.variables.insert(name.clone());
self.file_variables.insert(name.clone());
self.analyze_expr(path);
self.validate_file_open_path(path);
self.deps.uses_io = true;
}
Statement::FileRead { buffer, .. } => {
if !self.is_variable_available(buffer) {
self.push_error(format!("Unknown buffer: {}", buffer), Some(buffer));
} else if !self.is_buffer_variable(buffer) {
self.push_error(
format!("Read target must be a buffer: {}", buffer),
Some(buffer),
);
}
self.deps.uses_io = true;
}
Statement::FileReadLine { buffer, .. } => {
if !self.is_variable_available(buffer) {
self.push_error(format!("Unknown buffer: {}", buffer), Some(buffer));
} else if !self.is_buffer_variable(buffer) {
self.push_error(
format!("Read target must be a buffer: {}", buffer),
Some(buffer),
);
}
self.deps.uses_io = true;
}
Statement::FileSeekLine { file, line } => {
if !self.is_variable_available(file) {
self.push_error(format!("Unknown file: {}", file), Some(file));
} else if !self.file_variables.contains(file.as_str()) {
self.push_error(
format!("Seek target must be a file: {}", file),
Some(file),
);
}
self.analyze_expr(line);
self.deps.uses_io = true;
}
Statement::FileSeekByte { file, byte } => {
if !self.is_variable_available(file) {
self.push_error(format!("Unknown file: {}", file), Some(file));
} else if !self.file_variables.contains(file.as_str()) {
self.push_error(
format!("Seek target must be a file: {}", file),
Some(file),
);
}
self.analyze_expr(byte);
self.deps.uses_io = true;
}
Statement::FileWrite { file, value } => {
if !self.is_variable_available(file) {
self.push_error(format!("Unknown file: {}", file), Some(file));
} else if !self.file_variables.contains(file.as_str()) {
self.push_error(
format!("Write target must be a file: {}", file),
Some(file),
);
}
self.analyze_expr(value);
self.deps.uses_io = true;
}
Statement::FileWriteNewline { file } => {
if !self.is_variable_available(file) {
self.push_error(format!("Unknown file: {}", file), Some(file));
} else if !self.file_variables.contains(file.as_str()) {
self.push_error(
format!("Write target must be a file: {}", file),
Some(file),
);
}
self.deps.uses_io = true;
}
Statement::FileClose { file } => {
if !self.is_variable_available(file) {
self.push_error(format!("Unknown file: {}", file), Some(file));
} else if !self.file_variables.contains(file.as_str()) {
self.push_error(
format!("Close target must be a file: {}", file),
Some(file),
);
}
self.deps.uses_io = true;
}
Statement::FileDelete { path } => {
self.analyze_expr(path);
self.deps.uses_io = true;
}
Statement::Rmdir { path } => {
self.analyze_expr(path);
self.deps.uses_io = true;
}
Statement::Mkdir { path } => {
self.analyze_expr(path);
self.deps.uses_io = true;
}
Statement::Chdir { path } => {
self.analyze_expr(path);
self.deps.uses_io = true;
}
Statement::Mount { source, target, fstype, options } => {
self.analyze_expr(source);
self.analyze_expr(target);
self.analyze_expr(fstype);
if let Some(o) = options {
self.analyze_expr(o);
}
self.deps.uses_io = true;
}
Statement::Unmount { target, .. } => {
self.analyze_expr(target);
self.deps.uses_io = true;
}
Statement::Shutdown | Statement::Reboot | Statement::Halt => {
self.deps.uses_io = true;
}
Statement::PivotRoot { new_root, put_old } => {
self.analyze_expr(new_root);
self.analyze_expr(put_old);
self.deps.uses_io = true;
}
Statement::Execute { path, args } => {
self.analyze_expr(path);
self.analyze_expr(args);
self.deps.uses_io = true;
// execve needs the process's real envp to properly inherit
// the environment (NULL would give the child an empty one) -
// this forces SAVE_ARGS to run and _envp to be captured.
self.deps.uses_args = true;
}
Statement::Symlink { target, linkpath } => {
self.analyze_expr(target);
self.analyze_expr(linkpath);
self.deps.uses_io = true;
}
Statement::Mknod { path, major, minor, .. } => {
self.analyze_expr(path);
self.analyze_expr(major);
self.analyze_expr(minor);
self.deps.uses_io = true;
}
Statement::OnError { actions } => {
for action in actions {
self.analyze_statement(action);
}
}
Statement::BufferResize { name, new_size } => {
if !self.is_variable_available(name) {
self.push_error(format!("Unknown buffer: {}", name), Some(name));
} else if !self.is_buffer_variable(name) {
self.push_error(
format!("Resize target must be a buffer: {}", name),
Some(name),
);
}
self.analyze_expr(new_size);
self.deps.uses_heap = true;
}
Statement::LibraryDecl { name, version } => {
self.pending_blank_line_truncation = None;
// A `Library` declaration sets the identity for the function
// definitions that follow it. The per-function tables are keyed
// by the `<lib>_<ver>_<func>` label, so a call inside this
// library's bodies resolves only against this library's
// functions. The walk is in source order and a `Library`
// precedes its functions, so the field is current when each
// `FunctionDef` body is analyzed. (In a multi-input --shared
// build the concatenated unit has one `Library` per input,
// so each library's functions resolve in their own scope.)
self.current_library = Some((name.clone(), version.clone()));
}
Statement::See { .. } => {
// See statements are handled at compile time
}
Statement::Exit { code } => {
self.analyze_expr(code);
}
// Time and Timer statements
Statement::TimerDecl { name } => {
self.variables.insert(name.clone());
self.timer_variables.insert(name.clone());
}
Statement::TimerStart { name } => {
if !self.is_variable_available(name) {
self.push_error(format!("Unknown timer: {}", name), Some(name));
} else if !self.timer_variables.contains(name) {
self.push_error(
format!("Start requires a timer: {}", name),
Some(name),
);
}
}
Statement::TimerStop { name } => {
if !self.is_variable_available(name) {
self.push_error(format!("Unknown timer: {}", name), Some(name));
} else if !self.timer_variables.contains(name) {
self.push_error(
format!("Stop requires a timer: {}", name),
Some(name),
);
}
}
Statement::Wait { duration, .. } => {
self.analyze_expr(duration);
}
Statement::GetTime { into } => {
self.variables.insert(into.clone());
// The variable now holds a unix timestamp.
self.scalar_types.insert(into.clone(), Type::Integer);
}
}
}
fn analyze_expr(&mut self, expr: &Expr) {
match expr {
Expr::BinaryOp { left, op, right } => {
self.analyze_expr(left);
self.analyze_expr(right);
// Arithmetic operators require numeric operands. Text,
// buffer, list, file, and timer values compile to
// pointer/handle arithmetic and yield garbage without an
// explicit cast (`s as a number`).
if self.is_arithmetic_op(op) {
self.check_arithmetic_operand(left);
self.check_arithmetic_operand(right);
}
}
Expr::UnaryOp { op, operand } => {
self.analyze_expr(operand);
// Negation is arithmetic; `minus s` on a text/buffer/etc.
// value has the same garbage problem as `0 subtract s`.
if matches!(op, UnaryOperator::Negate) {
self.check_arithmetic_operand(operand);
}
}
Expr::Range { start, end, .. } => {
self.analyze_expr(start);
self.analyze_expr(end);
}
Expr::PropertyCheck { value, .. } => {
self.analyze_expr(value);
}
// Runtime type predicate (stage 1c). The type noun was validated
// by the parser, so the analyzer only needs to recurse into the
// operand.
Expr::TypeCheck { value, .. } => {
self.analyze_expr(value);
}
Expr::PropertyAccess { object, property } => {
// _current_time is a synthetic object for "current time's X" - not a user variable
if object == "_current_time" {
return;
}
self.track_identifier(object);
if !self.is_variable_available(object) {
self.push_error(format!("Unknown variable: {}", object), Some(object));
} else {
let is_buf = self.is_buffer_variable(object);
let is_list = self.is_list_variable(object);
let is_map = self.is_map_variable(object);
let is_file = self.file_variables.contains(object.as_str());
let is_scalar = self.is_scalar_variable(object);
// A text variable is "scalar" (its slot holds a raw
// 64-bit value), but that value is a string pointer -
// number/time properties on it read the pointer as a
// number and yield garbage. Only reject when the label
// is positively String; unknown stays allowed.
let is_text =
matches!(self.scalar_types.get(object.as_str()), Some(Type::String));
match property {
ObjectProperty::Size | ObjectProperty::Empty => {
if !is_buf && !is_list && !is_map && !is_file {
self.push_error(
format!("Property '{}' requires a buffer, list, map, or file variable: {}",
match property {
ObjectProperty::Size => "size",
ObjectProperty::Empty => "empty",
_ => "unknown",
}, object),
Some(object),
);
}
}
ObjectProperty::Full => {
if !is_buf && !is_list && !is_file {
self.push_error(
format!("Property 'full' requires a buffer, list, or file variable: {}", object),
Some(object),
);
}
}
ObjectProperty::Keys | ObjectProperty::Values => {
if !is_map {
self.push_error(
format!("Property '{}' requires a map variable: {}",
if matches!(property, ObjectProperty::Keys) { "keys" } else { "values" }, object),
Some(object),
);
}
}
ObjectProperty::Capacity => {
if !is_buf && !is_list {
self.push_error(
format!("Property 'capacity' requires a buffer or list variable: {}", object),
Some(object),
);
}
}
ObjectProperty::First | ObjectProperty::Last => {
if !is_list {
self.push_error(
format!("Property '{}' requires a list variable: {}",
if matches!(property, ObjectProperty::First) { "first" } else { "last" }, object),
Some(object),
);
}
}
ObjectProperty::Descriptor | ObjectProperty::Modified |
ObjectProperty::Accessed | ObjectProperty::Permissions |
ObjectProperty::Readable | ObjectProperty::Writable => {
if !is_file {
self.push_error(
format!("File property access requires a file variable: {}", object),
Some(object),
);
}
}
ObjectProperty::Absolute | ObjectProperty::Sign |
ObjectProperty::Even | ObjectProperty::Odd |
ObjectProperty::Positive | ObjectProperty::Negative |
ObjectProperty::Zero => {
if !is_scalar || is_text {
self.push_error(
format!(
"Property '{}' requires a number variable: {}",
match property {
ObjectProperty::Absolute => "absolute",
ObjectProperty::Sign => "sign",
ObjectProperty::Even => "even",
ObjectProperty::Odd => "odd",
ObjectProperty::Positive => "positive",
ObjectProperty::Negative => "negative",
ObjectProperty::Zero => "zero",
_ => "unknown",
},
object,
),
Some(object),
);
}
}
ObjectProperty::Hour | ObjectProperty::Minute |
ObjectProperty::Second | ObjectProperty::Day |
ObjectProperty::Month | ObjectProperty::Year |
ObjectProperty::Unix => {
if !is_scalar || is_text {
self.push_error(
format!(
"Property '{}' requires a time value (number): {}",
match property {
ObjectProperty::Hour => "hour",
ObjectProperty::Minute => "minute",
ObjectProperty::Second => "second",
ObjectProperty::Day => "day",
ObjectProperty::Month => "month",
ObjectProperty::Year => "year",
ObjectProperty::Unix => "unix",
_ => "unknown",
},
object,
),
Some(object),
);
}
}
ObjectProperty::Duration | ObjectProperty::Elapsed |
ObjectProperty::StartTime | ObjectProperty::EndTime |
ObjectProperty::Running => {
if !self.timer_variables.contains(object.as_str()) {
self.push_error(
format!(
"Property '{}' requires a timer: {}",
match property {
ObjectProperty::Duration => "duration",
ObjectProperty::Elapsed => "elapsed",
ObjectProperty::StartTime => "start time",
ObjectProperty::EndTime => "end time",
ObjectProperty::Running => "running",
_ => "unknown",
},
object,
),
Some(object),
);
}
}
}
}
}
Expr::FunctionCall { name, args } => {
self.deps.uses_funcs = true; // Track that functions are used
self.check_function_call(name, args);
for arg in args {
self.analyze_expr(arg);
}
}
Expr::ListAccess { list, index } => {
self.analyze_expr(list);
self.analyze_expr(index);
if let Expr::Identifier(name) = list.as_ref() {
self.track_identifier(name);
if !self.is_variable_available(name) {
self.push_error(format!("Unknown list: {}", name), Some(name));
} else if !self.is_list_variable(name) {
self.push_error(
format!("List access target must be a list: {}", name),
Some(name),
);
}
}
}
Expr::ByteAccess { buffer, index } => {
self.analyze_expr(buffer);
self.analyze_expr(index);
if let Expr::Identifier(name) = buffer.as_ref() {
self.track_identifier(name);
if !self.is_variable_available(name) {
self.push_error(format!("Unknown buffer: {}", name), Some(name));
} else if !self.is_buffer_variable(name) {
self.push_error(
format!("Byte access target must be a buffer: {}", name),
Some(name),
);
}
}
}
Expr::ElementAccess { list, index } => {
self.analyze_expr(list);
self.analyze_expr(index);
if let Expr::Identifier(name) = list.as_ref() {
self.track_identifier(name);
if !self.is_variable_available(name) {
self.push_error(format!("Unknown list: {}", name), Some(name));
} else if !self.is_list_variable(name) {
self.push_error(
format!("Element access target must be a list: {}", name),
Some(name),
);
}
}
}
Expr::ListLit { elements } => {
self.deps.uses_heap = true;
for elem in elements {
self.analyze_expr(elem);
}
}
// Map literal {"k": v, ...}. Keys must be text; values are
// analyzed (and may themselves be lists/maps -> uses_heap).
Expr::MapLit { pairs } => {
self.deps.uses_heap = true;
for (key, value) in pairs {
self.analyze_expr(key);
self.analyze_expr(value);
if self.infer_simple_expr_type(key) != Some(Type::String) {
self.push_error(
"Map keys must be text".to_string(),
None,
);
}
}
}
// Map key access: person's "name". The map operand must be a
// map variable and the key must be text.
Expr::MapAccess { map, key } => {
self.track_identifier(map);
self.analyze_expr(key);
if !self.is_variable_available(map) {
self.push_error(format!("Unknown map: {}", map), Some(map));
} else if !self.is_map_variable(map) {
self.push_error(
format!("Map access target must be a map: {}", map),
Some(map),
);
}
if self.infer_simple_expr_type(key) != Some(Type::String) {
self.push_error(
"Map keys must be text".to_string(),
Some(map),
);
}
}
Expr::StringLit(_) => {
self.deps.uses_strings = true;
}
Expr::FormatString { parts } => {
self.deps.uses_strings = true;
for part in parts {
match part {
FormatPart::Expression { expr, .. } => {
self.analyze_expr(expr);
}
FormatPart::Variable { name, .. } => {
self.track_identifier(name);
if !self.is_variable_available(name) && name != "_iter" {
if find_similar_keyword(name, ENGLISH_KEYWORDS).is_none() {
self.push_unknown_variable(name);
} else {
self.track_typo_candidate(name);
}
}
}
FormatPart::Literal(_) => {}
}
}
}
Expr::Identifier(name) => {
self.track_identifier(name);
if !self.is_variable_available(name) && name != "_iter" {
// Plan 270 G4: a bare/quoted identifier naming a
// zero-argument function is a call in expression position,
// not a variable lookup. Validate it resolves and has zero
// arity via the shared call-site path.
if self.is_zero_arg_function(name) {
self.deps.uses_funcs = true;
self.check_function_call(name, &[]);
} else if find_similar_keyword(name, ENGLISH_KEYWORDS).is_none() {
// Don't report as unknown variable if it might be a
// keyword typo (that will be caught by check_for_typos)
self.push_unknown_variable(name);
} else {
self.track_typo_candidate(name);
}
}
}
// Argument and environment variable expressions
Expr::ArgumentCount | Expr::ArgumentName | Expr::ArgumentFirst |
Expr::ArgumentSecond | Expr::ArgumentLast | Expr::ArgumentEmpty |
Expr::ArgumentAll | Expr::ArgumentRaw => {
self.deps.uses_args = true;
}
Expr::ArgumentHas { value } => {
self.deps.uses_args = true;
self.deps.uses_strings = true;
self.analyze_expr(value);
}
Expr::TreatingAs { value, match_value, replacement } => {
self.analyze_expr(value);
self.analyze_expr(match_value);
self.analyze_expr(replacement);
self.validate_treating_expr(value, match_value, replacement);
}
Expr::ArgumentAt { index } => {
self.deps.uses_args = true;
self.analyze_expr(index);
}
Expr::EnvironmentVariable { name } => {
self.deps.uses_args = true;
self.analyze_expr(name);
}
Expr::EnvironmentVariableCount | Expr::EnvironmentVariableFirst |
Expr::EnvironmentVariableLast | Expr::EnvironmentVariableEmpty => {
self.deps.uses_args = true;
}
Expr::EnvironmentVariableAt { index } => {
self.deps.uses_args = true;
self.analyze_expr(index);
}
Expr::EnvironmentVariableExists { name } => {
self.deps.uses_args = true;
self.analyze_expr(name);
}
Expr::DurationCast { value, .. } => {
// `timer's duration in seconds` parses as a DurationCast
// wrapping a PropertyAccess. Without recursing here the
// inner property access was never analyzed, so a duration
// cast on a non-timer (or referencing an unknown variable)
// compiled silently and read stack garbage at runtime.
self.analyze_expr(value);
}
Expr::Cast { value, target_type, .. } => {
// Recurse so unknown variables / nested type errors inside
// a cast (`missing as a number`) are reported instead of
// compiling silently and emitting garbage.
self.analyze_expr(value);
// Plan 294 finding 21 (adjacent discovery, not one of the
// original 18): a cast on a dynamically-tagged `value`
// source (a declared `a value called x`, a `value`
// parameter, or - as of finding 18's fix - a heterogeneous-
// list loop variable) is codegen-unimplemented, not merely
// unchecked. Verified on unmodified `main`: codegen's Cast
// arm dispatches on the STATIC source type
// (`infer_expr_type`), which is `VarType::Mixed` here, and
// every target-type branch's fallback for an unrecognised
// source type is to pass the raw payload through
// unconverted. That is silently correct only when the
// runtime tag happens to already match the target's native
// representation (an Integer-tagged value cast `as a
// number` is a no-op that looks like a real conversion);
// for any other tag it reinterprets the bytes - a text
// pointer read as an integer, the same failure mode this
// whole track exists to close, just reached through the
// suggested fix-it rather than around it. The properly
// general fix is a runtime tag dispatch in codegen's Cast
// arm (the tag-branch machinery already exists and is
// proven correct for `Print`'s equivalent dispatch,
// `emit_mixed_print_dispatch`) - tracked as its own follow-
// up rather than attempted here under this session's time
// pressure, in the single highest-risk area for a change
// like that to go wrong. Loud and honest beats silently
// wrong: reject the cast instead of emitting it.
let is_dynamic_source = match value.as_ref() {
Expr::Identifier(name) | Expr::StringLit(name) => {
self.value_typed_names.contains(name.as_str())
}
_ => false,
};
if is_dynamic_source {
// Deliberately not suggesting a workaround: the type
// predicate guard ('X is a number') was checked and
// does NOT narrow X's type inside its own body (still
// rejected there too), so recommending it here would
// repeat the exact mistake this whole check exists to
// avoid - confidently pointing at a dead end. There is
// currently no supported way to convert a genuinely
// dynamically-tagged value; say so plainly rather than
// invent one.
self.push_error(
format!(
"Cannot cast {} to {}: {}'s type is only known at runtime, and casting a dynamically-tagged value is not currently supported by the compiler (a known gap, not yet resolvable from within the language).",
self.operand_label(value),
self.typed_phrase(target_type),
self.operand_label(value),
),
None,
);
}
}
Expr::FileAvailable { path } => {
// `path is available` wraps the path expression; recurse so
// an unknown variable used as the path is caught.
self.analyze_expr(path);
}
Expr::ReapChild { pid } => {
if let Some(p) = pid {
self.analyze_expr(p);
}
}
_ => {}
}
}
}