Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 | 13x 13x 13x 13x 13x 13x 13x 1012x 1012x 1012x 1012x 1012x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 947x 172x 172x 172x 172x 172x 5649x 5649x 5649x 5649x 5649x 1012x 10217x 10240x 10183x 113x 89x 89x 1x 1x 3x 3x 1x 1x 1x 1x 3x 3x 1x 3x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 5x 5x 1x 1x 1x 1x 1648x 1390x 1390x 112x 112x 113x 113x 2x 2x 2x 2x 4x 4x 20x 20x 5x 5x 1x 4x 2x 2x 1x 3x 1798x 5x 5x 5x 5x 5x 3542x 3542x 1515x 3542x 16x 319x 16x 2043x 2009x 2009x 2009x 1808x 722x 75x 10x 68x 87x 74x 74x 74x 2x 72x 36x 36x 3x 69x 69x 69x 67x 2x 2x 2x 2x 2x 1x 1x 1x 8x 173x 53x 8x 8x 12x 138x 26x 26x 6x 5x 1x 6x 28x 70x 96x 6x 975x 985x 985x 985x 1001x 1001x 1001x 1001x 976x 1353x 976x 964x 964x 5x 1089x 1089x 452x 637x 330x 307x 76x 231x 30x 201x 10x 191x 7x 184x 12x 172x 13x 159x 95x 64x 5x 59x 55x 1068x 16x 16x 16x 1052x 85x 84x 1x 1x 1x 225x 13x 58x 59x 6x 615x 615x 615x 615x 615x 402x 213x 615x 180x 180x 180x 180x 66x 24x 66x 2x 213x 615x 615x 28x 184x 184x 184x 81x 30x 28x 30x 30x 30x 1x 1x 1x 1x 30x 1x 1x 29x 29x 14x 24x 21x 16x 16x 15x 6x 3x 217x 247x 2099x 12x 12x 12x 2087x 12x 2075x 10x 20x 10x 2065x 158x 158x 134x 24x 12x 1919x 329x 1590x 1554x 36x 181x 211x 64x 147x 147x 60x 17x 43x 1x 42x 87x 87x 85x 85x 2x 2x 24x 918x 891x 646x 7x 6x 640x 306x 306x 1810x 1810x 90x 1576x 1576x 921x 894x 3x 3x 799x 4x 4x 4x 1x 1x 1x 1x 1x 4x 113x 241x 241x 241x 23x 23x 23x 23x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 23x 1x 24x 23x 1x 24x 24x 26x 25x 25x 1x 26x 1x 1x 24x 1x 24x 72x 12x 12x 12x 12x 27x 2006x 24x 1982x 1x 1981x 33x 1948x 25x 1923x 1923x 25x 1898x 26x 1872x 631x 1241x 1226x 15x 15x 255x 708x 114x 61x 61x 21x 40x 59x 59x 20x 59x 4x 59x 41x 33x 18x 20x 23x 22x 71x 71x 42x 173x 171x 42x 160x 41x 184x 89x 178x 24x 11x 34x 11x 5x 5x 2x 3x 3x 3x 2x 1x 1x 29x 29x 29x 29x 52x 959x 959x 947x 947x 959x 959x 959x 1x 958x 958x 958x 958x 958x 959x 959x 959x 959x 959x 959x 959x 959x 959x 959x 959x 959x 958x 958x 153x 958x 958x 958x 1987x 8x 8x 4x 958x 958x 958x 958x 958x 958x 958x 958x 132x 132x 132x 132x 132x 958x 958x 958x 958x 958x 958x 958x 958x 958x 39x 39x 39x 39x 39x 39x 957x 37x 957x 4x 4x 4x 4x 2x 956x 3x 956x 956x 1604x 1604x 1604x 1604x 1540x 926x 926x 926x 926x 926x 926x 926x 926x 685x 926x 17x 17x 926x 5x 926x 2x 926x 926x 30x 926x 926x 959x 3x 3x 1x 2x 958x 958x 1x 957x 958x 958x 4x 4x 1x 1x 1x 1x 1x 1x 957x 39x 958x 1606x 153x 153x 1453x 143x 143x 1310x 801x 153x 153x 153x 153x 236x 119x 119x 119x 119x 119x 119x 119x 153x 143x 143x 233x 233x 233x 4x 801x 801x 801x 801x 801x 958x 20x 20x 5x 69x 139x 137x 918x 891x 920x 920x 220x 251x 251x 251x 251x 251x 920x 920x 920x 920x 220x 251x 251x 251x 251x 251x 251x 251x 251x 3x 3x 3x 248x 248x 251x 8x 245x 34x 39x 39x 211x 251x 920x 74x 29x 26x 3x 2x 412x 10x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 1x 1604x 153x 1451x 8x 1443x 143x 5x 138x 1300x 57x 11x 46x 1243x 11x 11x 1232x 799x 433x 415x 18x 153x 153x 153x 153x 153x 8x 8x 8x 8x 8x 138x 138x 1x 137x 137x 137x 46x 46x 1x 45x 45x 45x 11x 11x 11x 11x 11x 11x 11x 11x 33x 33x 1x 32x 32x 33x 33x 33x 33x 33x 1x 32x 33x 59x 59x 35x 35x 59x 59x 59x 33x 59x 32x 32x 25x 2x 2x 2x 2x 23x 23x 23x 76x 76x 23x 23x 23x 799x 799x 799x 799x 799x 918x 66x 1x 251x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 247x 241x 241x 35x 201x 201x 247x 247x 247x 4x 5x 4x 4x 4x 243x 243x 33x 37x 33x 2x 2x 2x 241x 241x 238x 230x 116x 114x 114x 867x 674x 653x 77x 74x 172x 817x 864x 864x 2x 29x 26x 24x 1x 864x 864x 864x 181x 683x 683x 2x 681x 681x 683x 683x 677x 6x 683x 2x 4x 4x 1x 3x 3x 2x 1x 683x 683x 86x 597x 597x 597x 7x 590x 590x 161x 429x 7x 7x 7x 7x 7x 2x 5x 161x 24x 137x 125x 12x 161x 1x 11x 144x 864x 414x 450x 20x 7x 450x 450x 2x 2x 1x 2x 2x 2x 64x 64x 13x 13x 1x 63x 63x 17x 17x 17x 20x 16x 1x 1x 1x 147x 5x 5x 5x 142x 2x 140x 6x 12x 6x 6x 134x 47x 87x 52x 52x 10x 5x 1x 1x 330x 330x 330x 330x 183x 330x 330x 330x 330x 330x 330x 330x 330x 330x 152x 46x 2x 330x 327x 327x 330x 330x 330x 2x 2x 2x 402x 402x 36x 366x 366x 4x 237x 184x 184x 184x 184x 184x 184x 184x 77x 163x 30x 10x 7x 12x 95x 5x 13x 8x 8x 8x 8x 8x 8x 25x 1x 24x 631x 631x 631x 137x 494x 494x 32x 494x 26x 26x 2x 24x 468x 468x 1x 466x 468x 451x 43x 43x 1x 42x 425x 425x 21x 2x 425x 425x 2x 1x 424x 1226x 1226x 1226x 2x 1224x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 926x 5x 4x 1647x 1647x 1647x 926x | /**
* C-Next Code Generator
* Transforms C-Next AST to clean, readable C code
*/
import { basename } from "node:path";
import { CommonTokenStream, ParserRuleContext } from "antlr4ng";
import * as Parser from "../../logic/parser/grammar/CNextParser";
import CommentExtractor from "../../logic/analysis/CommentExtractor";
import TypeRegistrationEngine from "./helpers/TypeRegistrationEngine";
import CommentFormatter from "./CommentFormatter";
import IncludeDiscovery from "../../data/IncludeDiscovery";
import IComment from "../../types/IComment";
import TYPE_WIDTH from "./types/TYPE_WIDTH";
import TYPE_MAP from "./types/TYPE_MAP";
import TYPE_LIMITS from "./types/TYPE_LIMITS";
// Issue #60: BITMAP_SIZE and BITMAP_BACKING_TYPE moved to SymbolCollector
import TTypeInfo from "./types/TTypeInfo";
import TParameterInfo from "./types/TParameterInfo";
import ICodeGeneratorOptions from "./types/ICodeGeneratorOptions";
import TypeResolver from "./TypeResolver";
import ICodeGenSymbols from "../../types/ICodeGenSymbols";
import TypeValidator from "./TypeValidator";
import IOrchestrator from "./generators/IOrchestrator";
import IGeneratorInput from "./generators/IGeneratorInput";
import IGeneratorState from "./generators/IGeneratorState";
import TGeneratorEffect from "./generators/TGeneratorEffect";
import TIncludeHeader from "./generators/TIncludeHeader";
import GeneratorRegistry from "./generators/GeneratorRegistry";
// ADR-053: Expression generators (A2)
import generateLiteral from "./generators/expressions/LiteralGenerator";
import binaryExprGenerators from "./generators/expressions/BinaryExprGenerator";
import generateUnaryExpr from "./generators/expressions/UnaryExprGenerator";
import expressionGenerators from "./generators/expressions/ExpressionGenerator";
import generatePostfixExpression from "./generators/expressions/PostfixExpressionGenerator";
// ADR-053: Statement generators (A3)
import controlFlowGenerators from "./generators/statements/ControlFlowGenerator";
import generateCriticalStatement from "./generators/statements/CriticalGenerator";
import atomicGenerators from "./generators/statements/AtomicGenerator";
import switchGenerators from "./generators/statements/SwitchGenerator";
// ADR-053: Declaration generators (A4)
import enumGenerator from "./generators/declarationGenerators/EnumGenerator";
import bitmapGenerator from "./generators/declarationGenerators/BitmapGenerator";
import registerGenerator from "./generators/declarationGenerators/RegisterGenerator";
import scopedRegisterGenerator from "./generators/declarationGenerators/ScopedRegisterGenerator";
import structGenerator from "./generators/declarationGenerators/StructGenerator";
import functionGenerator from "./generators/declarationGenerators/FunctionGenerator";
import scopeGenerator from "./generators/declarationGenerators/ScopeGenerator";
// ADR-109: Extracted utilities
import BitUtils from "../../../utils/BitUtils";
import CppNamespaceUtils from "../../../utils/CppNamespaceUtils";
import FormatUtils from "../../../utils/FormatUtils";
import StringUtils from "../../../utils/StringUtils";
import TypeCheckUtils from "../../../utils/TypeCheckUtils";
import ExpressionUtils from "../../../utils/ExpressionUtils";
// ADR-053: Support generators (A5)
import helperGenerators from "./generators/support/HelperGenerator";
import includeGenerators from "./generators/support/IncludeGenerator";
import commentUtils from "./generators/support/CommentUtils";
// ADR-046: NullCheckAnalyzer for nullable C pointer type detection
import NullCheckAnalyzer from "../../logic/analysis/NullCheckAnalyzer";
// ADR-006: Helper for building member access chains with proper separators
import memberAccessChain from "./memberAccessChain";
// ADR-109: Assignment decomposition (Phase 2)
import AssignmentHandlerRegistry from "./assignment/index";
import AssignmentClassifier from "./assignment/AssignmentClassifier";
import buildAssignmentContext from "./assignment/AssignmentContextBuilder";
// IHandlerDeps removed - handlers now use CodeGenState.generator directly
// Issue #461: LiteralUtils for parsing const values from symbol table
import LiteralUtils from "../../../utils/LiteralUtils";
// Issue #644: Extracted string length counter for strlen caching optimization
import StringLengthCounter from "./analysis/StringLengthCounter";
// Issue #644: C/C++ mode helper for consolidated mode-specific patterns
import CppModeHelper from "./helpers/CppModeHelper";
// Issue #644: Array dimension parsing helper for consolidation
import ArrayDimensionParser from "./helpers/ArrayDimensionParser";
// Issue #644: Member chain analyzer for bit access pattern detection
import MemberChainAnalyzer from "./analysis/MemberChainAnalyzer";
// Issue #644: Float bit write helper for shadow variable pattern
import FloatBitHelper from "./helpers/FloatBitHelper";
// Issue #644: String declaration helper for bounded/array/concat strings
// Note: StringDeclHelper is now used via VariableDeclHelper
// Issue #794: Argument generation helper for ADR-006 semantics
import ArgumentGenerator from "./helpers/ArgumentGenerator";
// Issue #644: Enum assignment validator for type-safe enum assignments
import EnumAssignmentValidator from "./helpers/EnumAssignmentValidator";
// Issue #644: Array initialization helper for size inference and fill-all
// Note: ArrayInitHelper is now used via VariableDeclHelper
// Issue #644: Assignment expected type resolution helper
import AssignmentExpectedTypeResolver from "./helpers/AssignmentExpectedTypeResolver";
// PR #715: C++ member conversion helper for improved testability
import CppMemberHelper from "./helpers/CppMemberHelper";
import IPostfixOp from "./helpers/types/IPostfixOp";
// PR #715: Boolean conversion helper for improved testability
import BooleanHelper from "./helpers/BooleanHelper";
// PR #715: C++ constructor detection helper for improved testability
import CppConstructorHelper from "./helpers/CppConstructorHelper";
// PR #715: Set/Map utilities for improved testability
import SetMapHelper from "./helpers/SetMapHelper";
// PR #715: Symbol lookup utilities for improved testability
import SymbolLookupHelper from "./helpers/SymbolLookupHelper";
// Issue #644: Assignment validation coordinator helper
import AssignmentValidator from "./helpers/AssignmentValidator";
// Issue #696: Variable modifier extraction helper
// Note: VariableModifierBuilder is now used via VariableDeclHelper
// Issue #792: Variable declaration helper
import VariableDeclHelper from "./helpers/VariableDeclHelper";
// String operation detection and extraction
import StringOperationsHelper from "./helpers/StringOperationsHelper";
// PR #681: Extracted separator and dereference resolution utilities
import MemberSeparatorResolver from "./helpers/MemberSeparatorResolver";
import ParameterDereferenceResolver from "./helpers/ParameterDereferenceResolver";
// SonarCloud S3776: Extracted helpers for assignment target generation
import PostfixChainBuilder from "./helpers/PostfixChainBuilder";
import SimpleIdentifierResolver from "./helpers/SimpleIdentifierResolver";
import BaseIdentifierBuilder from "./helpers/BaseIdentifierBuilder";
import ISimpleIdentifierDeps from "./types/ISimpleIdentifierDeps";
import IPostfixChainDeps from "./types/IPostfixChainDeps";
import IPostfixOperation from "./types/IPostfixOperation";
// Issue #707: Expression unwrapping utility for reducing duplication
import ExpressionUnwrapper from "../../../utils/ExpressionUnwrapper";
// Stateless parser utilities extracted from CodeGenerator
import CodegenParserUtils from "./utils/CodegenParserUtils";
import IMemberSeparatorDeps from "./types/IMemberSeparatorDeps";
import IParameterDereferenceDeps from "./types/IParameterDereferenceDeps";
import ISeparatorContext from "./types/ISeparatorContext";
// Issue #269: Transitive modification propagation for const inference (used by analyzeModificationsOnly)
import TransitiveModificationPropagator from "../../logic/analysis/helpers/TransitiveModificationPropagator";
// Phase 3: Type generation helper for improved testability
import TypeGenerationHelper from "./helpers/TypeGenerationHelper";
// Phase 5: Cast validation helper for improved testability
import CastValidator from "./helpers/CastValidator";
// Issue #793: Function context lifecycle and parameter processing helper
import FunctionContextManager from "./helpers/FunctionContextManager";
import IFunctionContextCallbacks from "./types/IFunctionContextCallbacks";
// Global state for code generation (simplifies debugging, eliminates DI complexity)
import CodeGenState from "../../state/CodeGenState";
// Issue #269: Pass-by-value analysis extracted from CodeGenerator
import PassByValueAnalyzer from "../../logic/analysis/PassByValueAnalyzer";
// Unified parameter generation (Phase 1)
import ParameterInputAdapter from "./helpers/ParameterInputAdapter";
import ParameterSignatureBuilder from "./helpers/ParameterSignatureBuilder";
// Issue #895: Parse typedef signatures to determine pointer vs value params
// Extracted resolvers that use CodeGenState
import SizeofResolver from "./resolution/SizeofResolver";
import EnumTypeResolver from "./resolution/EnumTypeResolver";
import ScopeResolver from "./resolution/ScopeResolver";
// Issue #797: Centralized C-style name generation
import QualifiedNameGenerator from "./utils/QualifiedNameGenerator";
const {
generateOverflowHelpers: helperGenerateOverflowHelpers,
generateSafeDivHelpers: helperGenerateSafeDivHelpers,
} = helperGenerators;
const {
transformIncludeDirective: includeTransformIncludeDirective,
processPreprocessorDirective: includeProcessPreprocessorDirective,
} = includeGenerators;
const {
getLeadingComments: commentGetLeadingComments,
formatLeadingComments: commentFormatLeadingComments,
} = commentUtils;
/**
* Maps C-Next assignment operators to C assignment operators
*/
const ASSIGNMENT_OPERATOR_MAP: Record<string, string> = {
"<-": "=",
"+<-": "+=",
"-<-": "-=",
"*<-": "*=",
"/<-": "/=",
"%<-": "%=",
"&<-": "&=",
"|<-": "|=",
"^<-": "^=",
"<<<-": "<<=",
">><-": ">>=",
};
/**
* ADR-013: Function signature for const parameter tracking
* Used to validate const-to-non-const errors at call sites
*/
interface FunctionSignature {
name: string;
parameters: Array<{
name: string;
baseType: string; // The C-Next type (e.g., 'u32', 'f32')
isConst: boolean;
isArray: boolean;
}>;
}
/**
* ADR-049: Target platform capabilities for code generation
*/
interface TargetCapabilities {
wordSize: 8 | 16 | 32;
hasLdrexStrex: boolean;
hasBasepri: boolean;
}
/**
* ADR-049: Target platform capability map
*/
const TARGET_CAPABILITIES: Record<string, TargetCapabilities> = {
teensy41: { wordSize: 32, hasLdrexStrex: true, hasBasepri: true },
teensy40: { wordSize: 32, hasLdrexStrex: true, hasBasepri: true },
"cortex-m7": { wordSize: 32, hasLdrexStrex: true, hasBasepri: true },
"cortex-m4": { wordSize: 32, hasLdrexStrex: true, hasBasepri: true },
"cortex-m3": { wordSize: 32, hasLdrexStrex: true, hasBasepri: true },
"cortex-m0+": { wordSize: 32, hasLdrexStrex: true, hasBasepri: false },
"cortex-m0": { wordSize: 32, hasLdrexStrex: false, hasBasepri: false },
avr: { wordSize: 8, hasLdrexStrex: false, hasBasepri: false },
};
/**
* ADR-049: Default target capabilities (safe fallback)
*/
const DEFAULT_TARGET: TargetCapabilities = {
wordSize: 32,
hasLdrexStrex: false,
hasBasepri: false,
};
/**
* Code Generator - Transpiles C-Next to C
*
* Implements IOrchestrator to support modular generator extraction (ADR-053).
*/
export default class CodeGenerator implements IOrchestrator {
/** Lookup map for primitive type zero initializers */
private static readonly PRIMITIVE_ZERO_VALUES: ReadonlyMap<string, string> =
new Map([
["bool", "false"],
["f32", "0.0f"],
["f64", "0.0"],
]);
/** Token stream for comment extraction (ADR-043) */
private tokenStream: CommonTokenStream | null = null;
private commentExtractor: CommentExtractor | null = null;
private readonly commentFormatter: CommentFormatter = new CommentFormatter();
/** Type resolution and classification - now a static class, no instance needed */
/** Symbol collection - ADR-055: Now uses ISymbolInfo from TSymbolInfoAdapter */
public symbols: ICodeGenSymbols | null = null;
/** Issue #644: String declaration helper for bounded/array/concat strings */
/** Issue #644: Array initialization helper for size inference and fill-all */
/** Generator registry for modular code generation (ADR-053) */
private readonly registry: GeneratorRegistry = new GeneratorRegistry();
/**
* Initialize generator registry with extracted generators.
* Called once before code generation begins.
*/
private initializeGenerators(): void {
// Phase 1: Simple leaf generators
this.registry.registerDeclaration("enum", enumGenerator);
this.registry.registerDeclaration("bitmap", bitmapGenerator);
this.registry.registerDeclaration("register", registerGenerator);
// Note: generateScopedRegister has a different signature (extra scopeName param)
// and is called directly rather than through the registry
// Phase 2: Medium complexity generators
this.registry.registerDeclaration("struct", structGenerator);
// Phase 3: Complex generators
this.registry.registerDeclaration("function", functionGenerator);
// Phase 4: Composite generators
this.registry.registerDeclaration("scope", scopeGenerator);
// Statement generators (ADR-053 A3)
// Note: generateSwitchCase, generateCaseLabel, generateDefaultCase have extra
// switchEnumType param and are called directly rather than through the registry.
// Same for generateForVarDecl, generateForAssignment - internal helpers.
this.registry.registerStatement(
"return",
controlFlowGenerators.generateReturn,
);
this.registry.registerStatement("if", controlFlowGenerators.generateIf);
this.registry.registerStatement(
"while",
controlFlowGenerators.generateWhile,
);
this.registry.registerStatement(
"do-while",
controlFlowGenerators.generateDoWhile,
);
this.registry.registerStatement("for", controlFlowGenerators.generateFor);
this.registry.registerStatement("switch", switchGenerators.generateSwitch);
this.registry.registerStatement("critical", generateCriticalStatement);
// Expression generators (ADR-053 A2)
this.registry.registerExpression(
"expression",
expressionGenerators.generateExpression,
);
this.registry.registerExpression(
"ternary",
expressionGenerators.generateTernaryExpr,
);
this.registry.registerExpression("or", binaryExprGenerators.generateOrExpr);
this.registry.registerExpression(
"and",
binaryExprGenerators.generateAndExpr,
);
this.registry.registerExpression(
"equality",
binaryExprGenerators.generateEqualityExpr,
);
this.registry.registerExpression(
"relational",
binaryExprGenerators.generateRelationalExpr,
);
this.registry.registerExpression(
"bitwise-or",
binaryExprGenerators.generateBitwiseOrExpr,
);
this.registry.registerExpression(
"bitwise-xor",
binaryExprGenerators.generateBitwiseXorExpr,
);
this.registry.registerExpression(
"bitwise-and",
binaryExprGenerators.generateBitwiseAndExpr,
);
this.registry.registerExpression(
"shift",
binaryExprGenerators.generateShiftExpr,
);
this.registry.registerExpression(
"additive",
binaryExprGenerators.generateAdditiveExpr,
);
this.registry.registerExpression(
"multiplicative",
binaryExprGenerators.generateMultiplicativeExpr,
);
this.registry.registerExpression("unary", generateUnaryExpr);
this.registry.registerExpression("literal", generateLiteral);
}
/**
* Invoke a registered statement generator by name.
* Reduces boilerplate in wrapper methods.
*/
private invokeStatement(name: string, ctx: ParserRuleContext): string {
const generator = this.registry.getStatement(name);
Iif (!generator) {
throw new Error(`${name} statement generator not registered`);
}
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
/**
* Invoke a registered expression generator by name.
* Reduces boilerplate in wrapper methods.
*/
private invokeExpression(name: string, ctx: ParserRuleContext): string {
const generator = this.registry.getExpression(name);
Iif (!generator) {
throw new Error(`${name} expression generator not registered`);
}
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
private generatorsInitialized = false;
// ===========================================================================
// IOrchestrator Implementation (ADR-053)
// ===========================================================================
/**
* Get read-only input context for generators.
* Contains all the information generators need to produce code.
*/
getInput(): IGeneratorInput {
return {
symbolTable: CodeGenState.symbolTable,
symbols: CodeGenState.symbols,
typeRegistry: CodeGenState.getTypeRegistryView(),
functionSignatures: CodeGenState.functionSignatures,
knownFunctions: CodeGenState.knownFunctions,
knownStructs: CodeGenState.symbols?.knownStructs ?? new Set(),
constValues: CodeGenState.constValues,
callbackTypes: CodeGenState.callbackTypes,
callbackFieldTypes: CodeGenState.callbackFieldTypes,
targetCapabilities: CodeGenState.targetCapabilities,
debugMode: CodeGenState.debugMode,
};
}
/**
* Get a snapshot of the current generation state.
* Represents where we are in the AST traversal.
*/
getState(): IGeneratorState {
return {
currentScope: CodeGenState.currentScope,
indentLevel: CodeGenState.indentLevel,
inFunctionBody: CodeGenState.inFunctionBody,
currentParameters: CodeGenState.currentParameters,
localVariables: CodeGenState.localVariables,
localArrays: CodeGenState.localArrays,
expectedType: CodeGenState.expectedType,
selfIncludeAdded: CodeGenState.selfIncludeAdded, // Issue #369
// Issue #644: Postfix expression state
scopeMembers: CodeGenState.getAllScopeMembers(),
mainArgsName: CodeGenState.mainArgsName,
floatBitShadows: CodeGenState.floatBitShadows,
floatShadowCurrent: CodeGenState.floatShadowCurrent,
lengthCache: CodeGenState.lengthCache,
};
}
/**
* Process effects returned by generators, updating internal state.
* This centralizes all side-effect handling.
*/
applyEffects(effects: readonly TGeneratorEffect[]): void {
for (const effect of effects) {
switch (effect.type) {
// Include effects - delegate to requireInclude()
case "include":
this.requireInclude(effect.header);
break;
case "isr":
this.requireInclude("isr");
break;
// Helper function effects
case "helper":
CodeGenState.usedClampOps.add(
`${effect.operation}_${effect.cnxType}`,
);
break;
case "safe-div":
CodeGenState.usedSafeDivOps.add(
`${effect.operation}_${effect.cnxType}`,
);
break;
// Type registration effects
case "register-type":
CodeGenState.setVariableTypeInfo(effect.name, effect.info);
break;
case "register-local":
CodeGenState.localVariables.add(effect.name);
if (effect.isArray) {
CodeGenState.localArrays.add(effect.name);
}
break;
case "register-const-value":
CodeGenState.constValues.set(effect.name, effect.value);
break;
// Scope effects (ADR-016)
case "set-scope":
CodeGenState.currentScope = effect.name;
break;
// Function body effects
case "enter-function-body":
CodeGenState.inFunctionBody = true;
CodeGenState.localVariables.clear();
CodeGenState.localArrays.clear();
CodeGenState.floatBitShadows.clear();
CodeGenState.floatShadowCurrent.clear();
break;
case "exit-function-body":
CodeGenState.inFunctionBody = false;
CodeGenState.localVariables.clear();
CodeGenState.localArrays.clear();
CodeGenState.floatBitShadows.clear();
CodeGenState.floatShadowCurrent.clear();
break;
case "set-parameters":
CodeGenState.currentParameters = new Map(effect.params);
break;
case "clear-parameters":
CodeGenState.currentParameters.clear();
break;
// Callback effects
case "register-callback-field":
CodeGenState.callbackFieldTypes.set(effect.key, effect.typeName);
break;
// Array initializer effects
case "set-array-init-count":
CodeGenState.lastArrayInitCount = effect.count;
break;
case "set-array-fill-value":
CodeGenState.lastArrayFillValue = effect.value;
break;
}
}
}
/**
* Register a required include header. Centralizes all include flag management
* to reduce scattered assignments throughout the codebase.
*
* @param header - The header to require (stdint, stdbool, string, etc.)
*/
private requireInclude(header: TIncludeHeader): void {
switch (header) {
case "stdint":
CodeGenState.needsStdint = true;
break;
case "stdbool":
CodeGenState.needsStdbool = true;
break;
case "string":
CodeGenState.needsString = true;
break;
case "cmsis":
CodeGenState.needsCMSIS = true;
break;
case "limits":
CodeGenState.needsLimits = true;
break;
case "isr":
CodeGenState.needsISR = true;
break;
case "float_static_assert":
CodeGenState.needsFloatStaticAssert = true;
break;
case "irq_wrappers":
CodeGenState.needsIrqWrappers = true;
break;
}
}
/**
* Get the current indentation string.
*/
getIndent(): string {
return FormatUtils.indent(CodeGenState.indentLevel);
}
/**
* Resolve an identifier to its fully-scoped name.
* Part of IOrchestrator interface.
* ADR-016: Inside a scope, checks if the identifier is a scope member first.
* Otherwise returns the identifier unchanged (global scope).
*/
resolveIdentifier(identifier: string): string {
// Check current scope first (inner scope shadows outer)
if (CodeGenState.currentScope) {
const members = CodeGenState.getScopeMembers(CodeGenState.currentScope);
if (members?.has(identifier)) {
return `${CodeGenState.currentScope}_${identifier}`;
}
}
// Fall back to global scope
return identifier;
}
// === Expression Generation (ADR-053 A2) ===
/**
* Generate a C expression from any expression context.
* Part of IOrchestrator interface.
*/
generateExpression(ctx: Parser.ExpressionContext): string {
return this.invokeExpression("expression", ctx);
}
/**
* Issue #477: Generate expression with a specific expected type context.
* Used by return statements to resolve unqualified enum values.
* Note: Uses explicit save/restore (not withExpectedType) to support null values.
*/
generateExpressionWithExpectedType(
ctx: Parser.ExpressionContext,
expectedType: string | null,
): string {
const saved = CodeGenState.expectedType;
CodeGenState.expectedType = expectedType;
try {
return this.generateExpression(ctx);
} finally {
CodeGenState.expectedType = saved;
}
}
/**
* Generate type translation (C-Next type -> C type).
* Part of IOrchestrator interface.
*/
generateType(ctx: Parser.TypeContext): string {
// Track required includes based on type usage
const requiredInclude = TypeGenerationHelper.getRequiredInclude(ctx);
if (requiredInclude) {
this.requireInclude(requiredInclude);
}
// Generate the C type using the helper with dependencies
return TypeGenerationHelper.generate(ctx, {
currentScope: CodeGenState.currentScope,
isCppScopeSymbol: (name) => this.isCppScopeSymbol(name),
checkNeedsStructKeyword: (name) =>
CodeGenState.symbolTable.checkNeedsStructKeyword(name),
validateCrossScopeVisibility: (scope, member) =>
ScopeResolver.validateCrossScopeVisibility(scope, member),
});
}
/**
* Generate a unary expression.
* Part of IOrchestrator interface.
*/
generateUnaryExpr(ctx: Parser.UnaryExpressionContext): string {
return this.invokeExpression("unary", ctx);
}
/**
* Generate a postfix expression.
* Part of IOrchestrator interface.
* Issue #644: Delegates to extracted PostfixExpressionGenerator.
*/
generatePostfixExpr(ctx: Parser.PostfixExpressionContext): string {
const result = generatePostfixExpression(
ctx,
this.getInput(),
this.getState(),
this,
);
this.applyEffects(result.effects);
return result.code;
}
/**
* Generate the full precedence chain from or-expression down.
* Part of IOrchestrator interface.
*/
generateOrExpr(ctx: Parser.OrExpressionContext): string {
return this.invokeExpression("or", ctx);
}
// === Type Utilities ===
/**
* Check if a type name is a known struct.
* Part of IOrchestrator interface.
*/
isKnownStruct(typeName: string): boolean {
return SymbolLookupHelper.isKnownStruct(
CodeGenState.symbols?.knownStructs,
CodeGenState.symbols?.knownBitmaps,
CodeGenState.symbolTable,
typeName,
);
}
/**
* Check if a type is a float type.
* Part of IOrchestrator interface - delegates to TypeResolver.
*/
isFloatType(typeName: string): boolean {
return TypeResolver.isFloatType(typeName);
}
/**
* Check if a type is an integer type.
* Part of IOrchestrator interface - delegates to TypeResolver.
*/
isIntegerType(typeName: string): boolean {
return TypeResolver.isIntegerType(typeName);
}
/**
* Check if a function is defined in C-Next.
* Part of IOrchestrator interface.
*/
isCNextFunction(name: string): boolean {
return SymbolLookupHelper.isCNextFunctionCombined(
CodeGenState.knownFunctions,
CodeGenState.symbolTable,
name,
);
}
// === Expression Analysis ===
/**
* Get the enum type of an expression.
* Part of IOrchestrator interface - delegates to private implementation.
*/
getExpressionEnumType(
ctx: Parser.ExpressionContext | Parser.RelationalExpressionContext,
): string | null {
return EnumTypeResolver.resolve(ctx);
}
/**
* Check if an expression is an integer literal or variable.
* Part of IOrchestrator interface - delegates to private implementation.
*/
isIntegerExpression(
ctx: Parser.ExpressionContext | Parser.RelationalExpressionContext,
): boolean {
return this._isIntegerExpression(ctx);
}
/**
* Check if an expression is a string type.
* Part of IOrchestrator interface.
* ADR-045: Used to detect string comparisons and generate strcmp().
* Issue #137: Extended to handle array element access (e.g., names[0])
*/
isStringExpression(ctx: Parser.RelationalExpressionContext): boolean {
const text = ctx.getText();
// Check for string literals
if (text.startsWith('"') && text.endsWith('"')) {
return true;
}
// Check if it's a simple variable of string type
if (/^[a-zA-Z_]\w*$/.exec(text)) {
const typeInfo = CodeGenState.getVariableTypeInfo(text);
if (typeInfo?.isString) {
return true;
}
}
// Issue #137: Check for array element access (e.g., names[0], arr[i])
return this._isArrayAccessStringExpression(text);
}
/**
* Check if array access expression evaluates to a string.
* Extracted from isStringExpression to reduce cognitive complexity.
*/
private _isArrayAccessStringExpression(text: string): boolean {
// Pattern: identifier[expression] or identifier[expression][expression]...
// BUT NOT if accessing properties that return numbers, not strings
const arrayAccessMatch = /^([a-zA-Z_]\w*)\[/.exec(text);
if (!arrayAccessMatch) {
return false;
}
// ADR-045/ADR-058: String/array properties return numeric values, not strings
// ADR-058: .length deprecated, replaced by .bit_length, .byte_length,
// .element_count, .char_count
Iif (
text.endsWith(".length") ||
text.endsWith(".capacity") ||
text.endsWith(".size") ||
text.endsWith(".bit_length") ||
text.endsWith(".byte_length") ||
text.endsWith(".element_count") ||
text.endsWith(".char_count")
) {
return false;
}
const arrayName = arrayAccessMatch[1];
const typeInfo = CodeGenState.getVariableTypeInfo(arrayName);
Iif (!typeInfo) {
return false;
}
// Check if it's an ARRAY OF STRINGS (not a single string being indexed)
// A single string<50> has arrayDimensions=[51] (just the char buffer)
// An array of strings string<50>[10] has arrayDimensions=[10, 51]
// Single string indexing (e.g., userName[i]) returns a char, not a string
// Array of strings indexing (e.g., names[0]) returns a string
if (typeInfo.isString) {
// For strings, only treat as string expression if it's an array of strings
// (arrayDimensions.length > 1 means it's string<N>[M], not just string<N>)
const dims = typeInfo.arrayDimensions;
return Array.isArray(dims) && dims.length > 1;
}
// Non-string array with string base type
return Boolean(
typeInfo.isArray &&
typeInfo.baseType &&
TypeCheckUtils.isString(typeInfo.baseType),
);
}
/**
* Get type of additive expression.
* Part of IOrchestrator interface - delegates to private implementation.
*/
getAdditiveExpressionType(
ctx: Parser.AdditiveExpressionContext,
): string | null {
return this._getAdditiveExpressionType(ctx);
}
/**
* Extract operators from parse tree children in correct order.
* Part of IOrchestrator interface - delegates to CodegenParserUtils.
*/
getOperatorsFromChildren(ctx: ParserRuleContext): string[] {
return CodegenParserUtils.getOperatorsFromChildren(ctx);
}
// === Validation ===
/**
* Validate cross-scope member visibility.
* Part of IOrchestrator interface - delegates to private implementation.
*/
validateCrossScopeVisibility(
scopeName: string,
memberName: string,
isGlobalAccess: boolean = false,
): void {
ScopeResolver.validateCrossScopeVisibility(
scopeName,
memberName,
isGlobalAccess,
);
}
/**
* Validate shift amount is within type bounds.
* Part of IOrchestrator interface - delegates to TypeValidator.
*/
validateShiftAmount(
leftType: string,
rightExpr: Parser.AdditiveExpressionContext,
op: string,
ctx: Parser.ShiftExpressionContext,
): void {
TypeValidator.validateShiftAmount(leftType, rightExpr, op, ctx);
}
/**
* Validate ternary condition is a comparison (ADR-022).
* Part of IOrchestrator interface - delegates to TypeValidator.
*/
validateTernaryCondition(condition: Parser.OrExpressionContext): void {
TypeValidator.validateTernaryCondition(condition);
}
/**
* Validate no nested ternary expressions (ADR-022).
* Part of IOrchestrator interface - delegates to TypeValidator.
*/
validateNoNestedTernary(
expr: Parser.OrExpressionContext,
branchName: string,
): void {
TypeValidator.validateNoNestedTernary(expr, branchName);
}
// === Function Call Helpers (ADR-053 A2 Phase 5) ===
/**
* Get simple identifier from expression, or null if complex.
* Part of IOrchestrator interface - delegates to CodegenParserUtils.
*/
getSimpleIdentifier(ctx: Parser.ExpressionContext): string | null {
return CodegenParserUtils.getSimpleIdentifier(ctx);
}
/**
* Generate function argument with pass-by-reference handling.
* Part of IOrchestrator interface - delegates to ArgumentGenerator.
*/
generateFunctionArg(
ctx: Parser.ExpressionContext,
targetParamBaseType?: string,
): string {
const simpleId = CodegenParserUtils.getSimpleIdentifier(ctx);
return ArgumentGenerator.generateArg(ctx, simpleId, targetParamBaseType, {
getLvalueType: (c) => this.getLvalueType(c),
getMemberAccessArrayStatus: (c) => this.getMemberAccessArrayStatus(c),
needsCppMemberConversion: (c, t) => this.needsCppMemberConversion(c, t),
isStringSubscriptAccess: (c) => this.isStringSubscriptAccess(c),
generateExpression: (c) => this.generateExpression(c),
});
}
/**
* Check if a value is const.
* Part of IOrchestrator interface - delegates to TypeValidator.
*/
isConstValue(name: string): boolean {
return TypeValidator.isConstValue(name);
}
/**
* Get known enums set for pass-by-value detection.
* Part of IOrchestrator interface.
*/
getKnownEnums(): ReadonlySet<string> {
return CodeGenState.symbols!.knownEnums;
}
/**
* Issue #304: Check if we're generating C++ output.
* Part of IOrchestrator interface.
*/
isCppMode(): boolean {
return CodeGenState.cppMode;
}
/**
* Issue #304: Check if a type is a C++ enum class (scoped enum).
* These require explicit casts to integer types in C++.
* Part of IOrchestrator interface.
*/
isCppEnumClass(typeName: string): boolean {
return SymbolLookupHelper.isCppEnumClass(
CodeGenState.symbolTable,
typeName,
);
}
/**
* Issue #304: Get the type of an expression.
* Part of IOrchestrator interface.
*/
getExpressionType(ctx: Parser.ExpressionContext): string | null {
return TypeResolver.getExpressionType(ctx);
}
/**
* Generate a block (curly braces with statements).
* Part of IOrchestrator interface (ADR-053 A3).
*/
generateBlock(ctx: Parser.BlockContext): string {
const lines: string[] = ["{"];
const innerIndent = FormatUtils.indent(1); // One level of relative indentation
for (const stmt of ctx.statement()) {
// Temporarily increment for any nested context that needs absolute level
CodeGenState.indentLevel++;
const stmtCode = this.generateStatement(stmt);
CodeGenState.indentLevel--;
if (stmtCode) {
// Add one level of indent to each line (relative indentation)
const indentedLines = stmtCode
.split("\n")
.map((line) => innerIndent + line);
lines.push(indentedLines.join("\n"));
}
}
lines.push("}");
return lines.join("\n");
}
/**
* Validate no early exits (return/break) in critical blocks.
* Part of IOrchestrator interface (ADR-053 A3).
*/
validateNoEarlyExits(ctx: Parser.BlockContext): void {
TypeValidator.validateNoEarlyExits(ctx);
}
/**
* Generate a single statement.
* Part of IOrchestrator interface (ADR-053 A3).
*/
generateStatement(ctx: Parser.StatementContext): string {
let result = "";
if (ctx.variableDeclaration()) {
result = this.generateVariableDecl(ctx.variableDeclaration()!);
} else if (ctx.assignmentStatement()) {
result = this.generateAssignment(ctx.assignmentStatement()!);
} else if (ctx.expressionStatement()) {
result =
this.generateExpression(ctx.expressionStatement()!.expression()) + ";";
} else if (ctx.ifStatement()) {
result = this.generateIf(ctx.ifStatement()!);
} else if (ctx.whileStatement()) {
result = this.generateWhile(ctx.whileStatement()!);
} else if (ctx.doWhileStatement()) {
result = this.generateDoWhile(ctx.doWhileStatement()!);
} else if (ctx.forStatement()) {
result = this.generateFor(ctx.forStatement()!);
} else if (ctx.switchStatement()) {
result = this.generateSwitch(ctx.switchStatement()!);
} else if (ctx.returnStatement()) {
result = this.generateReturn(ctx.returnStatement()!);
} else if (ctx.criticalStatement()) {
// ADR-050: Critical statement for atomic multi-variable operations
result = this.generateCriticalStatement(ctx.criticalStatement()!);
} else if (ctx.block()) {
result = this.generateBlock(ctx.block()!);
}
// Issue #250: Prepend any pending temp variable declarations (C++ mode)
if (CodeGenState.pendingTempDeclarations.length > 0) {
const tempDecls = CodeGenState.pendingTempDeclarations.join("\n");
CodeGenState.pendingTempDeclarations = [];
return tempDecls + "\n" + result;
}
return result;
}
/**
* Issue #250: Flush pending temp variable declarations.
* Returns declarations as a single string and clears the pending list.
* Part of IOrchestrator interface.
*/
flushPendingTempDeclarations(): string {
if (CodeGenState.pendingTempDeclarations.length === 0) {
return "";
}
const decls = CodeGenState.pendingTempDeclarations.join("\n");
CodeGenState.pendingTempDeclarations = [];
return decls;
}
/**
* Get indentation string for current level.
* Part of IOrchestrator interface (ADR-053 A3).
*/
indent(text: string): string {
return FormatUtils.indentAllLines(text, CodeGenState.indentLevel);
}
/**
* Validate switch statement.
* Part of IOrchestrator interface (ADR-053 A3).
*/
validateSwitchStatement(
ctx: Parser.SwitchStatementContext,
switchExpr: Parser.ExpressionContext,
): void {
TypeValidator.validateSwitchStatement(ctx, switchExpr);
}
/**
* Validate condition is a boolean expression (ADR-027, Issue #884).
* Part of IOrchestrator interface (ADR-053 A3).
*/
validateConditionIsBoolean(
ctx: Parser.ExpressionContext,
conditionType: string,
): void {
TypeValidator.validateConditionIsBoolean(ctx, conditionType);
}
/**
* Issue #254: Validate no function calls in condition (E0702).
* Part of IOrchestrator interface (ADR-053 A3).
*/
validateConditionNoFunctionCall(
ctx: Parser.ExpressionContext,
conditionType: string,
): void {
TypeValidator.validateConditionNoFunctionCall(ctx, conditionType);
}
/**
* Issue #254: Validate no function calls in ternary condition (E0702).
* Part of IOrchestrator interface (ADR-053 A2).
*/
validateTernaryConditionNoFunctionCall(
ctx: Parser.OrExpressionContext,
): void {
TypeValidator.validateTernaryConditionNoFunctionCall(ctx);
}
/**
* Generate an assignment target.
* Part of IOrchestrator interface (ADR-053 A3).
* Issue #387: Unified postfix chain - all patterns now use IDENTIFIER postfixTargetOp*
*/
generateAssignmentTarget(ctx: Parser.AssignmentTargetContext): string {
const hasGlobal = ctx.GLOBAL() !== null;
const hasThis = ctx.THIS() !== null;
const identifier = ctx.IDENTIFIER()?.getText();
const postfixOps = ctx.postfixTargetOp();
// SonarCloud S3776: Use SimpleIdentifierResolver for simple identifier case
if (!hasGlobal && !hasThis && postfixOps.length === 0 && identifier) {
return SimpleIdentifierResolver.resolve(
identifier,
this._buildSimpleIdentifierDeps(),
);
}
// Issue #779: Resolve bare scope member identifiers before postfix chain processing
// This ensures scope members get their prefix even with array/member access.
// Skip parameters - they don't need scope resolution and shouldn't be dereferenced
// when used with array indexing (buf[idx] is valid C for pointer params).
// Also skip known registers - they should be handled by the postfix chain builder
// to enable proper register validation (requiring global. when shadowed).
let resolvedIdentifier = identifier ?? "";
if (!hasGlobal && !hasThis && identifier) {
const isParameter = CodeGenState.currentParameters.has(identifier);
const isLocalVariable = CodeGenState.localVariables.has(identifier);
const isKnownRegister =
CodeGenState.symbols?.knownRegisters.has(identifier);
if (!isParameter && !isLocalVariable && !isKnownRegister) {
const resolved = TypeValidator.resolveBareIdentifier(
identifier,
false, // not local
(name: string) => this.isKnownStruct(name),
);
if (resolved !== null) {
resolvedIdentifier = resolved;
}
}
}
// SonarCloud S3776: Use BaseIdentifierBuilder for base identifier
const safeIdentifier = identifier ?? "";
const { result: baseResult, firstId } = BaseIdentifierBuilder.build(
hasGlobal || hasThis ? safeIdentifier : resolvedIdentifier,
hasGlobal,
hasThis,
CodeGenState.currentScope,
);
// No postfix operations - return base
if (postfixOps.length === 0) {
return baseResult;
}
// SonarCloud S3776: Use PostfixChainBuilder for postfix operations
const operations = this._extractPostfixOperations(postfixOps);
const postfixDeps = this._buildPostfixChainDeps(
firstId,
hasGlobal,
hasThis,
);
return PostfixChainBuilder.build(
baseResult,
firstId,
operations,
postfixDeps,
);
}
/**
* Generate array dimensions.
* Part of IOrchestrator interface (ADR-053 A3).
*/
generateArrayDimensions(dims: Parser.ArrayDimensionContext[]): string {
return dims.map((d) => this.generateArrayDimension(d)).join("");
}
// === strlen Optimization (ADR-053 A3) ===
/**
* Count string length accesses for caching.
* Part of IOrchestrator interface (ADR-053 A3).
*/
countStringLengthAccesses(
ctx: Parser.ExpressionContext,
): Map<string, number> {
// Issue #644: Delegate to extracted StringLengthCounter (now static)
return StringLengthCounter.countExpression(ctx);
}
/**
* Count block length accesses.
* Part of IOrchestrator interface (ADR-053 A3).
*/
countBlockLengthAccesses(
ctx: Parser.BlockContext,
counts: Map<string, number>,
): void {
// Issue #644: Delegate to extracted StringLengthCounter (now static)
StringLengthCounter.countBlockInto(ctx, counts);
}
/**
* Setup length cache and return declarations.
* Part of IOrchestrator interface (ADR-053 A3).
*/
setupLengthCache(counts: Map<string, number>): string {
const declarations: string[] = [];
const cache = new Map<string, string>();
for (const [varName, count] of counts) {
Eif (count >= 2) {
const tempVar = `_${varName}_len`;
cache.set(varName, tempVar);
declarations.push(`size_t ${tempVar} = strlen(${varName});`);
}
}
if (declarations.length > 0) {
CodeGenState.lengthCache = cache;
return declarations.join("\n") + "\n";
}
return "";
}
/**
* Clear length cache.
* Part of IOrchestrator interface (ADR-053 A3).
*/
clearLengthCache(): void {
CodeGenState.lengthCache = null;
}
/**
* Register a local variable.
* Part of IOrchestrator interface (ADR-053 A3).
*/
registerLocalVariable(name: string): void {
CodeGenState.localVariables.add(name);
}
// === Declaration Generation (ADR-053 A4) ===
/** Generate single array dimension */
generateArrayDimension(dim: Parser.ArrayDimensionContext): string {
if (dim.expression()) {
// Bug #8: At file scope, resolve const values to numeric literals
// because C doesn't allow const variables as array sizes at file scope
if (!CodeGenState.inFunctionBody) {
const constValue = this.tryEvaluateConstant(dim.expression()!);
if (constValue !== undefined) {
return `[${constValue}]`;
}
}
return `[${this.generateExpression(dim.expression()!)}]`;
}
return "[]";
}
/** Generate parameter list for function signature */
generateParameterList(ctx: Parser.ParameterListContext): string {
return ctx
.parameter()
.map((p, index) => this.generateParameter(p, index))
.join(", ");
}
/** Get the raw type name without C conversion */
getTypeName(ctx: Parser.TypeContext): string {
// ADR-016: Handle this.Type for scoped types (e.g., this.State -> Motor_State)
if (ctx.scopedType()) {
const typeName = ctx.scopedType()!.IDENTIFIER().getText();
Eif (CodeGenState.currentScope) {
return `${CodeGenState.currentScope}_${typeName}`;
}
return typeName;
}
// Issue #478: Handle global.Type for global types inside scope
if (ctx.globalType()) {
return ctx.globalType()!.IDENTIFIER().getText();
}
// ADR-016: Handle Scope.Type from outside scope (e.g., Motor.State -> Motor_State)
// Issue #388: Also handles C++ namespace types
if (ctx.qualifiedType()) {
const identifiers = ctx.qualifiedType()!.IDENTIFIER();
const identifierNames = identifiers.map((id) => id.getText());
return this.resolveQualifiedType(identifierNames);
}
// Handle C-Next array type syntax (Type[N]) - return base type without dimension
if (ctx.arrayType()) {
const arrayTypeCtx = ctx.arrayType()!;
if (arrayTypeCtx.primitiveType()) {
return arrayTypeCtx.primitiveType()!.getText();
}
if (arrayTypeCtx.userType()) {
return arrayTypeCtx.userType()!.getText();
}
}
if (ctx.userType()) {
return ctx.userType()!.getText();
}
if (ctx.primitiveType()) {
return ctx.primitiveType()!.getText();
}
return ctx.getText();
}
/** Try to evaluate a constant expression at compile time */
tryEvaluateConstant(ctx: Parser.ExpressionContext): number | undefined {
return ArrayDimensionParser.parseSingleDimension(ctx, {
constValues: CodeGenState.constValues,
typeWidths: TYPE_WIDTH,
isKnownStruct: (name) => this.isKnownStruct(name),
});
}
/**
* Get zero initializer for a type.
* ADR-015: Get the appropriate zero initializer for a type
* ADR-017: Handle enum types by initializing to first member
*/
getZeroInitializer(typeCtx: Parser.TypeContext, isArray: boolean): string {
// Issue #379: Arrays need element type checking for C++ classes
if (isArray) {
return this._getArrayZeroInitializer(typeCtx);
}
// Handle named types (scoped, global, qualified, user)
const resolved = this._resolveTypeNameFromContext(typeCtx);
if (resolved) {
// Check if enum
if (CodeGenState.symbols!.knownEnums.has(resolved.name)) {
return this._getEnumZeroValue(resolved.name, resolved.separator);
}
// Check if C++ type needing {} (only for userType, not qualified/scoped/global)
if (resolved.checkCppType && this._needsEmptyBraceInit(resolved.name)) {
return "{}";
}
return "{0}";
}
// Issue #295: C++ template types use value initialization {}
Iif (typeCtx.templateType()) {
return "{}";
}
// Primitive types use lookup map
if (typeCtx.primitiveType()) {
const primType = typeCtx.primitiveType()!.getText();
return CodeGenerator.PRIMITIVE_ZERO_VALUES.get(primType) ?? "0";
}
// Default fallback
return "0";
}
// === Validation (IOrchestrator A4) ===
/** Validate that a literal value fits in the target type */
validateLiteralFitsType(literal: string, typeName: string): void {
this._validateLiteralFitsType(literal, typeName);
}
/** Validate type conversion is allowed */
validateTypeConversion(targetType: string, sourceType: string | null): void {
this._validateTypeConversion(targetType, sourceType);
}
// === String Helpers (IOrchestrator A4) ===
/** Get the length of a string literal */
getStringLiteralLength(literal: string): number {
return StringUtils.literalLength(literal);
}
/** Get string concatenation operands if expression is a concat */
getStringConcatOperands(ctx: Parser.ExpressionContext): {
left: string;
right: string;
leftCapacity: number;
rightCapacity: number;
} | null {
return this._getStringConcatOperands(ctx);
}
/** Get substring operands if expression is a substring call */
getSubstringOperands(ctx: Parser.ExpressionContext): {
source: string;
start: string;
length: string;
sourceCapacity: number;
} | null {
return this._getSubstringOperands(ctx);
}
/** Get the capacity of a string expression */
getStringExprCapacity(exprCode: string): number | null {
return StringOperationsHelper.getStringExprCapacity(exprCode);
}
// === Parameter Management (IOrchestrator A4) ===
/** Set current function parameters */
setParameters(paramList: Parser.ParameterListContext | null): void {
this._setParameters(paramList);
}
/** Clear current function parameters */
clearParameters(): void {
this._clearParameters();
}
/** Check if a callback type is used as a struct field type */
isCallbackTypeUsedAsFieldType(funcName: string): boolean {
for (const callbackType of CodeGenState.callbackFieldTypes.values()) {
if (callbackType === funcName) {
return true;
}
}
return false;
}
// === Scope Management (A4) ===
setCurrentScope(name: string | null): void {
CodeGenState.currentScope = name;
CodeGenState.currentScope = name;
}
/**
* Issue #269: Set the current function name for pass-by-value lookup.
* Part of IOrchestrator interface.
*/
setCurrentFunctionName(name: string | null): void {
CodeGenState.currentFunctionName = name;
CodeGenState.currentFunctionName = name;
}
/**
* Issue #477: Get the current function's return type for enum inference.
* Used by return statement generation to set expectedType.
*/
getCurrentFunctionReturnType(): string | null {
return CodeGenState.currentFunctionReturnType;
}
/**
* Issue #477: Set the current function's return type for enum inference.
*/
setCurrentFunctionReturnType(returnType: string | null): void {
CodeGenState.currentFunctionReturnType = returnType;
CodeGenState.currentFunctionReturnType = returnType;
}
// === Function Body Management (A4) ===
/**
* Enter function body - clears local variables and sets inFunctionBody flag.
* Issue #793: Delegates to FunctionContextManager.
*/
enterFunctionBody(): void {
FunctionContextManager.enterFunctionBody();
}
/**
* Exit function body - clears local variables and inFunctionBody flag.
* Issue #793: Delegates to FunctionContextManager.
*/
exitFunctionBody(): void {
FunctionContextManager.exitFunctionBody();
}
setMainArgsName(name: string | null): void {
CodeGenState.mainArgsName = name;
CodeGenState.mainArgsName = name;
}
isMainFunctionWithArgs(
name: string,
paramList: Parser.ParameterListContext | null,
): boolean {
return CodegenParserUtils.isMainFunctionWithArgs(name, paramList);
}
/**
* ADR-029: Generate typedef for callback type
*/
generateCallbackTypedef(funcName: string): string | null {
const callbackInfo = CodeGenState.callbackTypes.get(funcName);
Iif (!callbackInfo) {
return null;
}
const paramList =
callbackInfo.parameters.length > 0
? callbackInfo.parameters
.map((p) => {
const constMod = p.isConst ? "const " : "";
Iif (p.isArray) {
// Array parameters: type name[]
return `${constMod}${p.type} ${p.name}${p.arrayDims}`;
} else if (p.isPointer) {
// ADR-006: Non-array, non-callback parameters become pointers
// In C++ mode, use reference (&) instead of pointer (*)
const ptrOrRef = this.isCppMode() ? "&" : "*";
return `${constMod}${p.type}${ptrOrRef}`;
} else E{
// ADR-029: Callback parameters are already function pointers
return `${p.type}`;
}
})
.join(", ")
: "void";
return `\ntypedef ${callbackInfo.returnType} (*${callbackInfo.typedefName})(${paramList});\n`;
}
/**
* Issue #268: Get unmodified parameters info for all functions.
* Returns map of function name -> Set of unmodified parameter names.
* Computed on-demand from functionSignatures and modifiedParameters.
*/
getFunctionUnmodifiedParams(): ReadonlyMap<string, Set<string>> {
return CodeGenState.getUnmodifiedParameters();
}
/**
* Issue #268: Update symbol parameters with auto-const info.
* Now a no-op - unmodified params are computed on-demand from CodeGenState.
* Kept for IOrchestrator interface compatibility.
*/
updateFunctionParamsAutoConst(_functionName: string): void {
// No-op: Unmodified parameters are now computed on-demand from
// CodeGenState.functionSignatures and CodeGenState.modifiedParameters
// via CodeGenState.getUnmodifiedParameters().
}
/**
* Issue #268: Mark a parameter as modified for auto-const tracking.
* Issue #558: Now a no-op - analysis phase handles all modification tracking
* including transitive propagation across function calls and files.
*/
markParameterModified(_paramName: string): void {
// No-op: Analysis phase (analyzePassByValue) now handles all modification
// tracking including cross-file and transitive propagation.
}
/**
* Issue #558: Check if a parameter is modified using analysis-phase results.
* This is the unified source of truth for modification tracking.
*/
private _isCurrentParameterModified(paramName: string): boolean {
const funcName = CodeGenState.currentFunctionName;
Iif (!funcName) return false;
return (
CodeGenState.modifiedParameters.get(funcName)?.has(paramName) ?? false
);
}
/**
* Issue #558: Get the modified parameters map for cross-file propagation.
* Returns function name -> set of modified parameter names.
*/
getModifiedParameters(): ReadonlyMap<string, Set<string>> {
return CodeGenState.modifiedParameters;
}
/**
* Issue #558: Set cross-file modification data to inject during analyzePassByValue.
* Called by Pipeline before generate() to share modifications from previously processed files.
*/
setCrossFileModifications(
modifications: ReadonlyMap<string, ReadonlySet<string>>,
paramLists: ReadonlyMap<string, readonly string[]>,
): void {
CodeGenState.pendingCrossFileModifications = modifications;
CodeGenState.pendingCrossFileParamLists = paramLists;
}
/**
* Issue #558: Get the function parameter lists for cross-file propagation.
*/
getFunctionParamLists(): ReadonlyMap<string, string[]> {
return CodeGenState.functionParamLists;
}
/**
* Issue #561: Analyze modifications in a parse tree without full code generation.
* Used by the transpile() pipeline to collect modification info from includes
* for cross-file const inference.
*
* Issue #565: Now accepts optional cross-file data for transitive propagation.
* When a file calls a function from an included file that modifies its param,
* we need that info available during analysis to propagate correctly.
*
* Returns the modifications and param lists discovered in this tree.
*/
analyzeModificationsOnly(
tree: Parser.ProgramContext,
crossFileModifications?: ReadonlyMap<string, ReadonlySet<string>>,
crossFileParamLists?: ReadonlyMap<string, readonly string[]>,
): {
modifications: Map<string, Set<string>>;
paramLists: Map<string, string[]>;
} {
// Save current state
const savedModifications = new Map(CodeGenState.modifiedParameters);
const savedParamLists = new Map(CodeGenState.functionParamLists);
const savedCallGraph = new Map(CodeGenState.functionCallGraph);
// Clear for fresh analysis
CodeGenState.modifiedParameters.clear();
CodeGenState.functionParamLists.clear();
CodeGenState.functionCallGraph.clear();
// Issue #565: Inject cross-file data BEFORE collecting this file's info
this.injectCrossFileData(crossFileModifications, crossFileParamLists);
// Track which functions were injected (not from this file)
const injectedFuncs = new Set(crossFileModifications?.keys() ?? []);
// Run modification analysis on the tree (adds to what was injected)
PassByValueAnalyzer.collectFunctionParametersAndModifications(tree);
// Issue #565: Run transitive propagation with full context
TransitiveModificationPropagator.propagate(
CodeGenState.functionCallGraph,
CodeGenState.functionParamLists,
CodeGenState.modifiedParameters,
);
// Capture results - only include functions NOT from cross-file injection
const modifications = this.extractThisFileModifications(
crossFileModifications,
injectedFuncs,
);
const paramLists = this.extractThisFileParamLists(crossFileParamLists);
// Restore previous state
this.restoreMapState(CodeGenState.modifiedParameters, savedModifications);
this.restoreMapState(CodeGenState.functionParamLists, savedParamLists);
this.restoreMapState(CodeGenState.functionCallGraph, savedCallGraph);
return { modifications, paramLists };
}
/**
* Inject cross-file modification data for transitive propagation.
*/
private injectCrossFileData(
crossFileModifications?: ReadonlyMap<string, ReadonlySet<string>>,
crossFileParamLists?: ReadonlyMap<string, readonly string[]>,
): void {
if (crossFileModifications) {
for (const [funcName, params] of crossFileModifications) {
CodeGenState.modifiedParameters.set(funcName, new Set(params));
}
}
if (crossFileParamLists) {
for (const [funcName, params] of crossFileParamLists) {
CodeGenState.functionParamLists.set(funcName, [...params]);
}
}
}
/**
* Extract modifications discovered in this file (excluding injected cross-file data).
*/
private extractThisFileModifications(
crossFileModifications:
| ReadonlyMap<string, ReadonlySet<string>>
| undefined,
injectedFuncs: Set<string>,
): Map<string, Set<string>> {
const modifications = new Map<string, Set<string>>();
for (const [funcName, params] of CodeGenState.modifiedParameters) {
if (!injectedFuncs.has(funcName)) {
// Function defined in this file - include all its modifications
modifications.set(funcName, new Set(params));
continue;
}
// Check if we discovered new modifications for an injected function
const injectedParams = crossFileModifications?.get(funcName);
Iif (!injectedParams) continue;
const newParams = this.findNewParams(params, injectedParams);
Iif (newParams.size > 0) {
modifications.set(funcName, newParams);
}
}
return modifications;
}
/**
* Find params that are in current set but not in injected set.
*/
private findNewParams(
params: Set<string>,
injectedParams: ReadonlySet<string>,
): Set<string> {
return SetMapHelper.findNewItems(params, injectedParams);
}
/**
* Extract param lists discovered in this file (excluding injected cross-file data).
*/
private extractThisFileParamLists(
crossFileParamLists?: ReadonlyMap<string, readonly string[]>,
): Map<string, string[]> {
return SetMapHelper.copyArrayValues(
SetMapHelper.filterExclude(
CodeGenState.functionParamLists,
crossFileParamLists,
),
);
}
/**
* Restore a map's state by clearing and repopulating from saved data.
*/
private restoreMapState<K, V>(target: Map<K, V>, saved: Map<K, V>): void {
SetMapHelper.restoreMapState(target, saved);
}
/**
* Issue #268: Check if a callee function's parameter at given index is modified.
* Returns true if the callee modifies that parameter (should not have const).
*/
isCalleeParameterModified(funcName: string, paramIndex: number): boolean {
// Get the parameter name at the given index from the function signature
const sig = CodeGenState.functionSignatures.get(funcName);
Iif (!sig || paramIndex >= sig.parameters.length) {
// Callee not yet processed - conservatively return false (assume unmodified)
return false;
}
const paramName = sig.parameters[paramIndex].name;
// Check directly if the parameter is in the modified set
return CodeGenState.isParameterModified(funcName, paramName);
}
/**
* Issue #268: Check if a name is a parameter of the current function.
*/
isCurrentParameter(name: string): boolean {
return CodeGenState.currentParameters.has(name);
}
// === Postfix Expression Helpers (Issue #644) ===
/**
* Generate a primary expression.
* Part of IOrchestrator interface for PostfixExpressionGenerator.
*/
generatePrimaryExpr(ctx: Parser.PrimaryExpressionContext): string {
// ADR-023: sizeof expression - sizeof(u32) or sizeof(variable)
if (ctx.sizeofExpression()) {
return this.generateSizeofExpr(ctx.sizeofExpression()!);
}
// ADR-017: Cast expression - (u8)State.IDLE
if (ctx.castExpression()) {
return this.generateCastExpression(ctx.castExpression()!);
}
// ADR-014: Struct initializer - Point { x: 10, y: 20 }
if (ctx.structInitializer()) {
return this.generateStructInitializer(ctx.structInitializer()!);
}
// ADR-035: Array initializer - [1, 2, 3] or [0*]
if (ctx.arrayInitializer()) {
return this.generateArrayInitializer(ctx.arrayInitializer()!);
}
// ADR-016: Handle 'this' keyword for scope-local reference
const text = ctx.getText();
if (text === "this") {
return this._resolveThisKeyword();
}
// ADR-016: Handle 'global' keyword for global reference
if (text === "global") {
return "__GLOBAL_PREFIX__";
}
if (ctx.IDENTIFIER()) {
return this._resolveIdentifierExpression(ctx.IDENTIFIER()!.getText());
}
if (ctx.literal()) {
return this._generateLiteralExpression(ctx.literal()!);
}
Eif (ctx.expression()) {
return `(${this.generateExpression(ctx.expression()!)})`;
}
return "";
}
/**
* Check if a name is a known scope.
* Part of IOrchestrator interface.
*/
isKnownScope(name: string): boolean {
return SymbolLookupHelper.isKnownScope(
CodeGenState.symbols?.knownScopes,
CodeGenState.symbolTable,
name,
);
}
/**
* Check if a symbol is a C++ scope symbol (namespace, class, enum).
* Part of IOrchestrator interface.
*/
isCppScopeSymbol(name: string): boolean {
return CppNamespaceUtils.isCppNamespace(
name,
CodeGenState.symbolTable ?? undefined,
);
}
/**
* Get the separator for scope access (:: for C++, _ for C-Next).
* Part of IOrchestrator interface - delegates to FormatUtils.
*/
getScopeSeparator(isCppAccess: boolean): string {
return FormatUtils.getScopeSeparator(isCppAccess);
}
/**
* Get struct field info for .length calculations.
* Part of IOrchestrator interface.
*
* Issue #831: SymbolTable is the single source of truth for struct fields
* (both C-Next and C header structs).
*/
getStructFieldInfo(
structType: string,
fieldName: string,
): { type: string; dimensions?: (number | string)[] } | null {
const fieldInfo = CodeGenState.symbolTable?.getStructFieldInfo(
structType,
fieldName,
);
if (fieldInfo) {
return {
type: fieldInfo.type,
dimensions: fieldInfo.arrayDimensions,
};
}
return null;
}
/**
* Get member type info for struct access chains.
* Part of IOrchestrator interface.
*/
getMemberTypeInfo(structType: string, memberName: string): TTypeInfo | null {
const fieldInfo = this.getStructFieldInfo(structType, memberName);
if (!fieldInfo) return null;
const isArray =
(fieldInfo.dimensions !== undefined && fieldInfo.dimensions.length > 0) ||
(CodeGenState.symbols!.structFieldArrays.get(structType)?.has(
memberName,
) ??
false);
const dims = fieldInfo.dimensions?.filter(
(d): d is number => typeof d === "number",
);
return {
baseType: fieldInfo.type,
bitWidth: TYPE_WIDTH[fieldInfo.type] ?? 32,
isConst: false,
isArray,
arrayDimensions: dims && dims.length > 0 ? dims : undefined,
};
}
/**
* Generate a bit mask for bit range access.
* Part of IOrchestrator interface.
* Issue #644: Delegate to BitUtils for code reuse.
*/
generateBitMask(width: string, is64Bit: boolean = false): string {
// BitUtils.generateMask expects a type string, not a boolean
return BitUtils.generateMask(width, is64Bit ? "u64" : undefined);
}
/**
* Add a pending temp variable declaration (for float bit indexing).
* Part of IOrchestrator interface.
*/
addPendingTempDeclaration(declaration: string): void {
CodeGenState.pendingTempDeclarations.push(declaration);
}
/**
* Register a float bit shadow variable.
* Part of IOrchestrator interface.
*/
registerFloatBitShadow(shadowName: string): void {
CodeGenState.floatBitShadows.add(shadowName);
}
/**
* Mark a float shadow as having current value (skip redundant memcpy).
* Part of IOrchestrator interface.
*/
markFloatShadowCurrent(shadowName: string): void {
CodeGenState.floatShadowCurrent.add(shadowName);
}
/**
* Check if a float shadow has been declared.
* Part of IOrchestrator interface.
*/
hasFloatBitShadow(shadowName: string): boolean {
return CodeGenState.floatBitShadows.has(shadowName);
}
/**
* Check if a float shadow has current value.
* Part of IOrchestrator interface.
*/
isFloatShadowCurrent(shadowName: string): boolean {
return CodeGenState.floatShadowCurrent.has(shadowName);
}
/**
* Issue #948: Check if a type is an opaque (forward-declared) struct type.
* Opaque types can only be used as pointers (cannot be instantiated).
* Part of IOrchestrator interface.
*/
isOpaqueType(typeName: string): boolean {
return CodeGenState.isOpaqueType(typeName);
}
/**
* Issue #958: Check if a type is an external typedef struct type.
* Used for scope variables which should always be pointers for external struct types.
* Part of IOrchestrator interface.
*/
isTypedefStructType(typeName: string): boolean {
return CodeGenState.isTypedefStructType(typeName);
}
/**
* Issue #948: Mark a scope variable as having an opaque type.
* These variables are generated as pointers with NULL initialization.
* Part of IOrchestrator interface.
*/
markOpaqueScopeVariable(qualifiedName: string): void {
CodeGenState.markOpaqueScopeVariable(qualifiedName);
}
// ===========================================================================
// End IOrchestrator Implementation
// ===========================================================================
/**
* Issue #551: Check if a type is a known primitive type.
* Known primitives use pass-by-reference with dereference.
* Unknown types (external enums, typedefs) use pass-by-value.
*/
private _isKnownPrimitive(typeName: string): boolean {
return !!TYPE_MAP[typeName];
}
/**
* PR #681: Build dependencies for parameter dereference resolution.
* Used by ParameterDereferenceResolver to determine if parameters need dereferencing.
*/
private _buildParameterDereferenceDeps(): IParameterDereferenceDeps {
return {
isFloatType: (typeName: string) => this._isFloatType(typeName),
isKnownPrimitive: (typeName: string) => this._isKnownPrimitive(typeName),
knownEnums: CodeGenState.symbols!.knownEnums,
isParameterPassByValue: (funcName: string, paramName: string) =>
PassByValueAnalyzer.isParameterPassByValueByName(funcName, paramName),
currentFunctionName: CodeGenState.currentFunctionName,
maybeDereference: (id: string) => CppModeHelper.maybeDereference(id),
};
}
/**
* PR #681: Build dependencies for member separator resolution.
* Used by MemberSeparatorResolver to determine appropriate separators.
*/
private _buildMemberSeparatorDeps(): IMemberSeparatorDeps {
return {
isKnownScope: (name: string) => this.isKnownScope(name),
isKnownRegister: (name: string) =>
CodeGenState.symbols!.knownRegisters.has(name),
validateCrossScopeVisibility: (scopeName: string, memberName: string) =>
this.validateCrossScopeVisibility(scopeName, memberName),
validateRegisterAccess: (
registerName: string,
memberName: string,
hasGlobal: boolean,
) => this._validateRegisterAccess(registerName, memberName, hasGlobal),
getStructParamSeparator: () =>
memberAccessChain.getStructParamSeparator({
cppMode: CodeGenState.cppMode,
}),
};
}
/**
* Validate register access from inside a scope requires global. prefix.
*
* Issue #779: Use ambiguity-aware validation - only require global. when
* the register name is ACTUALLY shadowed by a local or scope member.
*
* Exceptions (no global. required):
* 1. Scoped registers defined within the current scope
* 2. Unambiguous access - no local/scope member with the same name
*/
private _validateRegisterAccess(
registerName: string,
memberName: string,
hasGlobal: boolean,
): void {
// Only validate when inside a scope and accessing without global. prefix
if (CodeGenState.currentScope && !hasGlobal) {
// Check if this is a scoped register (defined within the current scope)
// The registerName may already be the fully qualified name (e.g., "GPIO_PORTA")
// if accessed as PORTA from inside scope GPIO
const scopePrefix = `${CodeGenState.currentScope}_`;
if (registerName.startsWith(scopePrefix)) {
// This is a scoped register - allow bare access
return;
}
// Issue #779: Ambiguity-aware validation
// Only require global. if the register name is shadowed by:
// 1. A local variable in the current function
// 2. A member of the current scope
const isShadowedByLocal = CodeGenState.localVariables.has(registerName);
const isShadowedByScope = CodeGenState.isCurrentScopeMember(registerName);
if (!isShadowedByLocal && !isShadowedByScope) {
// Unambiguous - allow bare access
return;
}
throw new Error(
`Error: Use 'global.${registerName}.${memberName}' to access register '${registerName}' ` +
`from inside scope '${CodeGenState.currentScope}'`,
);
}
}
/**
* Issue #517: Check if a type is a C++ class with a user-defined constructor.
* C++ classes with user-defined constructors are NOT aggregate types,
* so designated initializers { .field = value } don't work with them.
* We check for the existence of a constructor symbol (TypeName::ClassName).
*/
private _isCppClassWithConstructor(typeName: string): boolean {
return CppConstructorHelper.hasConstructor(
typeName,
CodeGenState.symbolTable,
);
}
private foldBooleanToInt(expr: string): string {
return BooleanHelper.foldBooleanToInt(expr);
}
/**
* Issue #388: Resolve a qualified type from dot notation to the correct output format.
* For C++ namespace types (like MockLib.Parse.ParseResult), uses :: separator.
* For C-Next scope types (like Motor.State), uses _ separator.
*
* @param identifiers Array of identifier names forming the qualified type
* @returns The resolved type name with appropriate separator
*/
private resolveQualifiedType(identifiers: string[]): string {
Iif (identifiers.length === 0) {
return "";
}
const firstName = identifiers[0];
// Check if the first identifier is a C++ scope symbol (namespace, class, enum)
Iif (this.isCppScopeSymbol(firstName)) {
// C++ namespace type: join all parts with ::
return identifiers.join("::");
}
// C-Next scope type: join all parts with _
return identifiers.join("_");
}
/**
* Issue #304: Check if a type name is from a C++ header
* Used to determine whether to use {} or {0} for initialization.
* C++ types with constructors may fail with {0} but work with {}.
*/
private isCppType(typeName: string): boolean {
return SymbolLookupHelper.isCppType(CodeGenState.symbolTable, typeName);
}
/**
* Generate C code from a C-Next program
* @param tree The parsed C-Next program
* @param tokenStream Optional token stream for comment preservation (ADR-043)
* @param options Optional code generator options (e.g., debugMode)
*/
generate(
tree: Parser.ProgramContext,
tokenStream?: CommonTokenStream,
options?: ICodeGeneratorOptions,
): string {
// ADR-049: Determine target capabilities with priority: CLI > pragma > default
const targetCapabilities = this.resolveTargetCapabilities(
tree,
options?.target,
);
// ADR-053: Initialize generators (once per CodeGenerator instance)
if (!this.generatorsInitialized) {
this.initializeGenerators();
this.generatorsInitialized = true;
}
// Reset state for fresh generation (must be before any state assignments)
this.resetGeneratorState(targetCapabilities);
// Initialize options and configuration (after reset)
this.initializeGenerateOptions(options, tokenStream);
// ADR-055: Use pre-collected symbolInfo from Pipeline (TSymbolInfoAdapter)
if (!options?.symbolInfo) {
throw new Error(
"symbolInfo is required - use CNextResolver + TSymbolInfoAdapter",
);
}
CodeGenState.symbols = options.symbolInfo;
// Initialize symbol data and const values
this.initializeSymbolData();
// Initialize all helper objects
this.initializeHelperObjects(tree);
// Second pass: register all variable types in the type registry
this.registerAllVariableTypes(tree);
// Assemble and return the output
return this.assembleGeneratedOutput(tree, options);
}
/**
* Initialize options and configuration for generate().
*/
private initializeGenerateOptions(
options: ICodeGeneratorOptions | undefined,
tokenStream: CommonTokenStream | undefined,
): void {
CodeGenState.debugMode = options?.debugMode ?? false;
CodeGenState.sourcePath = options?.sourcePath ?? null;
CodeGenState.includeDirs = options?.includeDirs ?? [];
CodeGenState.inputs = options?.inputs ?? [];
CodeGenState.cppMode = options?.cppMode ?? false;
CodeGenState.pendingTempDeclarations = [];
CodeGenState.tempVarCounter = 0;
CodeGenState.pendingCppClassAssignments = [];
this.tokenStream = tokenStream ?? null;
this.commentExtractor = this.tokenStream
? new CommentExtractor(this.tokenStream)
: null;
}
/**
* Reset all generator state for a fresh generation pass.
*/
private resetGeneratorState(targetCapabilities: TargetCapabilities): void {
// Reset global state (CodeGenState.reset() handles all field initialization)
CodeGenState.reset(targetCapabilities);
// Set generator reference for handlers to use
CodeGenState.generator = this;
}
/**
* Initialize symbol data and const values from symbol table.
*/
private initializeSymbolData(): void {
const symbols = CodeGenState.symbols!;
// Copy symbol data to CodeGenState.scopeMembers
for (const [scopeName, members] of symbols.scopeMembers) {
CodeGenState.setScopeMembers(scopeName, new Set(members));
}
// Issue #461: Initialize constValues from symbol table
// Only C-Next TSymbols have initialValue property
CodeGenState.constValues = new Map();
Eif (CodeGenState.symbolTable) {
for (const symbol of CodeGenState.symbolTable.getAllTSymbols()) {
if (
symbol.kind === "variable" &&
symbol.isConst &&
symbol.initialValue !== undefined
) {
const value = LiteralUtils.parseIntegerLiteral(symbol.initialValue);
if (value !== undefined) {
CodeGenState.constValues.set(symbol.name, value);
}
}
}
}
}
/**
* Initialize all helper objects needed for code generation.
*/
private initializeHelperObjects(tree: Parser.ProgramContext): void {
// Collect function/callback information
this.collectFunctionsAndCallbacks(tree);
PassByValueAnalyzer.analyze(tree);
}
/**
* Assemble the final generated output.
*/
private assembleGeneratedOutput(
tree: Parser.ProgramContext,
options: ICodeGeneratorOptions | undefined,
): string {
const output: string[] = [];
const symbols = CodeGenState.symbols!;
// Add header comment
const sourcePath = CodeGenState.sourcePath;
const generatedLine = sourcePath
? ` * Generated by C-Next Transpiler from: ${basename(sourcePath)}`
: " * Generated by C-Next Transpiler";
output.push(
"/**",
generatedLine,
" * A safer C for embedded systems",
" */",
"",
);
// Self-include for extern "C" linkage
if (symbols.hasPublicSymbols() && CodeGenState.sourcePath) {
const pathToUse =
options?.sourceRelativePath ||
CodeGenState.sourcePath.replace(/^.*[\\/]/, "");
// Issue #933: Use .hpp extension in C++ mode to match header file
const ext = CodeGenState.cppMode ? ".hpp" : ".h";
const headerName = pathToUse.replace(/\.cnx$|\.cnext$/, ext);
output.push(`#include "${headerName}"`, "");
CodeGenState.selfIncludeAdded = true;
}
// Process include directives
this.processIncludeDirectives(tree, output);
// Process preprocessor directives
this.processPreprocessorDirectives(tree, output);
// Generate declarations
const declarations = this.generateAllDeclarations(tree);
// Add auto-includes and helpers
this.addAutoIncludes(output);
this.addGeneratedHelpers(output);
// Add the declarations
output.push(...declarations);
return output.join("\n");
}
/**
* Process all include directives and add to output.
*/
private processIncludeDirectives(
tree: Parser.ProgramContext,
output: string[],
): void {
const includePaths = CodeGenState.sourcePath
? IncludeDiscovery.discoverIncludePaths(CodeGenState.sourcePath)
: [];
for (const includeDir of tree.includeDirective()) {
const leadingComments = this.getLeadingComments(includeDir);
output.push(...this.formatLeadingComments(leadingComments));
const lineNumber = includeDir.start?.line ?? 0;
TypeValidator.validateIncludeNotImplementationFile(
includeDir.getText(),
lineNumber,
);
TypeValidator.validateIncludeNoCnxAlternative(
includeDir.getText(),
lineNumber,
CodeGenState.sourcePath,
includePaths,
);
output.push(this.transformIncludeDirective(includeDir.getText()));
}
if (tree.includeDirective().length > 0) {
output.push("");
}
}
/**
* Process all preprocessor directives and add to output.
*/
private processPreprocessorDirectives(
tree: Parser.ProgramContext,
output: string[],
): void {
for (const ppDir of tree.preprocessorDirective()) {
const leadingComments = this.getLeadingComments(ppDir);
output.push(...this.formatLeadingComments(leadingComments));
const result = this.processPreprocessorDirective(ppDir);
if (result) {
output.push(result);
}
}
if (tree.preprocessorDirective().length > 0) {
output.push("");
}
}
/**
* Generate all declarations from the tree.
*/
private generateAllDeclarations(tree: Parser.ProgramContext): string[] {
const declarations: string[] = [];
for (const decl of tree.declaration()) {
const leadingComments = this.getLeadingComments(decl);
declarations.push(...this.formatLeadingComments(leadingComments));
const code = this.generateDeclaration(decl);
if (code) {
declarations.push(code);
}
}
return declarations;
}
/**
* Add auto-generated includes based on usage.
*/
private addAutoIncludes(output: string[]): void {
const autoIncludes: string[] = [];
if (CodeGenState.needsStdint) autoIncludes.push("#include <stdint.h>");
if (CodeGenState.needsStdbool) autoIncludes.push("#include <stdbool.h>");
if (CodeGenState.needsString) autoIncludes.push("#include <string.h>");
if (CodeGenState.needsCMSIS) autoIncludes.push("#include <cmsis_gcc.h>");
if (CodeGenState.needsLimits) autoIncludes.push("#include <limits.h>");
if (autoIncludes.length > 0) {
output.push(...autoIncludes, "");
}
}
/**
* Add generated helpers (static asserts, IRQ wrappers, typedefs, etc.).
*/
private addGeneratedHelpers(output: string[]): void {
if (CodeGenState.needsFloatStaticAssert) {
// Use static_assert for C++ (standard), _Static_assert for C11
const assertKeyword = this.isCppMode()
? "static_assert"
: "_Static_assert";
output.push(
`${assertKeyword}(sizeof(float) == 4, "Float bit indexing requires 32-bit float");`,
`${assertKeyword}(sizeof(double) == 8, "Float bit indexing requires 64-bit double");`,
"",
);
}
if (CodeGenState.needsIrqWrappers) {
output.push(...this.generateIrqWrappers());
}
if (CodeGenState.needsISR) {
output.push(
"/* ADR-040: ISR function pointer type */",
"typedef void (*ISR)(void);",
"",
);
}
const helpers = this.generateOverflowHelpers();
if (helpers.length > 0) {
output.push(...helpers);
}
const safeDivHelpers = this.generateSafeDivHelpers();
Iif (safeDivHelpers.length > 0) {
output.push(...safeDivHelpers);
}
}
/**
* ADR-049: Resolve target capabilities with priority: CLI > pragma > default
* @param tree - The parsed program tree
* @param cliTarget - Optional target from CLI --target flag
*/
private resolveTargetCapabilities(
tree: Parser.ProgramContext,
cliTarget?: string,
): TargetCapabilities {
// Priority 1: CLI --target flag
if (cliTarget) {
const targetName = cliTarget.toLowerCase();
if (TARGET_CAPABILITIES[targetName]) {
return TARGET_CAPABILITIES[targetName];
}
// Warn about unknown CLI target but continue with pragma/default
console.warn(
`Warning: Unknown target '${cliTarget}', falling back to pragma or default`,
);
}
// Priority 2: #pragma target in source
const pragmaTarget = this.parseTargetPragma(tree);
if (pragmaTarget !== DEFAULT_TARGET) {
return pragmaTarget;
}
// Priority 3: Default (safe fallback - no LDREX/STREX)
return DEFAULT_TARGET;
}
/**
* ADR-049: Parse #pragma target directive from source
* Returns capabilities for the specified platform, or DEFAULT_TARGET if none found
*/
private parseTargetPragma(tree: Parser.ProgramContext): TargetCapabilities {
// pragmaDirective is accessed through preprocessorDirective
const preprocessorDirs = tree.preprocessorDirective();
for (const ppDir of preprocessorDirs) {
const pragmaDir = ppDir.pragmaDirective();
if (pragmaDir) {
// PRAGMA_TARGET captures the whole "#pragma target <name>" as one token
const text = pragmaDir.getText();
// Extract target name: "#pragma target teensy41" -> "teensy41"
const match = /#\s*pragma\s+target\s+(\S+)/i.exec(text);
Eif (match) {
const targetName = match[1].toLowerCase();
Eif (TARGET_CAPABILITIES[targetName]) {
return TARGET_CAPABILITIES[targetName];
}
}
}
}
return DEFAULT_TARGET;
}
/**
* ADR-010: Transform #include directives, converting .cnx to .h or .hpp
* ADR-053 A5: Delegates to IncludeGenerator
* Issue #349: Now passes includeDirs and inputs for angle-bracket resolution
* Issue #941: Now passes cppMode for .hpp extension in C++ mode
*/
private transformIncludeDirective(includeText: string): string {
return includeTransformIncludeDirective(includeText, {
sourcePath: CodeGenState.sourcePath,
includeDirs: CodeGenState.includeDirs,
inputs: CodeGenState.inputs,
cppMode: CodeGenState.cppMode,
});
}
// Issue #63: validateIncludeNotImplementationFile moved to TypeValidator
/**
* Collect function and callback information.
* Issue #60: Symbol collection extracted to SymbolCollector.
* This method handles function signatures and callback types (not yet extracted).
*/
private collectFunctionsAndCallbacks(tree: Parser.ProgramContext): void {
for (const decl of tree.declaration()) {
// ADR-016: Handle scope declarations for function tracking
if (decl.scopeDeclaration()) {
this._collectScopeFunctions(decl.scopeDeclaration()!);
continue;
}
// ADR-029: Track callback field types in structs
if (decl.structDeclaration()) {
this._collectStructCallbackFields(decl.structDeclaration()!);
continue;
}
// Track top-level functions
if (decl.functionDeclaration()) {
this._collectTopLevelFunction(decl.functionDeclaration()!);
}
}
}
/**
* Collect scoped functions and their callback types
*/
private _collectScopeFunctions(
scopeDecl: Parser.ScopeDeclarationContext,
): void {
const scopeName = scopeDecl.IDENTIFIER().getText();
// Set scope context for scoped type resolution (this.Type)
const savedScope = CodeGenState.currentScope;
CodeGenState.currentScope = scopeName;
for (const member of scopeDecl.scopeMember()) {
if (member.functionDeclaration()) {
const funcDecl = member.functionDeclaration()!;
const funcName = funcDecl.IDENTIFIER().getText();
// Track fully qualified function name: Scope_function
const fullName = QualifiedNameGenerator.forFunctionStrings(
scopeName,
funcName,
);
CodeGenState.knownFunctions.add(fullName);
// ADR-013: Track function signature for const checking
const sig = this.extractFunctionSignature(
fullName,
funcDecl.parameterList() ?? null,
);
CodeGenState.functionSignatures.set(fullName, sig);
// ADR-029: Register scoped function as callback type
this.registerCallbackType(fullName, funcDecl);
}
}
// Restore previous scope context
CodeGenState.currentScope = savedScope;
}
/**
* Collect callback field types from struct declaration
*/
private _collectStructCallbackFields(
structDecl: Parser.StructDeclarationContext,
): void {
const structName = structDecl.IDENTIFIER().getText();
for (const member of structDecl.structMember()) {
const fieldName = member.IDENTIFIER().getText();
const fieldType = this.getTypeName(member.type());
// Track callback field types (needed for typedef generation)
if (CodeGenState.callbackTypes.has(fieldType)) {
CodeGenState.callbackFieldTypes.set(
`${structName}.${fieldName}`,
fieldType,
);
}
}
}
/**
* Collect top-level function and register as callback type
*/
private _collectTopLevelFunction(
funcDecl: Parser.FunctionDeclarationContext,
): void {
const name = funcDecl.IDENTIFIER().getText();
CodeGenState.knownFunctions.add(name);
// ADR-013: Track function signature for const checking
const sig = this.extractFunctionSignature(
name,
funcDecl.parameterList() ?? null,
);
CodeGenState.functionSignatures.set(name, sig);
// ADR-029: Register function as callback type
this.registerCallbackType(name, funcDecl);
}
/**
* Second pass: register all variable types in the type registry
* This ensures type information is available before generating any code,
* allowing .length and other type-dependent operations to work regardless
* of declaration order (e.g., scope functions can reference globals declared later)
* SonarCloud S3776: Refactored to use helper methods.
*/
private registerAllVariableTypes(tree: Parser.ProgramContext): void {
TypeRegistrationEngine.register(tree, {
tryEvaluateConstant: (ctx) => this.tryEvaluateConstant(ctx),
requireInclude: (header) => this.requireInclude(header),
resolveQualifiedType: (ids) => this.resolveQualifiedType(ids),
});
}
// Issue #60: collectEnum and collectBitmap methods removed - now in SymbolCollector
// Issue #63: validateBitmapFieldLiteral moved to TypeValidator
// Issue #60: evaluateConstantExpression method removed - now in SymbolCollector
// Issue #269: Pass-by-value analysis extracted to PassByValueAnalyzer
/**
* Issue #269: Check if a parameter should be passed by value (by index).
* Part of IOrchestrator interface - used by CallExprGenerator.
* Delegates to PassByValueAnalyzer.
*/
isParameterPassByValue(funcName: string, paramIndex: number): boolean {
return PassByValueAnalyzer.isParameterPassByValue(funcName, paramIndex);
}
/**
* Issue #269: Get all pass-by-value parameters.
* Returns a Map from function name to Set of parameter names that should be pass-by-value.
* Used by HeaderGenerator to ensure header and implementation signatures match.
*/
getPassByValueParams(): ReadonlyMap<string, ReadonlySet<string>> {
return CodeGenState.passByValueParams;
}
/**
* Issue #322: Check if a type name is a user-defined struct
* Part of IOrchestrator interface.
*/
isStructType(typeName: string): boolean {
return TypeResolver.isStructType(typeName);
}
/**
* Set up parameter tracking for a function.
* Issue #793: Delegates to FunctionContextManager.
*/
private _setParameters(params: Parser.ParameterListContext | null): void {
FunctionContextManager.processParameterList(
params,
this._getFunctionContextCallbacks(),
);
}
/**
* Clear parameter tracking when leaving a function.
* Issue #793: Delegates to FunctionContextManager.
*/
private _clearParameters(): void {
FunctionContextManager.clearParameters();
}
/**
* ADR-013: Extract function signature from parameter list
*/
private extractFunctionSignature(
name: string,
params: Parser.ParameterListContext | null,
): FunctionSignature {
const parameters: Array<{
name: string;
baseType: string;
isConst: boolean;
isArray: boolean;
}> = [];
if (params) {
for (const param of params.parameter()) {
const paramName = param.IDENTIFIER().getText();
const isConst = param.constModifier() !== null;
// arrayDimension() returns an array (due to grammar's *), so check length
// Also check C-Next style array type (e.g., u8[8] param)
const isArray =
param.arrayDimension().length > 0 ||
param.type().arrayType() !== null;
const baseType = this.getTypeName(param.type());
parameters.push({ name: paramName, baseType, isConst, isArray });
}
}
return { name, parameters };
}
/**
* ADR-029: Register a function as a callback type
* The function name becomes both a callable function and a type for callback fields
*/
private registerCallbackType(
name: string,
funcDecl: Parser.FunctionDeclarationContext,
): void {
const returnType = this.generateType(funcDecl.type());
const parameters: Array<{
name: string;
type: string;
isConst: boolean;
isPointer: boolean;
isArray: boolean;
arrayDims: string;
}> = [];
if (funcDecl.parameterList()) {
for (const param of funcDecl.parameterList()!.parameter()) {
const paramName = param.IDENTIFIER().getText();
const typeName = this.getTypeName(param.type());
const isConst = param.constModifier() !== null;
const dims = param.arrayDimension();
const arrayTypeCtx = param.type().arrayType();
const isArray = dims.length > 0 || arrayTypeCtx !== null;
// ADR-029: Check if parameter type is itself a callback type
const isCallbackParam = CodeGenState.callbackTypes.has(typeName);
let paramType: string;
let isPointer: boolean;
if (isCallbackParam) {
// Use the callback typedef name
const cbInfo = CodeGenState.callbackTypes.get(typeName)!;
paramType = cbInfo.typedefName;
isPointer = false; // Function pointers are already pointers
} else {
paramType = this.generateType(param.type());
// ADR-006: Non-array parameters become pointers
isPointer = !isArray;
}
let arrayDims: string;
if (dims.length > 0) {
arrayDims = dims.map((d) => this.generateArrayDimension(d)).join("");
} else if (arrayTypeCtx) {
// Generate all dimensions from arrayType (supports multi-dimensional)
arrayDims = arrayTypeCtx
.arrayTypeDimension()
.map((d) => {
const expr = d.expression();
return expr ? `[${this.generateExpression(expr)}]` : "[]";
})
.join("");
} else {
arrayDims = "";
}
parameters.push({
name: paramName,
type: paramType,
isConst,
isPointer,
isArray,
arrayDims,
});
}
}
CodeGenState.callbackTypes.set(name, {
functionName: name,
returnType,
parameters,
typedefName: `${name}_fp`,
});
}
/**
* ADR-029: Check if a function is used as a callback type (field type in a struct)
*/
// Issue #63: validateCallbackAssignment, callbackSignaturesMatch, isConstValue,
// and validateBareIdentifierInScope moved to TypeValidator
// EnumTypeResolver now handles: _getEnumTypeFromThisEnum, _getEnumTypeFromGlobalEnum,
// _getEnumTypeFromThisVariable, _getEnumTypeFromScopedEnum, _getEnumTypeFromMemberAccess,
// _getExpressionEnumType, _getFunctionCallEnumType
/**
* ADR-017: Check if an expression represents an integer literal or numeric type.
* Used to detect comparisons between enums and integers.
*/
private _isIntegerExpression(
ctx: Parser.ExpressionContext | Parser.RelationalExpressionContext,
): boolean {
return EnumAssignmentValidator.isIntegerExpression(ctx);
}
/**
* ADR-045: Check if an expression is a string concatenation.
* Delegates to StringOperationsHelper.
*/
private _getStringConcatOperands(ctx: Parser.ExpressionContext): {
left: string;
right: string;
leftCapacity: number;
rightCapacity: number;
} | null {
return StringOperationsHelper.getStringConcatOperands(ctx);
}
/**
* ADR-045: Check if an expression is a substring extraction.
* Delegates to StringOperationsHelper.
*/
private _getSubstringOperands(ctx: Parser.ExpressionContext): {
source: string;
start: string;
length: string;
sourceCapacity: number;
} | null {
return StringOperationsHelper.getSubstringOperands(ctx, {
generateExpression: (exprCtx) => this.generateExpression(exprCtx),
});
}
// ========================================================================
// ADR-024: Type Classification and Validation Helpers
// ========================================================================
// NOTE: Public isIntegerType and isFloatType moved to IOrchestrator interface (ADR-053 A2)
// Private versions kept for internal use
private _isIntegerType(typeName: string): boolean {
return TypeResolver.isIntegerType(typeName);
}
private _isFloatType(typeName: string): boolean {
return TypeResolver.isFloatType(typeName);
}
/**
* ADR-024: Check if conversion from sourceType to targetType is narrowing
* Narrowing occurs when target type has fewer bits than source type
*/
private isNarrowingConversion(
sourceType: string,
targetType: string,
): boolean {
return TypeResolver.isNarrowingConversion(sourceType, targetType);
}
/**
* ADR-024: Check if conversion involves a sign change
* Sign change occurs when converting between signed and unsigned types
*/
private isSignConversion(sourceType: string, targetType: string): boolean {
return TypeResolver.isSignConversion(sourceType, targetType);
}
/**
* ADR-024: Validate that a literal value fits within the target type's range.
* Throws an error if the value doesn't fit.
* @param literalText The literal text (e.g., "256", "-1", "0xFF")
* @param targetType The target type (e.g., "u8", "i32")
*/
private _validateLiteralFitsType(
literalText: string,
targetType: string,
): void {
TypeResolver.validateLiteralFitsType(literalText, targetType);
}
/**
* ADR-024: Get the type of a unary expression (for cast validation).
*/
private getUnaryExpressionType(
ctx: Parser.UnaryExpressionContext,
): string | null {
return TypeResolver.getUnaryExpressionType(ctx);
}
/**
* ADR-024: Validate that a type conversion is allowed.
* Throws error for narrowing or sign-changing conversions.
*/
private _validateTypeConversion(
targetType: string,
sourceType: string | null,
): void {
TypeResolver.validateTypeConversion(targetType, sourceType);
}
// Issue #63: checkConstAssignment moved to TypeValidator
/**
* Check if an expression is an lvalue that needs & when passed to functions.
* This includes member access (cursor.x) and array access (arr[i]).
* Returns the type of lvalue or null if not an lvalue.
*/
private getLvalueType(
ctx: Parser.ExpressionContext,
): "member" | "array" | null {
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
Iif (!postfix) return null;
const ops = postfix.postfixOp();
const result = CppMemberHelper.getLastPostfixOpType(
this._toPostfixOps(ops),
);
// Function calls are not lvalues
Iif (result === "function") return null;
return result;
}
/**
* Issue #251/#252/#256: Check if a member access expression needs a temp variable in C++ mode.
*
* Returns true when passing struct member to function would fail C++ compilation:
* 1. Const struct parameter member -> non-const parameter (const T* -> T* invalid)
* 2. External C struct members of bool/enum type -> u8 parameter (type mismatch)
* 3. Array element member access (arr[i].member) with external struct elements
*/
private needsCppMemberConversion(
ctx: Parser.ExpressionContext,
targetParamBaseType?: string,
): boolean {
if (!CodeGenState.cppMode) return false;
if (!targetParamBaseType) return false;
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
if (!postfix) return false;
const primary = postfix.primaryExpression();
if (!primary) return false;
const baseId = primary.IDENTIFIER()?.getText();
if (!baseId) return false;
const ops = postfix.postfixOp();
// Case 1: Direct parameter member access (cfg.value)
const paramInfo = CodeGenState.currentParameters.get(baseId);
if (paramInfo) {
return this._needsParamMemberConversion(paramInfo, targetParamBaseType);
}
// Case 2: Array element or function return member access
return this._needsComplexMemberConversion(ops, baseId, targetParamBaseType);
}
/**
* Case 1: Direct parameter member access needs conversion?
* Issue #251: Const struct parameter needs temp to break const chain
* Issue #252: External C structs may have bool/enum members
*/
private _needsParamMemberConversion(
paramInfo: { baseType: string; isStruct?: boolean; isConst?: boolean },
targetParamBaseType: string,
): boolean {
return CppMemberHelper.needsParamMemberConversion(
paramInfo,
targetParamBaseType,
);
}
/**
* Convert parser PostfixOpContext to IPostfixOp interface for CppMemberHelper.
*/
private _toPostfixOps(ops: Parser.PostfixOpContext[]): IPostfixOp[] {
return ops.map((op) => ({
hasExpression: op.expression() !== null,
hasIdentifier: op.IDENTIFIER() !== null,
hasArgumentList: op.argumentList() !== null,
textEndsWithParen: op.getText().endsWith(")"),
}));
}
/**
* Case 2: Array element or function return member access needs conversion?
* Issue #256: arr[i].member or getConfig().member patterns
*/
private _needsComplexMemberConversion(
ops: Parser.PostfixOpContext[],
baseId: string,
targetParamBaseType: string,
): boolean {
const typeInfo = CodeGenState.getVariableTypeInfo(baseId);
return CppMemberHelper.needsComplexMemberConversion(
this._toPostfixOps(ops),
typeInfo,
targetParamBaseType,
);
}
/**
* Issue #246: Check if an expression is a subscript access on a string variable.
* For example, buf[0] where buf is a string<N>.
* Used to determine when to cast char* to uint8_t* etc.
*/
private isStringSubscriptAccess(ctx: Parser.ExpressionContext): boolean {
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
Iif (!postfix) return false;
const ops = postfix.postfixOp();
const hasPostfixOps = ops.length > 0;
const lastOpHasExpression =
hasPostfixOps && ops.at(-1)!.expression() !== null;
// Get the base identifier
const primary = postfix.primaryExpression();
const baseId = primary.IDENTIFIER()?.getText();
Iif (!baseId) return false;
const typeInfo = CodeGenState.getVariableTypeInfo(baseId);
const paramInfo = CodeGenState.currentParameters.get(baseId);
return CppMemberHelper.isStringSubscriptPattern(
hasPostfixOps,
lastOpHasExpression,
typeInfo,
paramInfo?.isString ?? false,
);
}
/**
* Issue #308: Check if a member access expression is accessing an array member.
* For example, result.data where data is a u8[6] array member.
* When passing such expressions to functions, the array should naturally decay
* to a pointer, so we should NOT add & operator.
*
* Note: Currently handles single-level member access only (e.g., result.data).
* Nested access like outer.inner.data would require traversing the postfix chain
* to resolve intermediate struct types. This is acceptable since issue #308
* involves single-level access patterns.
*
* Issue #355: Check if struct field info is available for a member access.
* Used for defensive code generation - when we don't have field info,
* we skip potentially dangerous conversions.
*
* @returns "array" if definitely an array, "not-array" if definitely not,
* "unknown" if struct field info is not available
*/
private getMemberAccessArrayStatus(
ctx: Parser.ExpressionContext,
): "array" | "not-array" | "unknown" {
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
Iif (!postfix) return "not-array";
const ops = postfix.postfixOp();
Iif (ops.length === 0) return "not-array";
// Last operator must be member access (.identifier)
const lastOp = ops.at(-1)!;
const memberName = lastOp.IDENTIFIER()?.getText();
Iif (!memberName) return "not-array";
// Get the base identifier to find the struct type
const primary = postfix.primaryExpression();
Iif (!primary) return "not-array";
const baseId = primary.IDENTIFIER()?.getText();
Iif (!baseId) return "not-array";
// Look up the struct type from either:
// 1. Local variable: typeRegistry.get(baseId).baseType
// 2. Parameter: currentParameters.get(baseId).baseType
let structType: string | undefined;
const typeInfo = CodeGenState.getVariableTypeInfo(baseId);
if (typeInfo) {
structType = typeInfo.baseType;
} else E{
const paramInfo = CodeGenState.currentParameters.get(baseId);
if (paramInfo) {
structType = paramInfo.baseType;
}
}
Iif (!structType) return "not-array";
// Check if this struct member is an array
const memberInfo = this.getMemberTypeInfo(structType, memberName);
// Issue #355: If memberInfo is undefined, we don't have struct field info
// This could mean the header wasn't parsed - return "unknown" for defensive generation
if (!memberInfo) {
return "unknown";
}
return memberInfo.isArray ? "array" : "not-array";
}
// ========================================================================
// Declarations
// ========================================================================
private generateDeclaration(ctx: Parser.DeclarationContext): string {
// ADR-016: Handle scope declarations (renamed from namespace)
if (ctx.scopeDeclaration()) {
return this.generateScope(ctx.scopeDeclaration()!);
}
if (ctx.registerDeclaration()) {
return this.generateRegister(ctx.registerDeclaration()!);
}
// Issue #369: Skip struct/enum/bitmap definitions when self-include is added
// These types will be defined in the included header file
if (ctx.structDeclaration()) {
if (CodeGenState.selfIncludeAdded) {
return ""; // Definition will come from header
}
return this.generateStruct(ctx.structDeclaration()!);
}
// ADR-017: Handle enum declarations
if (ctx.enumDeclaration()) {
if (CodeGenState.selfIncludeAdded) {
return ""; // Definition will come from header
}
return this.generateEnum(ctx.enumDeclaration()!);
}
// ADR-034: Handle bitmap declarations
if (ctx.bitmapDeclaration()) {
Iif (CodeGenState.selfIncludeAdded) {
return ""; // Definition will come from header
}
return this.generateBitmap(ctx.bitmapDeclaration()!);
}
if (ctx.functionDeclaration()) {
return this.generateFunction(ctx.functionDeclaration()!);
}
if (ctx.variableDeclaration()) {
return this.generateVariableDecl(ctx.variableDeclaration()!) + "\n";
}
return "";
}
// ========================================================================
// Scope (ADR-016: Organization with visibility control)
// ========================================================================
private generateScope(ctx: Parser.ScopeDeclarationContext): string {
// ADR-053: Check registry for extracted generator
const generator = this.registry.getDeclaration("scope");
Eif (generator) {
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
// Fallback to inline implementation (will be removed after migration)
const name = ctx.IDENTIFIER().getText();
CodeGenState.currentScope = name;
const lines: string[] = [];
lines.push(`/* Scope: ${name} */`);
for (const member of ctx.scopeMember()) {
this._generateScopeMember(member, name, lines);
}
lines.push("");
CodeGenState.currentScope = null;
return lines.join("\n");
}
/**
* Generate code for a single scope member
*/
private _generateScopeMember(
member: Parser.ScopeMemberContext,
scopeName: string,
lines: string[],
): void {
const visibility = member.visibilityModifier()?.getText() || "private";
const isPrivate = visibility === "private";
if (member.variableDeclaration()) {
this._generateScopeVariable(
member.variableDeclaration()!,
scopeName,
isPrivate,
lines,
);
} else if (member.functionDeclaration()) {
this._generateScopeFunction(
member.functionDeclaration()!,
scopeName,
isPrivate,
lines,
);
} else if (member.enumDeclaration()) {
lines.push("", this.generateEnum(member.enumDeclaration()!));
} else if (member.bitmapDeclaration()) {
lines.push("", this.generateBitmap(member.bitmapDeclaration()!));
} else if (member.registerDeclaration()) {
lines.push(
"",
this.generateScopedRegister(member.registerDeclaration()!, scopeName),
);
}
}
/**
* Generate code for a scope variable declaration
*/
private _generateScopeVariable(
varDecl: Parser.VariableDeclarationContext,
scopeName: string,
isPrivate: boolean,
lines: string[],
): void {
const type = this.generateType(varDecl.type());
const varName = varDecl.IDENTIFIER().getText();
const fullName = QualifiedNameGenerator.forMember(scopeName, varName);
const prefix = isPrivate ? "static " : "";
const arrayDims = varDecl.arrayDimension();
const hasArrayTypeSyntax = varDecl.type().arrayType() !== null;
const isArray = arrayDims.length > 0 || hasArrayTypeSyntax;
let decl = `${prefix}${type} ${fullName}`;
// Handle arrayType dimension (C-Next style: u8[16] data)
if (hasArrayTypeSyntax) {
decl += VariableDeclHelper.getArrayTypeDimension(varDecl.type(), {
tryEvaluateConstant: (exprCtx) => this.tryEvaluateConstant(exprCtx),
generateExpression: (exprCtx) => this.generateExpression(exprCtx),
});
}
// Handle arrayDimension (C-style or additional dimensions)
if (arrayDims.length > 0) {
decl += this.generateArrayDimensions(arrayDims);
}
// ADR-045: Add string capacity dimension for string arrays
decl += this._getStringCapacityDimension(varDecl.type());
if (varDecl.expression()) {
decl += ` = ${this.generateExpression(varDecl.expression()!)}`;
} else {
// ADR-015: Zero initialization for uninitialized scope variables
decl += ` = ${this.getZeroInitializer(varDecl.type(), isArray)}`;
}
lines.push(decl + ";");
}
/**
* Get string capacity dimension if type is string<N>
*/
private _getStringCapacityDimension(typeCtx: Parser.TypeContext): string {
if (!typeCtx.stringType()) return "";
const intLiteral = typeCtx.stringType()!.INTEGER_LITERAL();
if (!intLiteral) return "";
const capacity = Number.parseInt(intLiteral.getText(), 10);
return `[${capacity + 1}]`;
}
/**
* Generate code for a scope function declaration
*/
private _generateScopeFunction(
funcDecl: Parser.FunctionDeclarationContext,
scopeName: string,
isPrivate: boolean,
lines: string[],
): void {
const returnType = this.generateType(funcDecl.type());
const funcName = funcDecl.IDENTIFIER().getText();
const fullName = QualifiedNameGenerator.forFunctionStrings(
scopeName,
funcName,
);
const prefix = isPrivate ? "static " : "";
// Issue #269: Set current function name for pass-by-value lookup
CodeGenState.currentFunctionName = fullName;
// Issue #477: Set return type for enum inference in return statements
CodeGenState.currentFunctionReturnType = funcDecl.type().getText();
// Track parameters for ADR-006 pointer semantics
this._setParameters(funcDecl.parameterList() ?? null);
// ADR-016: Enter function body context (also clears modifiedParameters for Issue #281)
this.enterFunctionBody();
// Issue #281: Generate body FIRST to track parameter modifications
const body = this.generateBlock(funcDecl.block());
// Issue #281: Update symbol's parameter info with auto-const before generating params
this.updateFunctionParamsAutoConst(fullName);
// Now generate parameter list (can use modifiedParameters for auto-const)
const params = funcDecl.parameterList()
? this.generateParameterList(funcDecl.parameterList()!)
: "void";
// ADR-016: Exit function body context
this.exitFunctionBody();
CodeGenState.currentFunctionName = null;
CodeGenState.currentFunctionReturnType = null;
this._clearParameters();
lines.push("", `${prefix}${returnType} ${fullName}(${params}) ${body}`);
// ADR-029: Generate callback typedef only if used as a type
if (this.isCallbackTypeUsedAsFieldType(fullName)) {
const typedef = this.generateCallbackTypedef(fullName);
if (typedef) {
lines.push(typedef);
}
}
}
// ========================================================================
// Register Bindings (ADR-004)
// ========================================================================
private generateRegister(ctx: Parser.RegisterDeclarationContext): string {
// ADR-053: Check registry for extracted generator
const generator = this.registry.getDeclaration("register");
Eif (generator) {
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
// Fallback to inline implementation (will be removed after migration)
const name = ctx.IDENTIFIER().getText();
const baseAddress = this.generateExpression(ctx.expression());
const lines: string[] = [];
lines.push(`/* Register: ${name} @ ${baseAddress} */`);
// Generate individual #define for each register member with its offset
// This handles non-contiguous register layouts correctly (like i.MX RT1062)
for (const member of ctx.registerMember()) {
const regName = member.IDENTIFIER().getText();
const regType = this.generateType(member.type());
const access = member.accessModifier().getText();
const offset = this.generateExpression(member.expression());
// Determine qualifiers based on access mode
let cast = `volatile ${regType}*`;
if (access === "ro") {
cast = `volatile ${regType} const *`;
}
// Generate: #define GPIO7_DR (*(volatile uint32_t*)(0x42004000 + 0x00))
lines.push(
`#define ${name}_${regName} (*(${cast})(${baseAddress} + ${offset}))`,
);
}
lines.push("");
return lines.join("\n");
}
/**
* Generate register macros with scope prefix
* scope Teensy4 { register GPIO7 @ ... } generates Teensy4_GPIO7_* macros
*/
private generateScopedRegister(
ctx: Parser.RegisterDeclarationContext,
scopeName: string,
): string {
// ADR-053: Delegate to extracted generator
const result = scopedRegisterGenerator(
ctx,
scopeName,
this.getInput(),
this.getState(),
this,
);
this.applyEffects(result.effects);
return result.code;
}
// ========================================================================
// Struct
// ========================================================================
private generateStruct(ctx: Parser.StructDeclarationContext): string {
// ADR-053: Delegates to extracted StructGenerator
const generator = this.registry.getDeclaration("struct");
if (!generator) {
throw new Error("Error: struct generator not registered");
}
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
// ========================================================================
// Enum (ADR-017: Type-safe enums)
// ========================================================================
/**
* ADR-017: Generate enum declaration
* enum State { IDLE, RUNNING, ERROR <- 255 }
* -> typedef enum { State_IDLE = 0, State_RUNNING = 1, State_ERROR = 255 } State;
*
* ADR-053: Delegates to extracted EnumGenerator.
*/
private generateEnum(ctx: Parser.EnumDeclarationContext): string {
const generator = this.registry.getDeclaration("enum");
if (!generator) {
throw new Error("Error: enum generator not registered");
}
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
/**
* ADR-034: Generate bitmap declaration
* bitmap8 MotorFlags { Running, Direction, Mode[3], Reserved[2] }
* -> typedef uint8_t MotorFlags; (with field layout comment)
*
* ADR-053: Delegates to extracted generator if registered.
*/
private generateBitmap(ctx: Parser.BitmapDeclarationContext): string {
// ADR-053: Check registry for extracted generator
const generator = this.registry.getDeclaration("bitmap");
Eif (generator) {
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
// Fallback to inline implementation (will be removed after migration)
const name = ctx.IDENTIFIER().getText();
const prefix = CodeGenState.currentScope
? `${CodeGenState.currentScope}_`
: "";
const fullName = `${prefix}${name}`;
const backingType = CodeGenState.symbols!.bitmapBackingType.get(fullName);
Iif (!backingType) {
throw new Error(`Error: Bitmap ${fullName} not found in registry`);
}
this.requireInclude("stdint");
const lines: string[] = [];
// Generate comment with field layout
lines.push(`/* Bitmap: ${fullName} */`);
const fields = CodeGenState.symbols!.bitmapFields.get(fullName);
if (fields) {
lines.push("/* Fields:");
for (const [fieldName, info] of fields.entries()) {
const endBit = info.offset + info.width - 1;
const bitRange =
info.width === 1
? `bit ${info.offset}`
: `bits ${info.offset}-${endBit}`;
lines.push(
` * ${fieldName}: ${bitRange} (${info.width} bit${info.width > 1 ? "s" : ""})`,
);
}
lines.push(" */");
}
lines.push(`typedef ${backingType} ${fullName};`, "");
return lines.join("\n");
}
/**
* ADR-014: Generate struct initializer
* { x: 10, y: 20 } -> (Point){ .x = 10, .y = 20 } (type inferred from context)
*
* Note: Explicit type syntax (Point { x: 10 }) is rejected as redundant
* when type is already declared on the left side of assignment.
*/
private generateStructInitializer(
ctx: Parser.StructInitializerContext,
): string {
// Reject redundant type in struct initializer
// Wrong: const Point p <- Point { x: 0 };
// Right: const Point p <- { x: 0 };
Iif (ctx.IDENTIFIER() && CodeGenState.expectedType) {
const explicitType = ctx.IDENTIFIER()!.getText();
throw new Error(
`Redundant type '${explicitType}' in struct initializer. ` +
`Use '{ field: value }' syntax when type is already declared.`,
);
}
// Get type name - either explicit or inferred from context
let typeName: string;
if (ctx.IDENTIFIER()) {
typeName = ctx.IDENTIFIER()!.getText();
} else if (CodeGenState.expectedType) {
typeName = CodeGenState.expectedType;
} else E{
// This should not happen in valid code
throw new Error(
"Cannot infer struct type - no explicit type and no context",
);
}
const fieldList = ctx.fieldInitializerList();
// Issue #517: Check if this is a C++ class with a user-defined constructor.
// C++ classes with user-defined constructors are NOT aggregate types,
// so designated initializers { .field = value } don't work with them.
// We check the SymbolTable for a constructor symbol (TypeName::TypeName).
const isCppClass =
CodeGenState.cppMode && this._isCppClassWithConstructor(typeName);
// Issue #834: For named struct tags (no typedef), we need 'struct' prefix in C mode
const needsStructKeyword =
!CodeGenState.cppMode &&
CodeGenState.symbolTable.checkNeedsStructKeyword(typeName);
const castType = TypeGenerationHelper.generateUserType(
typeName,
needsStructKeyword,
);
if (!fieldList) {
// Empty initializer: Point {} -> (Point){ 0 } or {} for C++ classes
return isCppClass ? "{}" : `(${castType}){ 0 }`;
}
// Get field type info for nested initializers
// Issue #831: SymbolTable is the single source of truth for struct fields
// (both C-Next and C/C++ header structs)
const structFieldTypes =
CodeGenState.symbolTable?.getStructFieldTypes(typeName);
const fields = fieldList.fieldInitializer().map((field) => {
const fieldName = field.IDENTIFIER().getText();
// Compute expected type for nested initializers
let fieldType: string | undefined;
if (structFieldTypes?.has(fieldName)) {
// Issue #502: Convert underscore format to correct output format
// C-Next struct fields may store C++ types with _ separator (e.g., SeaDash_Parse_ParseResult)
// but code generation needs :: for C++ types (e.g., SeaDash::Parse::ParseResult)
fieldType = structFieldTypes.get(fieldName)!;
Iif (fieldType.includes("_")) {
// Check if this looks like a qualified type (contains _) and convert
const parts = fieldType.split("_");
if (parts.length > 1 && this.isCppScopeSymbol(parts[0])) {
// It's a C++ namespaced type - convert _ to ::
fieldType = parts.join("::");
}
}
}
const value = CodeGenState.withExpectedType(fieldType, () =>
this.generateExpression(field.expression()),
);
return { fieldName, value };
});
// Issue #517: For C++ classes, store assignments for later and return {}
Iif (isCppClass) {
for (const { fieldName, value } of fields) {
CodeGenState.pendingCppClassAssignments.push(
`${fieldName} = ${value};`,
);
}
return "{}";
}
// For C-Next/C structs, generate designated initializer
const fieldInits = fields.map((f) => `.${f.fieldName} = ${f.value}`);
// Issue #882: In C++ mode, anonymous structs/unions must use plain brace init.
// Compound literals like (struct { ... }){ ... } create incompatible types in C++
// because each struct { ... } definition creates a distinct nominal type.
Iif (
CodeGenState.cppMode &&
(typeName.startsWith("struct {") || typeName.startsWith("union {"))
) {
return `{ ${fieldInits.join(", ")} }`;
}
return `(${castType}){ ${fieldInits.join(", ")} }`;
}
/**
* ADR-035: Generate array initializer
* [1, 2, 3] -> {1, 2, 3}
* [0*] -> {0} (fill-all syntax)
* Returns: { elements: string, count: number } for size inference
*/
private generateArrayInitializer(
ctx: Parser.ArrayInitializerContext,
): string {
// Check for fill-all syntax: [value*]
if (ctx.expression() && ctx.getChild(2)?.getText() === "*") {
// Fill-all: [0*] -> {0}
const fillValue = this.generateExpression(ctx.expression()!);
// Store element count as 0 to signal fill-all (size comes from declaration)
CodeGenState.lastArrayInitCount = 0;
CodeGenState.lastArrayFillValue = fillValue;
return `{${fillValue}}`;
}
// Regular list: [1, 2, 3] -> {1, 2, 3}
const elements = ctx.arrayInitializerElement();
const generatedElements: string[] = [];
for (const elem of elements) {
if (elem.expression()) {
generatedElements.push(this.generateExpression(elem.expression()!));
E} else if (elem.structInitializer()) {
generatedElements.push(
this.generateStructInitializer(elem.structInitializer()!),
);
} else if (elem.arrayInitializer()) {
// Nested array for multi-dimensional
generatedElements.push(
this.generateArrayInitializer(elem.arrayInitializer()!),
);
}
}
// Store element count for size inference
CodeGenState.lastArrayInitCount = generatedElements.length;
CodeGenState.lastArrayFillValue = undefined;
return `{${generatedElements.join(", ")}}`;
}
// ========================================================================
// Functions
// ========================================================================
private generateFunction(ctx: Parser.FunctionDeclarationContext): string {
// ADR-053: Check registry for extracted generator
const generator = this.registry.getDeclaration("function");
Eif (generator) {
const result = generator(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
return result.code;
}
// Fallback to inline implementation (will be removed after migration)
const returnType = this.generateType(ctx.type());
const name = ctx.IDENTIFIER().getText();
// Set up function context
this._setupFunctionContext(name, ctx);
// Check for main function with args parameter (u8 args[][])
const isMainWithArgs = CodegenParserUtils.isMainFunctionWithArgs(
name,
ctx.parameterList(),
);
// Get return type and params, handling main with args special case
const { actualReturnType, initialParams } =
this._resolveReturnTypeAndParams(name, returnType, isMainWithArgs, ctx);
// Generate body first (this populates modifiedParameters)
const body = this.generateBlock(ctx.block());
// Issue #268: Update symbol's parameter info with auto-const before clearing
this.updateFunctionParamsAutoConst(name);
// Now generate parameter list (can use modifiedParameters for auto-const)
let params: string;
if (isMainWithArgs) {
params = initialParams;
} else if (ctx.parameterList()) {
params = this.generateParameterList(ctx.parameterList()!);
} else {
params = "void";
}
// Clean up function context
this._cleanupFunctionContext();
const functionCode = `${actualReturnType} ${name}(${params}) ${body}\n`;
// ADR-029: Generate callback typedef only if this function is used as a type
return this._appendCallbackTypedefIfNeeded(name, functionCode);
}
/**
* Set up context for function generation.
* Issue #793: Delegates to FunctionContextManager.
*/
private _setupFunctionContext(
name: string,
ctx: Parser.FunctionDeclarationContext,
): void {
FunctionContextManager.setupFunctionContext(
name,
ctx,
this._getFunctionContextCallbacks(),
);
}
/**
* Issue #793: Create callbacks for FunctionContextManager.
*/
private _getFunctionContextCallbacks(): IFunctionContextCallbacks {
return {
isStructType: (typeName: string) => this.isStructType(typeName),
resolveQualifiedType: (identifiers: string[]) =>
this.resolveQualifiedType(identifiers),
isTypedefStructType: (t: string) =>
CodeGenState.symbolTable?.isTypedefStructType(t) ?? false,
};
}
/**
* Resolve return type and initial params for function.
* Issue #793: Delegates to FunctionContextManager.
*/
private _resolveReturnTypeAndParams(
name: string,
returnType: string,
isMainWithArgs: boolean,
ctx: Parser.FunctionDeclarationContext,
): { actualReturnType: string; initialParams: string } {
return FunctionContextManager.resolveReturnTypeAndParams(
name,
returnType,
isMainWithArgs,
ctx,
);
}
/**
* Clean up context after function generation.
* Issue #793: Delegates to FunctionContextManager.
*/
private _cleanupFunctionContext(): void {
FunctionContextManager.cleanupFunctionContext();
}
/**
* Append callback typedef if function is used as a field type
*/
private _appendCallbackTypedefIfNeeded(
name: string,
functionCode: string,
): string {
if (name === "main") {
return functionCode;
}
if (!this.isCallbackTypeUsedAsFieldType(name)) {
return functionCode;
}
const typedef = this.generateCallbackTypedef(name);
return typedef ? functionCode + typedef : functionCode;
}
private generateParameter(
ctx: Parser.ParameterContext,
paramIndex?: number,
): string {
const typeName = this.getTypeName(ctx.type());
const name = ctx.IDENTIFIER().getText();
// Validate: Reject C-style array parameters
this._validateCStyleArrayParam(ctx, typeName, name);
// Validate: Reject unbounded array dimensions
this._validateUnboundedArrayParam(ctx);
// Pre-compute CodeGenState-dependent values
const isModified = this._isCurrentParameterModified(name);
// Issue #895: For callback-compatible functions, determine pointer/value
// from the typedef signature, not from normal C-Next pass-by-value rules
const callbackInfo =
paramIndex === undefined
? null
: FunctionContextManager.getCallbackTypedefParamInfo(paramIndex);
const isPassByValue = callbackInfo
? !callbackInfo.shouldBePointer
: this._isPassByValueType(typeName, name);
const isCallbackCompatible = callbackInfo !== null;
// Build normalized input using adapter
// Issue #895: Force pass-by-reference and const from typedef signature
const forcePassByReference = callbackInfo?.shouldBePointer ?? false;
const forceConst = callbackInfo?.shouldBeConst ?? false;
const input = ParameterInputAdapter.fromAST(ctx, {
getTypeName: (t) => this.getTypeName(t),
generateType: (t) => this.generateType(t),
generateExpression: (e) => this.generateExpression(e),
callbackTypes: CodeGenState.callbackTypes,
isKnownStruct: (t) => this.isKnownStruct(t),
typeMap: TYPE_MAP,
isModified,
isPassByValue,
isCallbackCompatible,
forcePassByReference,
forceConst,
isTypedefStructType: (t) =>
CodeGenState.symbolTable?.isTypedefStructType(t) ?? false,
});
// Use shared builder with C/C++ mode
return ParameterSignatureBuilder.build(input, CppModeHelper.refOrPtr());
}
/**
* Validate: Reject C-style array parameters
* C-style: u8 data[8], u8 data[4][4], u8 data[]
* C-Next: u8[8] data, u8[4][4] data, u8[] data
*/
private _validateCStyleArrayParam(
ctx: Parser.ParameterContext,
typeName: string,
name: string,
): void {
const dims = ctx.arrayDimension();
if (dims.length > 0) {
const dimensions = dims
.map((dim) => `[${dim.expression()?.getText() ?? ""}]`)
.join("");
const line = ctx.start?.line ?? 0;
const col = ctx.start?.column ?? 0;
throw new Error(
`${line}:${col} C-style array parameter is not allowed. ` +
`Use '${typeName}${dimensions} ${name}' instead of '${typeName} ${name}${dimensions}'`,
);
}
}
/**
* Validate: Reject unbounded array dimensions for memory safety
*/
private _validateUnboundedArrayParam(ctx: Parser.ParameterContext): void {
const arrayTypeCtx = ctx.type().arrayType();
if (!arrayTypeCtx) return;
const allDims = arrayTypeCtx.arrayTypeDimension();
const hasUnboundedDim = allDims.some((d) => !d.expression());
if (hasUnboundedDim) {
const line = ctx.start?.line ?? 0;
const col = ctx.start?.column ?? 0;
throw new Error(
`${line}:${col} Unbounded array parameters are not allowed. ` +
`All dimensions must have explicit sizes for memory safety.`,
);
}
}
/**
* Check if type should use pass-by-value semantics
*/
private _isPassByValueType(typeName: string, name: string): boolean {
// ISR, float, enum types
Iif (typeName === "ISR") return true;
if (this._isFloatType(typeName)) return true;
if (CodeGenState.symbols?.knownEnums.has(typeName)) return true;
// Small unmodified primitives
if (
CodeGenState.currentFunctionName &&
PassByValueAnalyzer.isParameterPassByValueByName(
CodeGenState.currentFunctionName,
name,
)
) {
return true;
}
// Callback-compatible functions: struct params become pass-by-value
// to match C function pointer typedef signatures
// NOTE: This assumes the C typedef expects pass-by-value structs.
// Issue #895 describes cases where the typedef expects pointers instead.
// A full fix requires parsing the typedef signature to determine which.
Iif (
CodeGenState.currentFunctionName &&
CodeGenState.callbackCompatibleFunctions.has(
CodeGenState.currentFunctionName,
) &&
this.isKnownStruct(typeName)
) {
return true;
}
return false;
}
// ========================================================================
// Variables
// ========================================================================
private generateVariableDecl(ctx: Parser.VariableDeclarationContext): string {
// Issue #792: Delegate to VariableDeclHelper
return VariableDeclHelper.generateVariableDecl(ctx, {
generateExpression: (exprCtx) => this.generateExpression(exprCtx),
generateType: (typeCtx) => this.generateType(typeCtx),
getTypeName: (typeCtx) => this.getTypeName(typeCtx),
generateArrayDimensions: (dims) => this.generateArrayDimensions(dims),
tryEvaluateConstant: (exprCtx) => this.tryEvaluateConstant(exprCtx),
getZeroInitializer: (typeCtx, isArray) =>
this.getZeroInitializer(typeCtx, isArray),
getExpressionType: (exprCtx) => this.getExpressionType(exprCtx),
inferVariableType: (varCtx, name) =>
this._inferVariableType(varCtx, name),
trackLocalVariable: (varCtx, name) =>
this._trackLocalVariable(varCtx, name),
markVariableAsPointer: (name) => this._markVariableAsPointer(name),
getStringConcatOperands: (concatCtx) =>
this._getStringConcatOperands(concatCtx),
getSubstringOperands: (substrCtx) =>
this._getSubstringOperands(substrCtx),
getStringExprCapacity: (exprCode) => this.getStringExprCapacity(exprCode),
requireStringInclude: () => this.requireInclude("string"),
});
}
/**
* Issue #696: Infer variable type, handling nullable C pointer types.
* Issue #895 Bug B: Infer pointer type from C function return type.
*/
private _inferVariableType(
ctx: Parser.VariableDeclarationContext,
name: string,
): string {
const type = this.generateType(ctx.type());
// Issue #958: C-header typedef struct types always need pointer semantics
Iif (CodeGenState.symbolTable?.isTypedefStructType(type)) {
return `${type}*`;
}
if (!ctx.expression()) {
return type;
}
// Issue #895 Bug B: Check if initializer is a C function call returning pointer
const pointerType = this._inferPointerTypeFromFunctionCall(
ctx.expression()!,
type,
);
if (pointerType) {
return pointerType;
}
// ADR-046: Handle nullable C pointer types (c_ prefix variables)
Iif (name.startsWith("c_")) {
const exprText = ctx.expression()!.getText();
for (const funcName of NullCheckAnalyzer.getStructPointerFunctions()) {
if (exprText.includes(`${funcName}(`)) {
return `${type}*`;
}
}
}
return type;
}
/**
* Issue #895 Bug B: Infer pointer type from C function return type.
* If initializer is a call to a C function that returns T*, and declared
* type is T, return T* instead of T.
*/
private _inferPointerTypeFromFunctionCall(
expr: Parser.ExpressionContext,
declaredType: string,
): string | null {
// Extract function name from C function call patterns
const funcName = this._extractCFunctionName(expr);
if (!funcName) {
return null;
}
// Look up C function in symbol table
const cFunc = CodeGenState.symbolTable?.getCSymbol(funcName);
if (cFunc?.kind !== "function") {
return null;
}
// Check if return type is a pointer to the declared type
const returnType = cFunc.type;
if (!returnType.endsWith("*")) {
return null;
}
// Check if the base return type matches the declared type
// e.g., "widget_t *" or "widget_t*" matches declared "widget_t"
const returnBaseType = returnType.replace(/\s*\*\s*$/, "").trim();
if (returnBaseType === declaredType) {
return `${declaredType}*`;
}
return null;
}
/**
* Extract C function name from expression patterns.
* Handles both:
* - global.funcName(...) - explicit global access
* - funcName(...) - direct call (if funcName is a known C function)
* Returns null if expression doesn't match these patterns.
*/
private _extractCFunctionName(expr: Parser.ExpressionContext): string | null {
const postfix = ExpressionUnwrapper.getPostfixExpression(expr);
if (!postfix) {
return null;
}
const primary = postfix.primaryExpression();
const ops = postfix.postfixOp();
// Pattern 1: global.funcName(...)
if (primary.GLOBAL()) {
return this._extractGlobalPatternFuncName(ops);
}
// Pattern 2: funcName(...) - direct call
const identifier = primary.IDENTIFIER();
if (identifier) {
return this._extractDirectCallFuncName(identifier.getText(), ops);
}
return null;
}
/**
* Extract function name from global.funcName(...) pattern.
*/
private _extractGlobalPatternFuncName(
ops: Parser.PostfixOpContext[],
): string | null {
Iif (ops.length < 2) {
return null;
}
const memberOp = ops[0];
Iif (!memberOp.IDENTIFIER()) {
return null;
}
const callOp = ops[1];
if (!this._isCallOp(callOp)) {
return null;
}
return memberOp.IDENTIFIER()!.getText();
}
/**
* Extract function name from direct funcName(...) call if it's a C function.
*/
private _extractDirectCallFuncName(
funcName: string,
ops: Parser.PostfixOpContext[],
): string | null {
if (ops.length < 1) {
return null;
}
if (!this._isCallOp(ops[0])) {
return null;
}
// Verify this is actually a C function (not a C-Next scope function)
const cFunc = CodeGenState.symbolTable?.getCSymbol(funcName);
if (cFunc?.kind === "function") {
return funcName;
}
return null;
}
/**
* Check if a postfix op is a function call.
*/
private _isCallOp(op: Parser.PostfixOpContext): boolean {
return Boolean(op.argumentList() || op.getText().startsWith("("));
}
/**
* Issue #696: Track local variable for type registry and const values.
*/
private _trackLocalVariable(
ctx: Parser.VariableDeclarationContext,
name: string,
): void {
if (!CodeGenState.inFunctionBody) {
return;
}
TypeRegistrationEngine.trackVariable(ctx, {
tryEvaluateConstant: (expr) => this.tryEvaluateConstant(expr),
requireInclude: (header) => this.requireInclude(header),
resolveQualifiedType: (ids) => this.resolveQualifiedType(ids),
});
CodeGenState.localVariables.add(name);
// Bug #8: Track local const values for array size and bit index resolution
if (ctx.constModifier() && ctx.expression()) {
const constValue = this.tryEvaluateConstant(ctx.expression()!);
if (constValue !== undefined) {
CodeGenState.constValues.set(name, constValue);
}
}
}
/**
* Issue #895 Bug B: Mark variable as a pointer in the type registry.
* Called when type inference detects that a variable should be a pointer
* (e.g., initialized from a C function returning T*).
*/
private _markVariableAsPointer(name: string): void {
const typeInfo = CodeGenState.getVariableTypeInfo(name);
Eif (typeInfo) {
CodeGenState.setVariableTypeInfo(name, {
...typeInfo,
isPointer: true,
});
}
}
// Issue #792: Methods _handleArrayDeclaration, _getArrayTypeDimension, _parseArrayTypeDimension,
// _parseFirstArrayDimension, _validateArrayDeclarationSyntax, _extractBaseTypeName,
// _generateVariableInitializer, _validateIntegerInitializer, _finalizeCppClassAssignments,
// and _generateConstructorDecl have been extracted to VariableDeclHelper.ts
/**
* Get zero initializer for array types.
* Issue #379: C++ class arrays must use {} instead of {0}
*/
private _getArrayZeroInitializer(typeCtx: Parser.TypeContext): string {
// Check if element type is a C++ class or template type
Iif (typeCtx.userType()) {
const typeName = typeCtx.userType()!.getText();
if (this._needsEmptyBraceInit(typeName)) {
return "{}";
}
}
// Also check C-Next style array type (e.g., CppClass[4]) where
// the userType is nested inside arrayType.
if (typeCtx.arrayType()?.userType()) {
const typeName = typeCtx.arrayType()!.userType()!.getText();
if (this._needsEmptyBraceInit(typeName)) {
return "{}";
}
}
// Template types are always C++ classes
Iif (typeCtx.templateType()) {
return "{}";
}
// Default: POD arrays use {0}
return "{0}";
}
/**
* Get zero initializer for an enum type.
* Returns member with value 0, or first member, or casted 0.
* ADR-017: Enums initialize to first member
*/
private _getEnumZeroValue(enumName: string, separator: string = "_"): string {
const members = CodeGenState.symbols!.enumMembers.get(enumName);
Iif (!members) {
return `(${enumName})0`;
}
// Find member with explicit value 0
for (const [memberName, value] of members.entries()) {
if (value === 0) {
return `${enumName}${separator}${memberName}`;
}
}
// Fall back to first member
const firstMember = members.keys().next().value;
Eif (firstMember) {
return `${enumName}${separator}${firstMember}`;
}
return `(${enumName})0`;
}
/**
* Resolve full type name from any TypeContext variant.
* Returns { name, separator, checkCppType } or null if not a named type.
* ADR-016: Handles scoped, global, qualified, and user types
* checkCppType: only true for userType (original behavior preserved)
*/
private _resolveTypeNameFromContext(
typeCtx: Parser.TypeContext,
): { name: string; separator: string; checkCppType: boolean } | null {
// ADR-016: Check for scoped types (this.Type)
if (typeCtx.scopedType()) {
const localName = typeCtx.scopedType()!.IDENTIFIER().getText();
const name = CodeGenState.currentScope
? `${CodeGenState.currentScope}_${localName}`
: localName;
return { name, separator: "_", checkCppType: false };
}
// Issue #478: Check for global types (global.Type)
if (typeCtx.globalType()) {
return {
name: typeCtx.globalType()!.IDENTIFIER().getText(),
separator: "_",
checkCppType: false,
};
}
// ADR-016: Check for qualified types (Scope.Type)
// Issue #388: Also handles C++ namespace types (MockLib.Parse.ParseResult)
if (typeCtx.qualifiedType()) {
const parts = typeCtx.qualifiedType()!.IDENTIFIER();
const name = this.resolveQualifiedType(parts.map((id) => id.getText()));
const separator = name.includes("::") ? "::" : "_";
return { name, separator, checkCppType: false };
}
// Check for user-defined types (structs/classes/enums)
if (typeCtx.userType()) {
return {
name: typeCtx.userType()!.getText(),
separator: "_",
checkCppType: true,
};
}
return null;
}
/**
* Check if a type needs empty brace initialization {}.
* Issue #304: C++ types with constructors may fail with {0}
* Issue #309: Unknown user types in C++ mode may have non-trivial constructors
*/
private _needsEmptyBraceInit(typeName: string): boolean {
// C++ types (external libraries with constructors)
Iif (this.isCppType(typeName)) {
return true;
}
// In C++ mode, unknown user types may have non-trivial constructors
// Known structs (C-Next or C headers) are POD types where {0} works
return CodeGenState.cppMode && !this.isKnownStruct(typeName);
}
/**
* Generate a safe bit mask expression.
* Avoids undefined behavior when width >= 32 for 32-bit integers.
* @param width The width expression (may be a literal or expression)
* @param isF64 If true, generate 64-bit masks with ULL suffix (for f64 bit indexing)
*/
// ========================================================================
// Statements
// Issue #644: _generateBitMask removed, now delegating to BitUtils.generateMask
// ========================================================================
// ADR-109: buildHandlerDeps removed - handlers now use CodeGenState.generator directly
/**
* Analyze a member chain target to detect bit access at the end.
* Issue #644: Delegates to MemberChainAnalyzer.
*/
/** Public for handler access via CodeGenState.generator */
analyzeMemberChainForBitAccess(targetCtx: Parser.AssignmentTargetContext): {
isBitAccess: boolean;
baseTarget?: string;
bitIndex?: string;
baseType?: string;
} {
// Issue #644: MemberChainAnalyzer is now static, pass generateExpression callback
return MemberChainAnalyzer.analyze(targetCtx, (ctx) =>
this.generateExpression(ctx),
);
}
/**
* Generate float bit write using shadow variable + memcpy.
* Issue #644: Delegates to FloatBitHelper.
*/
/** Public for handler access via CodeGenState.generator */
generateFloatBitWrite(
name: string,
typeInfo: TTypeInfo,
bitIndex: string,
width: string | null,
value: string,
): string | null {
// Issue #644: FloatBitHelper is now static, pass callbacks
return FloatBitHelper.generateFloatBitWrite(
name,
typeInfo,
bitIndex,
width,
value,
{
generateBitMask: (w, is64Bit) => this.generateBitMask(w, is64Bit),
foldBooleanToInt: (expr) => this.foldBooleanToInt(expr),
requireInclude: (header) => this.requireInclude(header),
},
);
}
// ADR-001: <- becomes = in C, with compound assignment operators
private generateAssignment(ctx: Parser.AssignmentStatementContext): string {
const targetCtx = ctx.assignmentTarget();
// Issue #644: Set expected type for inferred struct initializers and overflow behavior
// Delegated to AssignmentExpectedTypeResolver helper
const savedAssignmentContext = { ...CodeGenState.assignmentContext };
// Issue #644: AssignmentExpectedTypeResolver is now static
const resolved = AssignmentExpectedTypeResolver.resolve(targetCtx);
if (resolved.assignmentContext) {
CodeGenState.assignmentContext = resolved.assignmentContext;
}
// Use withExpectedType for exception safety on expectedType,
// manually save/restore assignmentContext
let value: string;
try {
value = CodeGenState.withExpectedType(resolved.expectedType, () =>
this.generateExpression(ctx.expression()),
);
} finally {
CodeGenState.assignmentContext = savedAssignmentContext;
}
// Get the assignment operator and map to C equivalent
const operatorCtx = ctx.assignmentOperator();
const cnextOp = operatorCtx.getText();
const cOp = ASSIGNMENT_OPERATOR_MAP[cnextOp] || "=";
const isCompound = cOp !== "=";
// Issue #644: Validate assignment (const, enum, integer, array bounds, callbacks)
// Delegated to AssignmentValidator helper to reduce cognitive complexity
AssignmentValidator.validate(
targetCtx,
ctx.expression(),
isCompound,
ctx.start?.line ?? 0,
{
getExpressionType: (exprCtx) => this.getExpressionType(exprCtx),
tryEvaluateConstant: (exprCtx) => this.tryEvaluateConstant(exprCtx),
isCallbackTypeUsedAsFieldType: (name) =>
this.isCallbackTypeUsedAsFieldType(name),
},
);
// ADR-109: Dispatch to assignment handlers
// Build context, classify, and dispatch - all patterns handled by handlers
const assignCtx = buildAssignmentContext(ctx, {
typeRegistry: CodeGenState.getTypeRegistryView(),
generateExpression: () => value,
generateAssignmentTarget: (targetCtx) =>
this.generateAssignmentTarget(targetCtx),
isKnownRegister: (name) => CodeGenState.symbols!.knownRegisters.has(name),
currentScope: CodeGenState.currentScope,
});
// ADR-109: Handlers access CodeGenState directly, no deps needed
const assignmentKind = AssignmentClassifier.classify(assignCtx);
const handler = AssignmentHandlerRegistry.getHandler(assignmentKind);
return handler(assignCtx);
}
/**
* ADR-049: Generate atomic Read-Modify-Write operation
* Uses LDREX/STREX on platforms that support it, otherwise PRIMASK
*/
/** Public for handler access via CodeGenState.generator */
generateAtomicRMW(
target: string,
cOp: string,
value: string,
typeInfo: TTypeInfo,
): string {
const result = atomicGenerators.generateAtomicRMW(
target,
cOp,
value,
typeInfo,
CodeGenState.targetCapabilities,
);
this.applyEffects(result.effects);
return result.code;
}
/**
* Build dependencies for SimpleIdentifierResolver
*/
private _buildSimpleIdentifierDeps(): ISimpleIdentifierDeps {
return {
getParameterInfo: (name: string) =>
CodeGenState.currentParameters.get(name),
resolveParameter: (name: string, paramInfo: TParameterInfo) =>
ParameterDereferenceResolver.resolve(
name,
paramInfo,
this._buildParameterDereferenceDeps(),
),
isLocalVariable: (name: string) => CodeGenState.localVariables.has(name),
resolveBareIdentifier: (name: string, isLocal: boolean) =>
TypeValidator.resolveBareIdentifier(name, isLocal, (n: string) =>
this.isKnownStruct(n),
),
};
}
/**
* Extract postfix operations from parser contexts
*/
private _extractPostfixOperations(
postfixOps: Parser.PostfixTargetOpContext[],
): IPostfixOperation[] {
return postfixOps.map((op) => ({
memberName: op.IDENTIFIER()?.getText() ?? null,
expressions: op.expression(),
}));
}
/**
* Build dependencies for PostfixChainBuilder
*/
private _buildPostfixChainDeps(
firstId: string,
hasGlobal: boolean,
hasThis: boolean,
): IPostfixChainDeps {
const paramInfo = CodeGenState.currentParameters.get(firstId);
const isStructParam = paramInfo?.isStruct ?? false;
const isCppAccess = hasGlobal && this.isCppScopeSymbol(firstId);
const separatorDeps = this._buildMemberSeparatorDeps();
// Issue #895: Callback-compatible params need pointer semantics even in C++ mode
const forcePointerSemantics = paramInfo?.forcePointerSemantics ?? false;
const separatorCtx: ISeparatorContext =
MemberSeparatorResolver.buildContext(
{
firstId,
hasGlobal,
hasThis,
currentScope: CodeGenState.currentScope,
isStructParam,
isCppAccess,
forcePointerSemantics,
},
separatorDeps,
);
return {
generateExpression: (expr: unknown) =>
this.generateExpression(expr as Parser.ExpressionContext),
getSeparator: (
isFirstOp: boolean,
identifierChain: string[],
memberName: string,
) =>
MemberSeparatorResolver.getSeparator(
isFirstOp,
identifierChain,
memberName,
separatorCtx,
separatorDeps,
),
};
}
// ADR-016: _validateCrossScopeVisibility moved to ScopeResolver
// Issue #387: Dead methods removed (generateGlobalMemberAccess, generateGlobalArrayAccess,
// generateThisMemberAccess, generateThisArrayAccess) - now handled by unified doGenerateAssignmentTarget
private generateIf(ctx: Parser.IfStatementContext): string {
return this.invokeStatement("if", ctx);
}
private generateWhile(ctx: Parser.WhileStatementContext): string {
return this.invokeStatement("while", ctx);
}
private generateDoWhile(ctx: Parser.DoWhileStatementContext): string {
return this.invokeStatement("do-while", ctx);
}
private generateFor(ctx: Parser.ForStatementContext): string {
return this.invokeStatement("for", ctx);
}
private generateReturn(ctx: Parser.ReturnStatementContext): string {
return this.invokeStatement("return", ctx);
}
// ========================================================================
// Critical Statements (ADR-050)
// ========================================================================
/**
* ADR-050: Generate critical statement with PRIMASK wrapper
* Ensures atomic execution of multi-variable operations
*/
private generateCriticalStatement(
ctx: Parser.CriticalStatementContext,
): string {
return this.invokeStatement("critical", ctx);
}
// Issue #63: validateNoEarlyExits moved to TypeValidator
// ========================================================================
// Switch Statements (ADR-025)
// ========================================================================
private generateSwitch(ctx: Parser.SwitchStatementContext): string {
return this.invokeStatement("switch", ctx);
}
// ========================================================================
// Expressions
// ========================================================================
// Issue #63: validateShiftAmount, getTypeWidth, evaluateShiftAmount,
// evaluateUnaryExpression moved to TypeValidator
/**
* Get the type of an additive expression.
*/
private _getAdditiveExpressionType(
ctx: Parser.AdditiveExpressionContext,
): string | null {
// For simple case, get type from first multiplicative expression
const multExprs = ctx.multiplicativeExpression();
Iif (multExprs.length === 0) return null;
return this.getMultiplicativeExpressionType(multExprs[0]);
}
/**
* Get the type of a multiplicative expression.
*/
private getMultiplicativeExpressionType(
ctx: Parser.MultiplicativeExpressionContext,
): string | null {
const unaryExprs = ctx.unaryExpression();
Iif (unaryExprs.length === 0) return null;
return this.getUnaryExpressionType(unaryExprs[0]);
}
/**
* Resolve 'this' keyword to scope marker
* ADR-016: 'this' returns a marker that postfixOps will transform to Scope_member
*/
private _resolveThisKeyword(): string {
if (!CodeGenState.currentScope) {
throw new Error("Error: 'this' can only be used inside a scope");
}
return "__THIS_SCOPE__";
}
/**
* Resolve an identifier in a primary expression context
* Handles: main args, parameters, local variables, scope resolution, enum members
*/
private _resolveIdentifierExpression(id: string): string {
// Special case: main function's args parameter -> argv
Iif (CodeGenState.mainArgsName && id === CodeGenState.mainArgsName) {
return "argv";
}
// ADR-006: Check if it's a function parameter
const paramInfo = CodeGenState.currentParameters.get(id);
if (paramInfo) {
return ParameterDereferenceResolver.resolve(
id,
paramInfo,
this._buildParameterDereferenceDeps(),
);
}
// ADR-016: Resolve bare identifier using local -> scope -> global priority
const isLocalVariable = CodeGenState.localVariables.has(id);
const resolved = TypeValidator.resolveBareIdentifier(
id,
isLocalVariable,
(name: string) => this.isKnownStruct(name),
);
if (resolved !== null) {
// Issue #741: Check if this is a private const that should be inlined
const constValue =
CodeGenState.symbols!.scopePrivateConstValues.get(resolved);
if (constValue !== undefined) {
return constValue;
}
return resolved;
}
// Issue #452: Check if identifier is an unqualified enum member reference
const enumResolved = this._resolveUnqualifiedEnumMember(id);
if (enumResolved !== null) {
return enumResolved;
}
return id;
}
/**
* Resolve an unqualified identifier as an enum member
* Issue #452: Uses expectedType for type-aware resolution, falls back to searching all enums
* @returns The qualified enum member access, or null if not an enum member
*/
private _resolveUnqualifiedEnumMember(id: string): string | null {
// Issue #872: MISRA contexts set expectedType for U suffix but suppress enum resolution
// Bare enum resolution in function args was never allowed and requires ADR approval to change
if (CodeGenState.suppressBareEnumResolution) {
// Fall through to error handling below - don't resolve bare enums
} else if (
// Type-aware resolution: check only the expected enum type
CodeGenState.expectedType &&
CodeGenState.symbols!.knownEnums.has(CodeGenState.expectedType)
) {
const members = CodeGenState.symbols!.enumMembers.get(
CodeGenState.expectedType,
);
if (members?.has(id)) {
return `${CodeGenState.expectedType}${this.getScopeSeparator(false)}${id}`;
}
return null;
}
// No expected enum type - bare enum members are not allowed without context
const matchingEnums: string[] = [];
for (const [enumName, members] of CodeGenState.symbols!.enumMembers) {
if (members.has(id)) {
matchingEnums.push(enumName);
}
}
Iif (matchingEnums.length === 1) {
throw new Error(
`error[E0424]: '${id}' is not defined; did you mean '${matchingEnums[0]}.${id}'?`,
);
}
if (matchingEnums.length > 1) {
const suggestions = matchingEnums.map((e) => `'${e}.${id}'`).join(" or ");
throw new Error(
`error[E0424]: '${id}' is not defined; did you mean ${suggestions}?`,
);
}
return null;
}
/**
* Generate a literal expression with C++ mode handling
* ADR-053 A2: Uses extracted literal generator
*/
private _generateLiteralExpression(ctx: Parser.LiteralContext): string {
const result = generateLiteral(ctx, this.getInput(), this.getState(), this);
this.applyEffects(result.effects);
// Issue #304/#644: Transform NULL → nullptr in C++ mode
if (result.code === "NULL") {
return CppModeHelper.nullLiteral();
}
return result.code;
}
/**
* ADR-017: Generate cast expression
* C mode: (u8)State.IDLE -> (uint8_t)State_IDLE
* C++ mode: (u8)State.IDLE -> static_cast<uint8_t>(State_IDLE)
* Issue #267: Use C++ casts when cppMode is enabled
*/
private generateCastExpression(ctx: Parser.CastExpressionContext): string {
const targetType = this.generateType(ctx.type());
const targetTypeName = ctx.type().getText();
// ADR-024: Validate integer casts for narrowing and sign conversion
Eif (this._isIntegerType(targetTypeName)) {
const sourceType = this.getUnaryExpressionType(ctx.unaryExpression());
Iif (sourceType && this._isIntegerType(sourceType)) {
if (this.isNarrowingConversion(sourceType, targetTypeName)) {
const targetWidth = TYPE_WIDTH[targetTypeName] || 0;
throw new Error(
`Error: Cannot cast ${sourceType} to ${targetTypeName} (narrowing). ` +
`Use bit indexing: expr[0, ${targetWidth}]`,
);
}
if (this.isSignConversion(sourceType, targetTypeName)) {
const targetWidth = TYPE_WIDTH[targetTypeName] || 0;
throw new Error(
`Error: Cannot cast ${sourceType} to ${targetTypeName} (sign change). ` +
`Use bit indexing: expr[0, ${targetWidth}]`,
);
}
}
}
const expr = this.generateUnaryExpr(ctx.unaryExpression());
// Issue #632: Float-to-integer casts must clamp to avoid undefined behavior
// C-Next's default is "clamp" (saturate), so out-of-range values clamp to type limits
const sourceType = this.getUnaryExpressionType(ctx.unaryExpression());
Eif (CastValidator.requiresClampingCast(sourceType, targetTypeName)) {
return this.generateFloatToIntClampCast(
expr,
targetType,
targetTypeName,
sourceType!,
);
}
// Validate enum casts are only to unsigned types
const allowedCastTypes = ["u8", "u16", "u32", "u64"];
// Check if we're casting an enum (for validation)
// We allow casts from any expression, but could add validation here
if (
!allowedCastTypes.includes(targetTypeName) &&
!["i8", "i16", "i32", "i64", "f32", "f64", "bool"].includes(
targetTypeName,
)
) {
// It's a user type cast - allow for now (could be struct pointer, etc.)
}
// Issue #267/#644: Use C++ casts when cppMode is enabled for MISRA compliance
return CppModeHelper.cast(targetType, expr);
}
/**
* Issue #632: Generate clamping cast for float-to-integer conversions
* In C, casting an out-of-range float to an integer is undefined behavior.
* C-Next's default overflow behavior is "clamp" (saturate), so we generate
* explicit bounds checks to ensure safe, deterministic results.
*
* @param expr The C expression for the float value
* @param targetType The C type name (e.g., "uint8_t")
* @param targetTypeName The C-Next type name (e.g., "u8")
* @param sourceType The source float type (e.g., "f32")
* @returns A clamping cast expression
*/
private generateFloatToIntClampCast(
expr: string,
targetType: string,
targetTypeName: string,
sourceType: string,
): string {
const maxValue = TYPE_LIMITS.TYPE_MAX[targetTypeName];
const minValue = TYPE_LIMITS.TYPE_MIN[targetTypeName];
Iif (!maxValue) {
// Unknown type, fall back to raw cast - Issue #644
return CppModeHelper.cast(targetType, expr);
}
// Mark that we need limits.h for the type limit macros
this.requireInclude("limits");
// Use appropriate float suffix and type for comparisons
const floatSuffix = sourceType === "f32" ? "f" : "";
const floatCastType = sourceType === "f32" ? "float" : "double";
// For unsigned types, minValue is "0", for signed it's a macro like INT8_MIN
const minComparison =
minValue === "0"
? `0.0${floatSuffix}`
: `((${floatCastType})${minValue})`;
const maxComparison = `((${floatCastType})${maxValue})`;
// Generate clamping expression:
// (expr > MAX) ? MAX : (expr < MIN) ? MIN : (type)(expr)
// Note: For unsigned targets, MIN is 0 so we check < 0.0
// MISRA 10.3: Cast limit macros to target type (they have type 'int')
const finalCast = CppModeHelper.cast(targetType, `(${expr})`);
const castMax = CppModeHelper.cast(targetType, maxValue);
const castMin =
minValue === "0" ? "0" : CppModeHelper.cast(targetType, minValue);
return `((${expr}) > ${maxComparison} ? ${castMax} : (${expr}) < ${minComparison} ? ${castMin} : ${finalCast})`;
}
/**
* ADR-023: Generate sizeof expression
* Delegates to SizeofResolver which uses CodeGenState.
*/
private generateSizeofExpr(ctx: Parser.SizeofExpressionContext): string {
return SizeofResolver.generate(ctx, {
generateType: (typeCtx) => this.generateType(typeCtx),
generateExpression: (exprCtx) => this.generateExpression(exprCtx),
hasSideEffects: (exprCtx) => this.hasSideEffects(exprCtx),
});
}
/**
* ADR-023: Check if expression has side effects (E0602)
* Side effects include: assignments, function calls
*/
private hasSideEffects(expr: Parser.ExpressionContext): boolean {
const text = expr.getText();
// Check for assignment operators
Iif (text.includes("<-")) return true;
Iif (text.includes("+<-")) return true;
Iif (text.includes("-<-")) return true;
Iif (text.includes("*<-")) return true;
Iif (text.includes("/<-")) return true;
Iif (text.includes("%<-")) return true;
Iif (text.includes("&<-")) return true;
Iif (text.includes("|<-")) return true;
Iif (text.includes("^<-")) return true;
Iif (text.includes("<<<-")) return true;
Iif (text.includes(">><-")) return true;
// Check for function calls by looking for identifier followed by (
// This is a heuristic - looking for "name(" pattern that's not a cast
Iif (/[a-zA-Z_]\w*\s*\(/.exec(text)) {
// Could be a function call - walk the tree to confirm
return this.hasPostfixFunctionCall(expr);
}
return false;
}
/**
* ADR-023: Check if expression contains a function call (postfix with argumentList)
*/
private hasPostfixFunctionCall(expr: Parser.ExpressionContext): boolean {
return ExpressionUtils.hasFunctionCall(expr);
}
// NOTE: generateMemberAccess and generateArrayAccess removed in grammar consolidation
// These methods referenced MemberAccessContext and ArrayAccessContext which no longer
// exist after unifying to assignmentTarget: IDENTIFIER postfixTargetOp*
// ========================================================================
// strlen Optimization - Cache repeated .length accesses
// Issue #644: Walker methods extracted to StringLengthCounter class
// ========================================================================
/**
* Generate temp variable declarations for string lengths that are accessed 2+ times.
* Returns the declarations as a string and populates the lengthCache.
*/
// ========================================================================
// ADR-044: Overflow Helper Functions
// ========================================================================
/**
* Generate all needed overflow helper functions
* ADR-053 A5: Delegates to HelperGenerator
*/
private generateOverflowHelpers(): string[] {
return helperGenerateOverflowHelpers(
CodeGenState.usedClampOps,
CodeGenState.debugMode,
);
}
/**
* Generate platform-portable IRQ wrappers for critical sections (ADR-050, Issue #778)
*
* Generates code that works on:
* - ARM platforms (bare-metal or Arduino): Uses inline assembly for PRIMASK access
* - AVR Arduino: Uses SREG save/restore pattern
* - Other platforms: Falls back to CMSIS intrinsics
*
* This avoids dependencies on CMSIS headers which may not be available on all platforms
* (e.g., Teensy 4.x via Arduino.h doesn't expose __get_PRIMASK/__set_PRIMASK).
*/
private generateIrqWrappers(): string[] {
return [
"// ADR-050: Platform-portable IRQ wrappers for critical sections",
"#if defined(__arm__) || defined(__ARM_ARCH)",
"// ARM platforms (including ARM Arduino like Teensy 4.x, Due, Zero)",
"// Provide inline assembly PRIMASK access to avoid CMSIS header dependencies",
"__attribute__((always_inline)) static inline uint32_t __cnx_get_PRIMASK(void) {",
" uint32_t result;",
' __asm volatile ("MRS %0, primask" : "=r" (result));',
" return result;",
"}",
"__attribute__((always_inline)) static inline void __cnx_set_PRIMASK(uint32_t mask) {",
' __asm volatile ("MSR primask, %0" :: "r" (mask) : "memory");',
"}",
"#if defined(ARDUINO)",
"static inline void __cnx_disable_irq(void) { noInterrupts(); }",
"#else",
"__attribute__((always_inline)) static inline void __cnx_disable_irq(void) {",
' __asm volatile ("cpsid i" ::: "memory");',
"}",
"#endif",
"#elif defined(__AVR__)",
"// AVR Arduino: use SREG for interrupt state",
"// Note: Uses PRIMASK naming for API consistency across platforms (AVR has no PRIMASK)",
"// Returns uint8_t which is implicitly widened to uint32_t at call sites - this is intentional",
"static inline uint8_t __cnx_get_PRIMASK(void) { return SREG; }",
"static inline void __cnx_set_PRIMASK(uint8_t mask) { SREG = mask; }",
"static inline void __cnx_disable_irq(void) { cli(); }",
"#else",
"// Fallback: assume CMSIS is available",
"static inline void __cnx_disable_irq(void) { __disable_irq(); }",
"static inline uint32_t __cnx_get_PRIMASK(void) { return __get_PRIMASK(); }",
"static inline void __cnx_set_PRIMASK(uint32_t mask) { __set_PRIMASK(mask); }",
"#endif",
"",
];
}
/**
* Mark a clamp operation as used (will trigger helper generation)
*/
private markClampOpUsed(operation: string, cnxType: string): void {
// Only generate helpers for integer types (not float/bool)
if (TYPE_WIDTH[cnxType] && TypeCheckUtils.isInteger(cnxType)) {
CodeGenState.usedClampOps.add(`${operation}_${cnxType}`);
}
}
// ========================================================================
// Preprocessor Directive Handling (ADR-037)
// ========================================================================
/**
* Process a preprocessor directive
* ADR-053 A5: Delegates to IncludeGenerator
*/
private processPreprocessorDirective(
ctx: Parser.PreprocessorDirectiveContext,
): string | null {
return includeProcessPreprocessorDirective(ctx);
}
// ========================================================================
// Comment Handling (ADR-043)
// ADR-053 A5: Delegates to CommentUtils
// ========================================================================
/**
* Get comments that appear before a parse tree node
*/
private getLeadingComments(ctx: {
start?: { tokenIndex: number } | null;
}): IComment[] {
return commentGetLeadingComments(ctx, this.commentExtractor);
}
/**
* Format leading comments with current indentation
*/
private formatLeadingComments(comments: IComment[]): string[] {
const indent = FormatUtils.indent(CodeGenState.indentLevel);
return commentFormatLeadingComments(
comments,
this.commentFormatter,
indent,
);
}
/**
* ADR-051: Generate safe division helper functions for used integer types only
* ADR-053 A5: Delegates to HelperGenerator
*/
private generateSafeDivHelpers(): string[] {
return helperGenerateSafeDivHelpers(CodeGenState.usedSafeDivOps);
}
}
|