All files / transpiler/output/codegen CodeGenerator.ts

80.85% Statements 1546/1912
71.9% Branches 760/1057
90.52% Functions 344/380
82.14% Lines 1509/1837

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 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552                                                                                                                                                                                                                                                                                                12x         12x         12x         12x                                                                               12x                           12x                                                                                                 12x             871x               1714x                                                       871x   871x   871x     871x     871x     871x     871x     871x     871x     871x     871x     871x     871x     871x     871x     871x               830x 830x 830x         830x     830x     830x           830x       830x 830x       830x       830x 830x 830x     830x       830x       830x 830x       830x       830x       830x       830x       830x       830x       830x       830x       830x 830x               161x 161x     161x 161x 161x               4840x 4840x     4840x 4840x 4840x     871x                     8771x                                       8794x                                             8744x 105x     83x 83x   1x 1x       2x     2x   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       4x 4x       1x 1x   1x 1x                       1461x   1210x 1210x   108x 108x   114x 114x   1x 1x   1x 1x   4x 4x   18x 18x   5x 5x               1x                     453x 51x 51x 31x         422x                   1531x                     4x 4x 4x 4x 4x                 3056x 3056x 1331x       3056x   16x   247x   16x                 1770x                 1736x           1736x 1736x               1539x                   655x                         61x               10x               54x                               128x                   72x                   72x     72x 2x       70x 34x 34x 3x             67x 67x   2x             2x 2x   2x       1x       66x                   8x               169x                           43x                                 8x               7x                     10x                   110x                     24x               26x               56x               60x                 2x                     338x               864x 864x   864x   895x 895x 895x   895x   876x   1209x 876x       845x   845x               5x               983x   983x 413x 570x 298x 272x 56x   216x 30x 186x 10x 176x 7x 169x 12x 157x 13x 144x 84x 60x   5x 55x 55x       964x 14x 14x 14x     950x                 85x 84x   1x 1x 1x               201x                     13x               7x                     59x                   5x                 276x 276x 276x 276x     276x 198x             78x 276x               276x 14x       63x 63x           63x                         70x                         30x                       28x               30x 30x   30x 1x 1x 1x 1x       30x 1x 1x     29x               29x               14x             110x     100x 57x 57x 56x     44x   10x         173x   201x             1586x 9x 9x 9x         1577x 9x       1568x 9x 18x 9x   1559x 229x   1330x 1312x   18x         112x                           182x 49x       133x 133x   56x 17x     39x 1x   38x       77x         77x 76x 76x       1x                                     2x                                                   27x 23x       4x 4x 4x 4x 4x                     797x         778x         563x 5x 4x     559x           520x 520x               1576x 1576x               80x             1374x 1374x           800x 800x 800x   800x   800x       781x 781x 781x 781x 781x   781x 781x       2x 2x             694x             3x 3x         3x     1x 1x     1x   1x                 3x                 871x             209x                 778x 778x 778x 201x 161x     778x                                   85x 85x 85x                   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               10x 10x               10x 10x       10x   10x             25x                     1733x 24x     1709x 1x     1708x 21x     1687x 16x       1671x 1671x 25x       1646x 23x     1623x 574x   1049x 1034x   15x 15x                   214x                       645x                     110x                       55x 55x       55x 7x               48x 48x 47x 47x   46x 46x 46x             2x               53x 53x     52x         53x 7x     53x                               38x               15x               16x               18x               21x               20x                         43x               140x 138x 22x     127x   21x                 63x 44x   67x   14x         3x   14x                             3x 1x                                                                 28x       28x     28x           28x                 41x                                 843x           843x 830x 830x       843x     843x     843x     843x 1x       842x     842x     842x     842x     842x                   843x 843x 843x 843x 843x 843x 843x 843x 843x   843x 843x                   843x     843x   843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x             842x     842x 130x       842x 842x 840x 408x         7x 7x 3x   3x                     842x     842x       143x       842x 842x     842x               432x 43x 335x   309x   13x       842x             842x 2x     842x       8x       842x           1x   2x       842x   25x     12x     28x     12x       842x   5x 5x     21x 3x 26x 23x 22x 21x 1x     842x     43x 43x     842x       12x   24x   12x 12x 9x     842x     44x     842x             45x 169x 143x 29x   1x                     842x 842x 842x     842x                 842x   109x   109x 109x 109x       842x     842x     842x     842x 842x     842x   842x                     842x       842x 34x 34x   34x 34x       34x             34x     841x 32x                     841x 4x 4x 4x 4x 2x       840x 3x               840x   840x 1415x 1415x   1415x 1415x 1360x       818x             818x   818x 818x 818x 818x 818x   818x 603x               818x 15x             818x 5x                 818x 2x             818x 818x 28x     818x 818x                             843x 3x 3x 1x     2x           842x 842x 1x       841x                 842x 842x 4x 4x   1x   1x 1x 1x 1x 1x         841x                 34x                             842x   1417x 130x 130x       1287x 114x 114x       1173x 696x                     130x     130x 130x   130x 205x 103x 103x   103x 103x   103x       103x   103x         130x                 114x   114x 188x 188x     188x 3x                           696x 696x   696x       696x   696x                     842x   1417x 388x       1417x 130x                             388x     388x 18x 18x 18x 12x                       130x     130x 130x   130x 205x 62x 62x 62x   62x         130x                                     842x 842x 842x 842x     842x     842x 842x     842x             842x               842x   23x       24x 24x 23x       1x     23x               842x   23x 24x 1x     23x                       866x   1443x 133x 133x   133x 208x 106x 106x 106x 106x           1443x 718x 718x 718x                         824x 824x 824x 183x 211x     824x     824x   824x 824x     824x 824x 824x                       928x   928x 932x                           938x 299x       938x 893x   893x       938x 938x 6x   938x 104x                         299x 299x     299x     299x         9x           299x 39x                           1157x 1157x   1157x 1173x                             893x 893x 893x 903x 1060x                                 1060x 1060x   1041x 1041x     1041x 1060x 915x         126x 41x   126x 7x                         2076x   2084x 2094x 2155x 2249x 2253x 2257x 2263x 2275x 2368x                       1173x 1354x                         1376x 22x         22x       1354x 1354x 1354x                         1354x 1354x     1354x     1354x     1354x 12x       1354x                       1354x   243x 243x   65x 65x                         1354x   282x   282x 348x 197x 151x 90x 90x 90x 61x 61x                         282x 282x   282x 243x 39x 23x 23x 22x     282x                         155x 155x   99x 99x 103x 103x 103x 18x           103x                       1354x 348x 53x 55x     348x 94x                         842x                       842x 800x   800x     800x 800x 799x 203x 203x   203x             203x 203x 203x     203x       203x           100x         800x                       351x 351x               55x 55x     55x 55x                 134x                                     836x                                       827x                 827x             54x       773x 773x               5x     768x               801x 801x                             35x                             863x 863x 827x     36x 36x 1x     35x 35x 35x     35x   35x   863x                     863x                   828x 694x     134x   6x 6x         128x   2x     126x     12x 24x 12x     114x 113x     1x                     863x 863x 863x     863x   863x     863x     863x                   35x       828x                         828x 828x 1x       827x                   59x       768x                                                                                                                                                                             768x       768x 768x       768x                               112x             797x 797x 797x   175x 203x               203x 203x 203x 203x     203x     203x                 203x     203x                       203x 142x               61x 48x 48x               13x 1x     2x 1x 1x               12x 3x 3x     3x               9x 3x 3x               6x 6x                                                     203x 203x   203x 203x     203x         203x 203x 1x     203x                               203x                   203x 6x 6x 6x               778x 201x 201x   778x 778x 778x 778x                             799x   799x 175x 203x 203x   203x 203x 203x       799x                     799x               799x   799x 175x 203x 203x 203x 203x 203x     203x         203x   3x 3x 3x   200x   200x     203x 21x   203x                     799x                                               115x     115x         20x       95x 39x 39x         23x       72x                             26x 26x 26x     26x     3x 3x     3x 3x     3x 3x   3x         3x       3x                                                 23x 23x   23x 23x     23x   2x 2x     2x 2x   2x     2x 2x           2x 1x           1x   1x                                   772x       318x                                                               281x                 10x                     180x                         4x 4x   4x 4x         4x 4x                             2x                 2x                                                                 4x                                                                                                                                                       4x 4x   4x 4x     4x 4x 4x     4x 4x 4x 4x             4x 4x 4x               4x     4x       4x       4x                                 24x 24x 20x     4x 4x 4x                     20x 7x       13x 3x         10x 10x 1x       9x                 9x                       4x 4x       4x       2x 2x     2x       2x                   4x     4x 2x       2x             2x                                                                                                                                                 1415x 130x   1285x 7x       1278x 114x 5x   109x     1164x 55x 10x   45x     1109x 9x     9x   1100x 694x   406x 388x   18x                 130x 130x 130x 130x 130x                                                                                                                                                                                                                                                                                                                               7x 7x 7x 7x 7x                                                                                                                       109x 109x 1x   108x 108x 108x                             45x 45x 1x   44x 44x 44x                       9x 9x 9x 9x 9x               9x   9x 9x                                                                                         21x                   21x   21x 21x               21x             21x   21x             21x   21x 38x     38x 38x       34x 34x               34x     38x     38x   38x       21x                   38x 21x                         16x   2x   2x 2x 2x       14x 14x   14x 53x 53x                           14x 14x   14x                 694x 694x 694x 694x 694x                                                                                                                                                                                                                                                               201x 201x 201x 201x     201x 3x 3x     198x     198x           198x   197x 197x     180x 111x       69x           69x     64x 64x     1x                       198x 197x     1x 1x     198x 198x                       197x 180x     18x 17x 17x 197x               180x 180x 177x     169x       100x     69x                       69x 64x     5x 5x 69x                       64x 1x     63x 63x 64x 64x                 801x 801x         801x         801x 801x 801x     801x     801x               801x 35x       765x 765x     765x 765x 12x   753x     753x               753x                   800x     800x 800x                                     800x 387x     413x 413x     413x 2x 2x 1x                           765x 765x   765x 705x     66x 60x     60x 12x               12x 12x                   48x 48x   48x                 60x 3x   57x 57x 50x   7x                       753x   152x     601x 601x 601x     601x     601x   601x 601x   601x                   601x 140x     461x 461x 601x 601x   601x 601x   281x     180x 180x       3x     3x                         745x 745x                                                                                                                                                                                           49x 6x 6x         49x       49x                 17x 17x         17x 20x 16x         1x 1x 1x                               133x 5x 5x     5x       128x 2x                 126x 6x 12x 6x 6x       120x 43x             77x                   41x         41x                               295x           37x   264x 42x 16x   4x   1x   2x   3x         6x     9x   5x     7x   27x   1x                               9x                           5x                     298x       298x 298x   298x 298x 207x   298x 171x     298x     298x 298x     298x 298x 298x 298x       298x                 298x   295x   298x 298x               298x 298x 298x                         1x             1x 1x             198x   198x   17x         181x   181x 1x                     81x                           63x 63x 63x 63x     63x                   63x   8x           72x                               30x       10x       7x       12x       84x                           5x                   13x                                 8x 8x   8x                 8x 8x   8x               25x 1x   24x                 574x         574x 574x 123x               451x 451x     27x   451x     24x 24x 2x   22x       427x 427x       426x                   427x       41x     41x     41x       386x 386x 20x 2x       386x     386x 1x         385x               1034x 1034x     1034x 2x     1032x                   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                                                               818x                     27x 27x                             4x                           1453x             1453x 1453x                       818x      
/**
 * C-Next Code Generator
 * Transforms C-Next AST to clean, readable C code
 */
 
import { CommonTokenStream, ParserRuleContext } from "antlr4ng";
import * as Parser from "../../logic/parser/grammar/CNextParser";
import SymbolTable from "../../logic/symbols/SymbolTable";
import ESymbolKind from "../../../utils/types/ESymbolKind";
import CommentExtractor from "../../logic/analysis/CommentExtractor";
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 TOverflowBehavior from "./types/TOverflowBehavior";
import ICodeGeneratorOptions from "./types/ICodeGeneratorOptions";
import TypeResolver from "./TypeResolver";
import ICodeGenSymbols from "../../types/ICodeGenSymbols";
import TypeValidator from "./TypeValidator";
import TypeRegistrationUtils from "./TypeRegistrationUtils";
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";
import IHandlerDeps from "./assignment/handlers/IHandlerDeps";
// 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
import StringDeclHelper from "./helpers/StringDeclHelper";
// 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
import ArrayInitHelper from "./helpers/ArrayInitHelper";
// 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
import VariableModifierBuilder from "./helpers/VariableModifierBuilder";
// 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 #566: Statement expression collection for const inference
import StatementExpressionCollector from "./helpers/StatementExpressionCollector";
// Issue #269: Transitive modification propagation for const inference
import TransitiveModificationPropagator from "./helpers/TransitiveModificationPropagator";
// Issue #566: Child statement/block collection for const inference
import ChildStatementCollector from "./helpers/ChildStatementCollector";
// SonarCloud S3776: Assignment target extraction for walkStatementForModifications
import AssignmentTargetExtractor from "./helpers/AssignmentTargetExtractor";
// 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";
// Global state for code generation (simplifies debugging, eliminates DI complexity)
import CodeGenState from "./CodeGenState";
// Extracted resolvers that use CodeGenState
import SizeofResolver from "./resolution/SizeofResolver";
import EnumTypeResolver from "./resolution/EnumTypeResolver";
import ScopeResolver from "./resolution/ScopeResolver";
 
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,
};
 
/**
 * ADR-044: Assignment context for overflow behavior tracking
 */
interface AssignmentContext {
  targetName: string | null;
  targetType: string | null;
  overflowBehavior: TOverflowBehavior;
}
 
/**
 * Context for tracking current scope during code generation
 */
interface GeneratorContext {
  currentScope: string | null; // ADR-016: renamed from currentNamespace
  currentFunctionName: string | null; // Issue #269: track current function for pass-by-value lookup
  currentFunctionReturnType: string | null; // Issue #477: track return type for enum inference
  indentLevel: number;
  scopeMembers: Map<string, Set<string>>; // scope -> member names (ADR-016)
  currentParameters: Map<string, TParameterInfo>; // ADR-006: track params for pointer semantics
  // Issue #558: modifiedParameters removed - now uses analysis-phase results from CodeGenState.modifiedParameters
  localArrays: Set<string>; // ADR-006: track local array variables (no & needed)
  localVariables: Set<string>; // ADR-016: track local variables (allowed as bare identifiers)
  floatBitShadows: Set<string>; // Track declared shadow variables for float bit indexing
  floatShadowCurrent: Set<string>; // Track which shadows have current value (skip redundant memcpy reads)
  inFunctionBody: boolean; // ADR-016: track if we're inside a function body
  typeRegistry: Map<string, TTypeInfo>; // Track variable types for bit access and .length
  expectedType: string | null; // For inferred struct initializers
  mainArgsName: string | null; // Track the args parameter name for main() translation
  assignmentContext: AssignmentContext; // ADR-044: Track current assignment for overflow
  lastArrayInitCount: number; // ADR-035: Track element count for size inference
  lastArrayFillValue: string | undefined; // ADR-035: Track fill-all value
  lengthCache: Map<string, string> | null; // Cache: variable name -> temp variable name for strlen optimization
  targetCapabilities: TargetCapabilities; // ADR-049: Target platform for atomic code generation
}
 
/**
 * 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"],
    ]);
 
  private context: GeneratorContext =
    CodeGenerator.createDefaultContext(DEFAULT_TARGET);
 
  /**
   * Create a fresh GeneratorContext with default values.
   */
  private static createDefaultContext(
    targetCapabilities: TargetCapabilities,
  ): GeneratorContext {
    return {
      currentScope: null,
      currentFunctionName: null,
      currentFunctionReturnType: null,
      indentLevel: 0,
      scopeMembers: new Map(),
      currentParameters: new Map(),
      localArrays: new Set(),
      localVariables: new Set(),
      floatBitShadows: new Set(),
      floatShadowCurrent: new Set(),
      inFunctionBody: false,
      typeRegistry: new Map(),
      expectedType: null,
      mainArgsName: null,
      assignmentContext: {
        targetName: null,
        targetType: null,
        overflowBehavior: "clamp",
      },
      lastArrayInitCount: 0,
      lastArrayFillValue: undefined,
      lengthCache: null,
      targetCapabilities,
    };
  }
 
  /** 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 */
  private typeResolver: TypeResolver | null = null;
 
  /** Symbol collection - ADR-055: Now uses ISymbolInfo from TSymbolInfoAdapter */
  public symbols: ICodeGenSymbols | null = null;
 
  /** Type validation - Issue #63: Extracted from CodeGenerator */
  private typeValidator: TypeValidator | null = null;
 
  /** Issue #644: String length counter for strlen caching optimization */
  private stringLengthCounter: StringLengthCounter | null = null;
 
  /** Issue #644: Member chain analyzer for bit access pattern detection */
  private memberChainAnalyzer: MemberChainAnalyzer | null = null;
 
  /** Issue #644: Float bit write helper for shadow variable pattern */
  private floatBitHelper: FloatBitHelper | null = null;
 
  /** Issue #644: String declaration helper for bounded/array/concat strings */
  private stringDeclHelper: StringDeclHelper | null = null;
 
  /** Issue #644: Enum assignment validator for type-safe enum assignments */
  private enumValidator: EnumAssignmentValidator | null = null;
 
  /** Issue #644: Array initialization helper for size inference and fill-all */
  private arrayInitHelper: ArrayInitHelper | null = null;
 
  /** Issue #644: Assignment expected type resolution helper */
  private expectedTypeResolver: AssignmentExpectedTypeResolver | null = null;
 
  /** Issue #644: Assignment validation coordinator helper */
  private assignmentValidator: AssignmentValidator | null = null;
 
  /** Generator registry for modular code generation (ADR-053) */
  private readonly registry: GeneratorRegistry = new GeneratorRegistry();
 
  /** Issue #644: C/C++ mode helper for consolidated mode-specific patterns */
  private cppHelper: CppModeHelper | null = null;
 
  /**
   * 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.typeRegistry,
      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.scopeMembers,
      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.typeRegistry.set(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.scopeMembers.get(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.
   */
  generateExpressionWithExpectedType(
    ctx: Parser.ExpressionContext,
    expectedType: string | null,
  ): string {
    const savedExpectedType = CodeGenState.expectedType;
    CodeGenState.expectedType = expectedType;
    const result = this.generateExpression(ctx);
    CodeGenState.expectedType = savedExpectedType;
    return result;
  }
 
  /**
   * 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) ?? false,
      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 this.typeResolver!.isFloatType(typeName);
  }
 
  /**
   * Check if a type is an integer type.
   * Part of IOrchestrator interface - delegates to TypeResolver.
   */
  isIntegerType(typeName: string): boolean {
    return this.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.typeRegistry.get(text);
      if (typeInfo?.isString) {
        return true;
      }
    }
 
    // Issue #137: Check for array element access (e.g., names[0], arr[i])
    // Pattern: identifier[expression] or identifier[expression][expression]...
    // BUT NOT if accessing .length/.capacity/.size (those return numbers, not strings)
    const arrayAccessMatch = /^([a-zA-Z_]\w*)\[/.exec(text);
    if (arrayAccessMatch) {
      // ADR-045: String properties return numeric values, not strings
      Iif (
        text.endsWith(".length") ||
        text.endsWith(".capacity") ||
        text.endsWith(".size")
      ) {
        return false;
      }
      const arrayName = arrayAccessMatch[1];
      const typeInfo = CodeGenState.typeRegistry.get(arrayName);
      // Check if base type is a string type
      if (
        typeInfo?.isString ||
        (typeInfo?.baseType && TypeCheckUtils.isString(typeInfo.baseType))
      ) {
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * 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 {
    this.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 {
    this.typeValidator!.validateTernaryCondition(condition);
  }
 
  /**
   * Validate no nested ternary expressions (ADR-022).
   * Part of IOrchestrator interface - delegates to TypeValidator.
   */
  validateNoNestedTernary(
    expr: Parser.OrExpressionContext,
    branchName: string,
  ): void {
    this.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 private implementation.
   */
  generateFunctionArg(
    ctx: Parser.ExpressionContext,
    targetParamBaseType?: string,
  ): string {
    return this._generateFunctionArg(ctx, targetParamBaseType);
  }
 
  /**
   * Check if a value is const.
   * Part of IOrchestrator interface - delegates to TypeValidator.
   */
  isConstValue(name: string): boolean {
    return this.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 this.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 {
    this.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()!);
    E} 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 {
    this.typeValidator!.validateSwitchStatement(ctx, switchExpr);
  }
 
  /**
   * Validate do-while condition.
   * Part of IOrchestrator interface (ADR-053 A3).
   */
  validateDoWhileCondition(ctx: Parser.ExpressionContext): void {
    this.typeValidator!.validateDoWhileCondition(ctx);
  }
 
  /**
   * Issue #254: Validate no function calls in condition (E0702).
   * Part of IOrchestrator interface (ADR-053 A3).
   */
  validateConditionNoFunctionCall(
    ctx: Parser.ExpressionContext,
    conditionType: string,
  ): void {
    this.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 {
    this.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(),
      );
    }
 
    // SonarCloud S3776: Use BaseIdentifierBuilder for base identifier
    const safeIdentifier = identifier ?? "";
    const { result: baseResult, firstId } = BaseIdentifierBuilder.build(
      safeIdentifier,
      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
    return this.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
    this.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) => this.generateParameter(p))
      .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);
    }
    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 {
    // String literal - capacity equals content length
    if (exprCode.startsWith('"') && exprCode.endsWith('"')) {
      return StringUtils.literalLength(exprCode);
    }
 
    // Variable - check type registry
    const identifierRegex = /^[a-zA-Z_]\w*$/;
    Eif (identifierRegex.test(exprCode)) {
      const typeInfo = CodeGenState.typeRegistry.get(exprCode);
      Eif (typeInfo?.isString && typeInfo.stringCapacity !== undefined) {
        return typeInfo.stringCapacity;
      }
    }
 
    return null;
  }
 
  // === 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) ===
 
  enterFunctionBody(): void {
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    // Issue #558: modifiedParameters tracking removed - uses analysis-phase results
    CodeGenState.inFunctionBody = true;
    // Sync with CodeGenState
    CodeGenState.enterFunctionBody();
  }
 
  exitFunctionBody(): void {
    CodeGenState.inFunctionBody = false;
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.mainArgsName = null;
    // Sync with CodeGenState
    CodeGenState.exitFunctionBody();
    CodeGenState.mainArgsName = null;
  }
 
  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
                return `${constMod}${p.type}*`;
              } 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: Store unmodified parameters for a function.
   * Maps function name -> Set of parameter names that were NOT modified.
   * Used by Pipeline to update symbol info before header generation.
   */
  private readonly functionUnmodifiedParams: Map<string, Set<string>> =
    new Map();
 
  /**
   * Issue #268: Get unmodified parameters info for all functions.
   * Returns map of function name -> Set of unmodified parameter names.
   */
  getFunctionUnmodifiedParams(): ReadonlyMap<string, Set<string>> {
    return this.functionUnmodifiedParams;
  }
 
  /**
   * Issue #268: Update symbol parameters with auto-const info.
   * Issue #558: Now uses analysis-phase results for modification tracking.
   */
  updateFunctionParamsAutoConst(functionName: string): void {
    // Collect unmodified parameters for this function using analysis results
    const unmodifiedParams = new Set<string>();
    const modifiedSet = CodeGenState.modifiedParameters.get(functionName);
    for (const [paramName] of CodeGenState.currentParameters) {
      if (!modifiedSet?.has(paramName)) {
        unmodifiedParams.add(paramName);
      }
    }
    this.functionUnmodifiedParams.set(functionName, unmodifiedParams);
  }
 
  /**
   * 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 Pipeline.transpileSource() to collect modification info from includes
   * for cross-file const inference (unified with Pipeline.run() behavior).
   *
   * 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)
    this.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 {
    const unmodifiedParams = this.functionUnmodifiedParams.get(funcName);
    Iif (!unmodifiedParams) {
      // Callee not yet processed - conservatively return false (assume unmodified)
      // This means we won't mark our param as modified, which may cause a C compiler error
      // if the callee actually modifies the param. The C compiler will catch this.
      return false;
    }
 
    // Get the parameter name at the given index from the function signature
    const sig = CodeGenState.functionSignatures.get(funcName);
    Iif (!sig || paramIndex >= sig.parameters.length) {
      return false;
    }
 
    const paramName = sig.parameters[paramIndex].name;
    // If the param is NOT in the unmodified set, it was modified
    return !unmodifiedParams.has(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.
   */
  getStructFieldInfo(
    structType: string,
    fieldName: string,
  ): { type: string; dimensions?: (number | string)[] } | null {
    // First check SymbolTable (C header structs)
    Eif (CodeGenState.symbolTable) {
      const fieldInfo = CodeGenState.symbolTable.getStructFieldInfo(
        structType,
        fieldName,
      );
      if (fieldInfo) {
        return {
          type: fieldInfo.type,
          dimensions: fieldInfo.arrayDimensions,
        };
      }
    }
 
    // Fall back to local C-Next struct fields
    const localFields = CodeGenState.symbols!.structFields.get(structType);
    if (localFields) {
      const fieldType = localFields.get(fieldName);
      if (fieldType) {
        const fieldDimensions =
          CodeGenState.symbols!.structFieldDimensions.get(structType);
        const dimensions = fieldDimensions?.get(fieldName);
        return {
          type: fieldType,
          dimensions: dimensions ? [...dimensions] : undefined,
        };
      }
    }
 
    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);
  }
 
  // ===========================================================================
  // 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) =>
        this._isParameterPassByValueByName(funcName, paramName),
      currentFunctionName: CodeGenState.currentFunctionName,
      maybeDereference: (id: string) => this.cppHelper!.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
   */
  private _validateRegisterAccess(
    registerName: string,
    memberName: string,
    hasGlobal: boolean,
  ): void {
    // Only validate when inside a scope and accessing without global. prefix
    if (CodeGenState.currentScope && !hasGlobal) {
      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 symbolTable Optional symbol table for cross-language interop
   * @param tokenStream Optional token stream for comment preservation (ADR-043)
   * @param options Optional code generator options (e.g., debugMode)
   */
  generate(
    tree: Parser.ProgramContext,
    symbolTable?: SymbolTable,
    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);
 
    // Store symbol table for function lookup (after reset)
    CodeGenState.symbolTable = symbolTable ?? null;
 
    // 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;
    this.cppHelper = new CppModeHelper({ cppMode: CodeGenState.cppMode });
    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 first
    CodeGenState.reset(targetCapabilities);
 
    // Reset local context (will gradually migrate to CodeGenState)
    this.context = CodeGenerator.createDefaultContext(targetCapabilities);
 
    CodeGenState.knownFunctions = new Set();
    CodeGenState.functionSignatures = new Map();
    CodeGenState.callbackTypes = new Map();
    CodeGenState.callbackFieldTypes = new Map();
    CodeGenState.usedClampOps = new Set();
    CodeGenState.usedSafeDivOps = new Set();
    CodeGenState.needsStdint = false;
    CodeGenState.needsStdbool = false;
    CodeGenState.needsString = false;
    CodeGenState.needsFloatStaticAssert = false;
    CodeGenState.needsISR = false;
    CodeGenState.needsCMSIS = false;
    CodeGenState.needsLimits = false;
    CodeGenState.needsIrqWrappers = false;
    CodeGenState.selfIncludeAdded = false;
  }
 
  /**
   * 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.scopeMembers.set(scopeName, new Set(members));
    }
 
    // Issue #461: Initialize constValues from symbol table
    CodeGenState.constValues = new Map();
    if (CodeGenState.symbolTable) {
      for (const symbol of CodeGenState.symbolTable.getAllSymbols()) {
        if (
          symbol.kind === ESymbolKind.Variable &&
          symbol.isConst &&
          symbol.initialValue !== undefined
        ) {
          const value = LiteralUtils.parseIntegerLiteral(symbol.initialValue);
          if (value !== undefined) {
            CodeGenState.constValues.set(symbol.name, value);
            // Also populate CodeGenState
            CodeGenState.constValues.set(symbol.name, value);
          }
        }
      }
    }
  }
 
  /**
   * Initialize all helper objects needed for code generation.
   */
  private initializeHelperObjects(tree: Parser.ProgramContext): void {
    const symbols = CodeGenState.symbols!;
 
    // Initialize type resolver
    this.typeResolver = new TypeResolver({
      symbols: symbols,
      symbolTable: CodeGenState.symbolTable,
      typeRegistry: CodeGenState.typeRegistry,
      resolveIdentifier: (name: string) => this.resolveIdentifier(name),
    });
 
    // Collect function/callback information
    this.collectFunctionsAndCallbacks(tree);
    this.analyzePassByValue(tree);
 
    // Initialize type validator
    this.typeValidator = new TypeValidator({
      symbols: symbols,
      symbolTable: CodeGenState.symbolTable,
      typeRegistry: CodeGenState.typeRegistry,
      typeResolver: this.typeResolver,
      callbackTypes: CodeGenState.callbackTypes,
      knownFunctions: CodeGenState.knownFunctions,
      knownGlobals: new Set(),
      getCurrentScope: () => CodeGenState.currentScope,
      getScopeMembers: () => CodeGenState.scopeMembers,
      getCurrentParameters: () => CodeGenState.currentParameters,
      getLocalVariables: () => CodeGenState.localVariables,
      resolveIdentifier: (name: string) => this.resolveIdentifier(name),
      getExpressionType: (ctx: unknown) =>
        this.getExpressionType(ctx as Parser.ExpressionContext),
    });
 
    // Initialize remaining helpers
    this.initializeAnalysisHelpers(symbols);
  }
 
  /**
   * Initialize analysis and generation helpers.
   */
  private initializeAnalysisHelpers(symbols: ICodeGenSymbols): void {
    this.stringLengthCounter = new StringLengthCounter((name: string) =>
      CodeGenState.typeRegistry.get(name),
    );
 
    this.memberChainAnalyzer = new MemberChainAnalyzer({
      typeRegistry: CodeGenState.typeRegistry,
      structFields: symbols.structFields,
      structFieldArrays: symbols.structFieldArrays,
      isKnownStruct: (name) => this.isKnownStruct(name),
      generateExpression: (ctx) => this.generateExpression(ctx),
    });
 
    this.floatBitHelper = new FloatBitHelper({
      cppMode: CodeGenState.cppMode,
      state: {
        floatBitShadows: CodeGenState.floatBitShadows,
        floatShadowCurrent: CodeGenState.floatShadowCurrent,
      },
      generateBitMask: (width, is64Bit) => this.generateBitMask(width, is64Bit),
      foldBooleanToInt: (expr) => this.foldBooleanToInt(expr),
      requireInclude: (header) => this.requireInclude(header),
    });
 
    // Create arrayInitState proxy
    const arrayInitState = {
      get lastArrayInitCount() {
        return CodeGenState.lastArrayInitCount;
      },
      set lastArrayInitCount(val: number) {
        CodeGenState.lastArrayInitCount = val;
      },
      get lastArrayFillValue() {
        return CodeGenState.lastArrayFillValue;
      },
      set lastArrayFillValue(val: string | undefined) {
        CodeGenState.lastArrayFillValue = val;
      },
    };
 
    this.stringDeclHelper = new StringDeclHelper({
      typeRegistry: CodeGenState.typeRegistry,
      getInFunctionBody: () => CodeGenState.inFunctionBody,
      getIndentLevel: () => CodeGenState.indentLevel,
      arrayInitState,
      localArrays: CodeGenState.localArrays,
      generateExpression: (ctx) => this.generateExpression(ctx),
      generateArrayDimensions: (dims) => this.generateArrayDimensions(dims),
      getStringConcatOperands: (ctx) => this._getStringConcatOperands(ctx),
      getSubstringOperands: (ctx) => this._getSubstringOperands(ctx),
      getStringLiteralLength: (literal) => StringUtils.literalLength(literal),
      getStringExprCapacity: (exprCode) => this.getStringExprCapacity(exprCode),
      requireStringInclude: () => this.requireInclude("string"),
    });
 
    this.enumValidator = new EnumAssignmentValidator({
      knownEnums: symbols.knownEnums,
      getCurrentScope: () => CodeGenState.currentScope,
      getExpressionEnumType: (ctx) => this.getExpressionEnumType(ctx),
      isIntegerExpression: (ctx) => this._isIntegerExpression(ctx),
    });
 
    this.arrayInitHelper = new ArrayInitHelper({
      typeRegistry: CodeGenState.typeRegistry,
      localArrays: CodeGenState.localArrays,
      arrayInitState: arrayInitState,
      getExpectedType: () => CodeGenState.expectedType,
      setExpectedType: (type) => {
        CodeGenState.expectedType = type;
      },
      generateExpression: (ctx) => this.generateExpression(ctx),
      getTypeName: (ctx) => this.getTypeName(ctx),
      generateArrayDimensions: (dims) => this.generateArrayDimensions(dims),
    });
 
    this.expectedTypeResolver = new AssignmentExpectedTypeResolver({
      typeRegistry: CodeGenState.typeRegistry,
      structFields: symbols.structFields,
      isKnownStruct: (name) => this.isKnownStruct(name),
    });
 
    this.assignmentValidator = new AssignmentValidator({
      typeValidator: this.typeValidator!,
      enumValidator: this.enumValidator,
      typeRegistry: CodeGenState.typeRegistry,
      floatShadowCurrent: CodeGenState.floatShadowCurrent,
      registerMemberAccess: symbols.registerMemberAccess,
      callbackFieldTypes: CodeGenState.callbackFieldTypes,
      isKnownStruct: (name) => this.isKnownStruct(name),
      isIntegerType: (name) => this._isIntegerType(name),
      getExpressionType: (ctx) => this.getExpressionType(ctx),
      tryEvaluateConstant: (ctx) => this.tryEvaluateConstant(ctx),
      isCallbackTypeUsedAsFieldType: (name) =>
        this.isCallbackTypeUsedAsFieldType(name),
    });
  }
 
  /**
   * Assemble the final generated output.
   */
  private assembleGeneratedOutput(
    tree: Parser.ProgramContext,
    options: ICodeGeneratorOptions | undefined,
  ): string {
    const output: string[] = [];
    const symbols = CodeGenState.symbols!;
    const typeValidator = this.typeValidator!;
 
    // Add header comment
    output.push(
      "/**",
      " * Generated by C-Next Transpiler",
      " * A safer C for embedded systems",
      " */",
      "",
    );
 
    // Self-include for extern "C" linkage
    if (symbols.hasPublicSymbols() && CodeGenState.sourcePath) {
      const pathToUse =
        options?.sourceRelativePath ||
        CodeGenState.sourcePath.replace(/^.*[\\/]/, "");
      const headerName = pathToUse.replace(/\.cnx$|\.cnext$/, ".h");
      output.push(`#include "${headerName}"`, "");
      CodeGenState.selfIncludeAdded = true;
    }
 
    // Process include directives
    this.processIncludeDirectives(tree, output, typeValidator);
 
    // 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[],
    typeValidator: TypeValidator,
  ): 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) {
      output.push(
        '_Static_assert(sizeof(float) == 4, "Float bit indexing requires 32-bit float");',
        '_Static_assert(sizeof(double) == 8, "Float bit indexing requires 64-bit double");',
        "",
      );
    }
 
    if (CodeGenState.needsIrqWrappers) {
      output.push(
        "// ADR-050: IRQ wrappers to avoid macro collisions with platform headers",
        "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); }",
        "",
      );
    }
 
    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
   * ADR-053 A5: Delegates to IncludeGenerator
   * Issue #349: Now passes includeDirs and inputs for angle-bracket resolution
   */
  private transformIncludeDirective(includeText: string): string {
    return includeTransformIncludeDirective(includeText, {
      sourcePath: CodeGenState.sourcePath,
      includeDirs: CodeGenState.includeDirs,
      inputs: CodeGenState.inputs,
    });
  }
 
  // 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 = `${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 {
    for (const decl of tree.declaration()) {
      // Register global variable types
      if (decl.variableDeclaration()) {
        this.registerGlobalVariableType(decl.variableDeclaration()!);
      }
 
      // Register scope member variable types
      if (decl.scopeDeclaration()) {
        this.registerScopeMemberTypes(decl.scopeDeclaration()!);
      }
 
      // Note: Function parameters are registered per-function during generation
      // since they're scoped to the function body
    }
  }
 
  /**
   * Register a global variable type and track const values.
   * SonarCloud S3776: Extracted from registerAllVariableTypes().
   */
  private registerGlobalVariableType(
    varDecl: Parser.VariableDeclarationContext,
  ): void {
    this.trackVariableType(varDecl);
 
    // Bug #8: Track const values for array size resolution at file scope
    if (varDecl.constModifier() && varDecl.expression()) {
      const constName = varDecl.IDENTIFIER().getText();
      const constValue = this.tryEvaluateConstant(varDecl.expression()!);
      if (constValue !== undefined) {
        CodeGenState.constValues.set(constName, constValue);
      }
    }
  }
 
  /**
   * Register scope member variable types.
   * SonarCloud S3776: Extracted from registerAllVariableTypes().
   */
  private registerScopeMemberTypes(
    scopeDecl: Parser.ScopeDeclarationContext,
  ): void {
    const scopeName = scopeDecl.IDENTIFIER().getText();
 
    // Set currentScope so that this.Type references resolve correctly
    const savedScope = CodeGenState.currentScope;
    this.setCurrentScope(scopeName);
 
    for (const member of scopeDecl.scopeMember()) {
      if (member.variableDeclaration()) {
        const varDecl = member.variableDeclaration()!;
        const varName = varDecl.IDENTIFIER().getText();
        const fullName = `${scopeName}_${varName}`;
        // Register with mangled name (Scope_variable)
        this.trackVariableTypeWithName(varDecl, fullName);
      }
    }
 
    // Restore previous scope
    this.setCurrentScope(savedScope);
  }
 
  // 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 for small unmodified parameters
  // ========================================================================
 
  /**
   * Analyze all functions to determine which parameters should pass by value.
   * This runs before code generation and populates passByValueParams.
   * SonarCloud S3776: Refactored to use helper methods.
   */
  private analyzePassByValue(tree: Parser.ProgramContext): void {
    // Reset analysis state
    CodeGenState.modifiedParameters.clear();
    CodeGenState.passByValueParams.clear();
    CodeGenState.functionCallGraph.clear();
    CodeGenState.functionParamLists.clear();
 
    // Phase 1: Collect function parameter lists and direct modifications
    this.collectFunctionParametersAndModifications(tree);
 
    // Issue #558: Inject cross-file data before transitive propagation
    this.injectCrossFileModifications();
    this.injectCrossFileParamLists();
 
    // Phase 2: Fixed-point iteration for transitive modifications
    TransitiveModificationPropagator.propagate(
      CodeGenState.functionCallGraph,
      CodeGenState.functionParamLists,
      CodeGenState.modifiedParameters,
    );
 
    // Phase 3: Determine which parameters can pass by value
    this.computePassByValueParams();
  }
 
  /**
   * Inject cross-file modification data into modifiedParameters.
   * SonarCloud S3776: Extracted from analyzePassByValue().
   */
  private injectCrossFileModifications(): void {
    if (!CodeGenState.pendingCrossFileModifications) return;
 
    for (const [
      funcName,
      params,
    ] of CodeGenState.pendingCrossFileModifications) {
      const existing = CodeGenState.modifiedParameters.get(funcName);
      if (existing) {
        for (const param of params) {
          existing.add(param);
        }
      } else {
        CodeGenState.modifiedParameters.set(funcName, new Set(params));
      }
    }
    CodeGenState.pendingCrossFileModifications = null; // Clear after use
  }
 
  /**
   * Inject cross-file parameter lists into functionParamLists.
   * SonarCloud S3776: Extracted from analyzePassByValue().
   */
  private injectCrossFileParamLists(): void {
    if (!CodeGenState.pendingCrossFileParamLists) return;
 
    for (const [funcName, params] of CodeGenState.pendingCrossFileParamLists) {
      if (!CodeGenState.functionParamLists.has(funcName)) {
        CodeGenState.functionParamLists.set(funcName, [...params]);
      }
    }
    CodeGenState.pendingCrossFileParamLists = null; // Clear after use
  }
 
  /**
   * Phase 1: Walk all functions to collect:
   * - Parameter lists (for call graph resolution)
   * - Direct modifications (param <- value)
   * - Function calls where params are passed as arguments
   */
  private collectFunctionParametersAndModifications(
    tree: Parser.ProgramContext,
  ): void {
    for (const decl of tree.declaration()) {
      // Handle scope-level functions
      if (decl.scopeDeclaration()) {
        const scopeDecl = decl.scopeDeclaration()!;
        const scopeName = scopeDecl.IDENTIFIER().getText();
 
        for (const member of scopeDecl.scopeMember()) {
          if (member.functionDeclaration()) {
            const funcDecl = member.functionDeclaration()!;
            const funcName = funcDecl.IDENTIFIER().getText();
            const fullName = `${scopeName}_${funcName}`;
            this.analyzeFunctionForModifications(fullName, funcDecl);
          }
        }
      }
 
      // Handle top-level functions
      if (decl.functionDeclaration()) {
        const funcDecl = decl.functionDeclaration()!;
        const name = funcDecl.IDENTIFIER().getText();
        this.analyzeFunctionForModifications(name, funcDecl);
      }
    }
  }
 
  /**
   * Analyze a single function for parameter modifications and call graph edges.
   */
  private analyzeFunctionForModifications(
    funcName: string,
    funcDecl: Parser.FunctionDeclarationContext,
  ): void {
    // Collect parameter names
    const paramNames: string[] = [];
    const paramList = funcDecl.parameterList();
    if (paramList) {
      for (const param of paramList.parameter()) {
        paramNames.push(param.IDENTIFIER().getText());
      }
    }
    CodeGenState.functionParamLists.set(funcName, paramNames);
 
    // Initialize modified set
    CodeGenState.modifiedParameters.set(funcName, new Set());
    // Issue #579: Initialize subscript access tracking
    CodeGenState.subscriptAccessedParameters.set(funcName, new Set());
    CodeGenState.functionCallGraph.set(funcName, []);
 
    // Walk the function body to find modifications and calls
    const block = funcDecl.block();
    Eif (block) {
      this.walkBlockForModifications(funcName, paramNames, block);
    }
  }
 
  /**
   * Walk a block to find parameter modifications and function calls.
   */
  private walkBlockForModifications(
    funcName: string,
    paramNames: string[],
    block: Parser.BlockContext,
  ): void {
    const paramSet = new Set(paramNames);
 
    for (const stmt of block.statement()) {
      this.walkStatementForModifications(funcName, paramSet, stmt);
    }
  }
 
  /**
   * Walk a statement recursively looking for modifications and calls.
   * Issue #566: Refactored to use helper methods for expression and child collection.
   */
  private walkStatementForModifications(
    funcName: string,
    paramSet: Set<string>,
    stmt: Parser.StatementContext,
  ): void {
    // 1. Check for parameter modifications via assignment targets
    if (stmt.assignmentStatement()) {
      this.trackAssignmentModifications(funcName, paramSet, stmt);
    }
 
    // 2. Walk all expressions in this statement for function calls and subscript access
    for (const expr of StatementExpressionCollector.collectAll(stmt)) {
      this.walkExpressionForCalls(funcName, paramSet, expr);
      // Issue #579: Also track subscript read access on parameters
      this.walkExpressionForSubscriptAccess(funcName, paramSet, expr);
    }
 
    // 3. Recurse into child statements and blocks
    const { statements, blocks } = ChildStatementCollector.collectAll(stmt);
    for (const childStmt of statements) {
      this.walkStatementForModifications(funcName, paramSet, childStmt);
    }
    for (const block of blocks) {
      this.walkBlockForModifications(funcName, [...paramSet], block);
    }
  }
 
  /**
   * Track assignment modifications for parameter const inference.
   * SonarCloud S3776: Extracted from walkStatementForModifications().
   */
  private trackAssignmentModifications(
    funcName: string,
    paramSet: Set<string>,
    stmt: Parser.StatementContext,
  ): void {
    const assign = stmt.assignmentStatement()!;
    const target = assign.assignmentTarget();
 
    const { baseIdentifier, hasSingleIndexSubscript } =
      AssignmentTargetExtractor.extract(target);
 
    // Issue #579: Track subscript access on parameters (for write path)
    if (
      hasSingleIndexSubscript &&
      baseIdentifier &&
      paramSet.has(baseIdentifier)
    ) {
      CodeGenState.subscriptAccessedParameters
        .get(funcName)!
        .add(baseIdentifier);
    }
 
    // Track as modified parameter
    if (baseIdentifier && paramSet.has(baseIdentifier)) {
      CodeGenState.modifiedParameters.get(funcName)!.add(baseIdentifier);
    }
  }
 
  /**
   * Walk an expression tree to find function calls where parameters are passed.
   * Uses recursive descent through the expression hierarchy.
   */
  private walkExpressionForCalls(
    funcName: string,
    paramSet: Set<string>,
    expr: Parser.ExpressionContext,
  ): void {
    // Expression -> TernaryExpression -> OrExpression -> ... -> PostfixExpression
    const ternary = expr.ternaryExpression();
    Eif (ternary) {
      // Walk all orExpression children
      for (const orExpr of ternary.orExpression()) {
        this.walkOrExpressionForCalls(funcName, paramSet, orExpr);
      }
    }
  }
 
  /**
   * Issue #579: Walk an expression tree to find subscript access on parameters.
   * This tracks read access like `buf[i]` where buf is a parameter.
   * Parameters with subscript access must become pointers.
   */
  private walkExpressionForSubscriptAccess(
    funcName: string,
    paramSet: Set<string>,
    expr: Parser.ExpressionContext,
  ): void {
    const ternary = expr.ternaryExpression();
    Eif (ternary) {
      for (const orExpr of ternary.orExpression()) {
        this.walkOrExpression(orExpr, (unaryExpr) => {
          this.handleSubscriptAccess(funcName, paramSet, unaryExpr);
        });
      }
    }
  }
 
  /**
   * Issue #579: Handle subscript access on a unary expression.
   * Only tracks single-index subscript access (which could be array access).
   * Two-index subscript (e.g., value[start, width]) is always bit extraction,
   * so it doesn't require the parameter to become a pointer.
   */
  private handleSubscriptAccess(
    funcName: string,
    paramSet: Set<string>,
    unaryExpr: Parser.UnaryExpressionContext,
  ): void {
    const postfixExpr = unaryExpr.postfixExpression();
    if (!postfixExpr) return;
 
    const primary = postfixExpr.primaryExpression();
    const ops = postfixExpr.postfixOp();
 
    // Check if primary is a parameter and there's subscript access
    const primaryId = primary.IDENTIFIER()?.getText();
    if (!primaryId || !paramSet.has(primaryId)) {
      return;
    }
 
    // Only track SINGLE-index subscript access (potential array access)
    // Two-index subscript like value[0, 8] is bit extraction, not array access
    const hasSingleIndexSubscript = ops.some(
      (op) => op.expression().length === 1,
    );
    if (hasSingleIndexSubscript) {
      CodeGenState.subscriptAccessedParameters.get(funcName)!.add(primaryId);
    }
  }
 
  /**
   * Generic walker for orExpression trees.
   * Walks through the expression hierarchy and calls the handler for each unaryExpression.
   * Used by both function call tracking and subscript access tracking.
   */
  private walkOrExpression(
    orExpr: Parser.OrExpressionContext,
    handler: (unaryExpr: Parser.UnaryExpressionContext) => void,
  ): void {
    orExpr
      .andExpression()
      .flatMap((and) => and.equalityExpression())
      .flatMap((eq) => eq.relationalExpression())
      .flatMap((rel) => rel.bitwiseOrExpression())
      .flatMap((bor) => bor.bitwiseXorExpression())
      .flatMap((bxor) => bxor.bitwiseAndExpression())
      .flatMap((band) => band.shiftExpression())
      .flatMap((shift) => shift.additiveExpression())
      .flatMap((add) => add.multiplicativeExpression())
      .flatMap((mul) => mul.unaryExpression())
      .forEach(handler);
  }
 
  /**
   * Walk an orExpression tree for function calls.
   */
  private walkOrExpressionForCalls(
    funcName: string,
    paramSet: Set<string>,
    orExpr: Parser.OrExpressionContext,
  ): void {
    this.walkOrExpression(orExpr, (unaryExpr) => {
      this.walkUnaryExpressionForCalls(funcName, paramSet, unaryExpr);
    });
  }
 
  /**
   * Walk a unaryExpression tree for function calls.
   */
  private walkUnaryExpressionForCalls(
    funcName: string,
    paramSet: Set<string>,
    unaryExpr: Parser.UnaryExpressionContext,
  ): void {
    // Recurse into nested unary
    if (unaryExpr.unaryExpression()) {
      this.walkUnaryExpressionForCalls(
        funcName,
        paramSet,
        unaryExpr.unaryExpression()!,
      );
      return;
    }
 
    // Check postfix expression
    const postfix = unaryExpr.postfixExpression();
    Eif (postfix) {
      this.walkPostfixExpressionForCalls(funcName, paramSet, postfix);
    }
  }
 
  /**
   * Walk a postfixExpression for function calls.
   * This is where function calls are found: primaryExpr followed by '(' args ')'
   */
  private walkPostfixExpressionForCalls(
    funcName: string,
    paramSet: Set<string>,
    postfix: Parser.PostfixExpressionContext,
  ): void {
    const primary = postfix.primaryExpression();
    const postfixOps = postfix.postfixOp();
 
    // Handle simple function calls: IDENTIFIER followed by '(' ... ')'
    this.handleSimpleFunctionCall(funcName, paramSet, primary, postfixOps);
 
    // Issue #365: Handle scope-qualified calls: Scope.method(...) or global.Scope.method(...)
    this.handleScopeQualifiedCalls(funcName, paramSet, primary, postfixOps);
 
    // Recurse into primary expression if it's a parenthesized expression
    if (primary.expression()) {
      this.walkExpressionForCalls(funcName, paramSet, primary.expression()!);
    }
 
    // Walk arguments in any postfix function call ops (for nested calls)
    this.walkPostfixOpsRecursively(funcName, paramSet, postfixOps);
  }
 
  /**
   * Handle simple function calls: IDENTIFIER followed by '(' ... ')'
   */
  private handleSimpleFunctionCall(
    funcName: string,
    paramSet: Set<string>,
    primary: Parser.PrimaryExpressionContext,
    postfixOps: Parser.PostfixOpContext[],
  ): void {
    if (!primary.IDENTIFIER() || postfixOps.length === 0) return;
 
    const firstOp = postfixOps[0];
    if (!firstOp.LPAREN()) return;
 
    const calleeName = primary.IDENTIFIER()!.getText();
    this.recordCallsFromArgList(funcName, paramSet, calleeName, firstOp);
  }
 
  /**
   * Handle scope-qualified calls: Scope.method(...) or global.Scope.method(...)
   * Track member accesses to build the mangled callee name (e.g., Storage_load)
   */
  private handleScopeQualifiedCalls(
    funcName: string,
    paramSet: Set<string>,
    primary: Parser.PrimaryExpressionContext,
    postfixOps: Parser.PostfixOpContext[],
  ): void {
    if (postfixOps.length === 0) return;
 
    const memberNames = this.collectInitialMemberNames(funcName, primary);
 
    for (const op of postfixOps) {
      if (op.IDENTIFIER()) {
        memberNames.push(op.IDENTIFIER()!.getText());
      } else if (op.LPAREN() && memberNames.length >= 1) {
        const calleeName = memberNames.join("_");
        this.recordCallsFromArgList(funcName, paramSet, calleeName, op);
        memberNames.length = 0; // Reset for potential chained calls
      E} else if (op.expression().length > 0) {
        memberNames.length = 0; // Array subscript breaks scope chain
      }
    }
  }
 
  /**
   * Collect initial member names from primary expression for scope resolution.
   * Issue #561: When 'this' is used, resolve to the current scope name from funcName.
   */
  private collectInitialMemberNames(
    funcName: string,
    primary: Parser.PrimaryExpressionContext,
  ): string[] {
    const memberNames: string[] = [];
    const primaryId = primary.IDENTIFIER()?.getText();
 
    if (primaryId && primaryId !== "global") {
      memberNames.push(primaryId);
    } else if (primary.THIS()) {
      const scopeName = funcName.split("_")[0];
      if (scopeName && scopeName !== funcName) {
        memberNames.push(scopeName);
      }
    }
    return memberNames;
  }
 
  /**
   * Record function calls to the call graph from an argument list.
   * Also recurses into argument expressions.
   */
  private recordCallsFromArgList(
    funcName: string,
    paramSet: Set<string>,
    calleeName: string,
    op: Parser.PostfixOpContext,
  ): void {
    const argList = op.argumentList();
    if (!argList) return;
 
    const args = argList.expression();
    for (let i = 0; i < args.length; i++) {
      const arg = args[i];
      const argName = ExpressionUtils.extractIdentifier(arg);
      if (argName && paramSet.has(argName)) {
        CodeGenState.functionCallGraph.get(funcName)!.push({
          callee: calleeName,
          paramIndex: i,
          argParamName: argName,
        });
      }
      this.walkExpressionForCalls(funcName, paramSet, arg);
    }
  }
 
  /**
   * Walk postfix ops recursively for nested calls and array subscripts.
   */
  private walkPostfixOpsRecursively(
    funcName: string,
    paramSet: Set<string>,
    postfixOps: Parser.PostfixOpContext[],
  ): void {
    for (const op of postfixOps) {
      if (op.argumentList()) {
        for (const argExpr of op.argumentList()!.expression()) {
          this.walkExpressionForCalls(funcName, paramSet, argExpr);
        }
      }
      for (const expr of op.expression()) {
        this.walkExpressionForCalls(funcName, paramSet, expr);
      }
    }
  }
 
  /**
   * Phase 3: Determine which parameters can pass by value.
   * A parameter passes by value if:
   * 1. It's a small primitive type (u8, i8, u16, i16, u32, i32, u64, i64, bool)
   * 2. It's not modified (directly or transitively)
   * 3. It's not an array, struct, string, or callback
   */
  private computePassByValueParams(): void {
    const smallPrimitives = new Set([
      "u8",
      "i8",
      "u16",
      "i16",
      "u32",
      "i32",
      "u64",
      "i64",
      "bool",
    ]);
 
    for (const [funcName, paramNames] of CodeGenState.functionParamLists) {
      const passByValue = new Set<string>();
      const modified =
        CodeGenState.modifiedParameters.get(funcName) ?? new Set();
 
      // Get function declaration to check parameter types
      const funcSig = CodeGenState.functionSignatures.get(funcName);
      if (funcSig) {
        for (let i = 0; i < paramNames.length; i++) {
          const paramName = paramNames[i];
          const paramSig = funcSig.parameters[i];
 
          Iif (!paramSig) continue;
 
          // Check if eligible for pass-by-value:
          // - Is a small primitive type
          // - Not an array
          // - Not modified
          // - Not accessed via subscript (Issue #579)
          const isSmallPrimitive = smallPrimitives.has(paramSig.baseType);
          const isArray = paramSig.isArray ?? false;
          const isModified = modified.has(paramName);
          // Issue #579: Parameters with subscript access must become pointers
          const hasSubscriptAccess =
            CodeGenState.subscriptAccessedParameters
              .get(funcName)
              ?.has(paramName) ?? false;
 
          if (
            isSmallPrimitive &&
            !isArray &&
            !isModified &&
            !hasSubscriptAccess
          ) {
            passByValue.add(paramName);
          }
        }
      }
 
      CodeGenState.passByValueParams.set(funcName, passByValue);
    }
  }
 
  /**
   * Check if a parameter should be passed by value (by name).
   * Used internally during code generation.
   */
  private _isParameterPassByValueByName(
    funcName: string,
    paramName: string,
  ): boolean {
    const passByValue = CodeGenState.passByValueParams.get(funcName);
    return passByValue?.has(paramName) ?? false;
  }
 
  /**
   * Issue #269: Check if a parameter should be passed by value (by index).
   * Part of IOrchestrator interface - used by CallExprGenerator.
   */
  isParameterPassByValue(funcName: string, paramIndex: number): boolean {
    const paramList = CodeGenState.functionParamLists.get(funcName);
    Iif (!paramList || paramIndex < 0 || paramIndex >= paramList.length) {
      return false;
    }
    const paramName = paramList[paramIndex];
    return this._isParameterPassByValueByName(funcName, paramName);
  }
 
  /**
   * 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;
  }
 
  /**
   * ADR-036: Try to evaluate an expression as a compile-time constant.
   * Returns the numeric value if constant, undefined if not evaluable.
   * Bug #8: Extended to resolve const variable references for file-scope array sizes.
   * Issue #644: Delegates to ArrayDimensionParser for consolidated implementation.
   */
  // Issue #63: checkArrayBounds moved to TypeValidator
 
  /**
   * Evaluate array dimensions from ArrayDimensionContext[] to number[].
   * Used for bitmap array registration.
   * Issue #644: Delegates to ArrayDimensionParser for consolidated implementation.
   */
  private _evaluateArrayDimensions(
    arrayDim: Parser.ArrayDimensionContext[] | null,
  ): number[] | undefined {
    return ArrayDimensionParser.parseAllDimensions(arrayDim, {
      constValues: CodeGenState.constValues,
      typeWidths: TYPE_WIDTH,
      isKnownStruct: (name) => this.isKnownStruct(name),
    });
  }
 
  /**
   * Try to register a type as enum or bitmap. Returns true if handled.
   * Extracted to reduce duplication across type contexts (ADR-017, ADR-034).
   */
  private _tryRegisterEnumOrBitmapType(
    name: string,
    baseType: string,
    isConst: boolean,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
  ): boolean {
    // Common options for type registration
    const registrationOptions = {
      name,
      baseType,
      isConst,
      overflowBehavior,
      isAtomic,
    };
 
    // ADR-017: Check if this is an enum type
    if (
      TypeRegistrationUtils.tryRegisterEnumType(
        CodeGenState.typeRegistry,
        CodeGenState.symbols!,
        registrationOptions,
      )
    ) {
      return true;
    }
 
    // ADR-034: Check if this is a bitmap type
    const bitmapDimensions = this._evaluateArrayDimensions(arrayDim);
    if (
      TypeRegistrationUtils.tryRegisterBitmapType(
        CodeGenState.typeRegistry,
        CodeGenState.symbols!,
        registrationOptions,
        bitmapDimensions,
      )
    ) {
      return true;
    }
 
    return false;
  }
 
  /**
   * Extract type info from a variable declaration and register it.
   * Delegates to trackVariableTypeWithName using the variable's identifier.
   */
  private trackVariableType(varDecl: Parser.VariableDeclarationContext): void {
    const name = varDecl.IDENTIFIER().getText();
    this.trackVariableTypeWithName(varDecl, name);
  }
 
  // =========================================================================
  // Type Registration Helpers - Extracted to reduce cognitive complexity
  // =========================================================================
 
  /**
   * Extract array dimensions from ArrayDimensionContext array (simple parseInt version)
   * Used for string array dimensions where const evaluation is not needed.
   * Issue #644: Delegates to ArrayDimensionParser for consolidated implementation.
   */
  private extractArrayDimensionsSimple(
    arrayDim: Parser.ArrayDimensionContext[] | null,
  ): number[] {
    return ArrayDimensionParser.parseSimpleDimensions(arrayDim);
  }
 
  /**
   * Register a string type in the type registry
   * Returns true if registration was successful
   */
  private tryRegisterStringType(
    registryName: string,
    typeCtx: Parser.TypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
  ): boolean {
    const stringCtx = typeCtx.stringType();
    if (!stringCtx) {
      return false;
    }
 
    const intLiteral = stringCtx.INTEGER_LITERAL();
    if (!intLiteral) {
      return false;
    }
 
    const capacity = Number.parseInt(intLiteral.getText(), 10);
    this.requireInclude("string");
    const stringDim = capacity + 1;
 
    // Check if there are additional array dimensions (e.g., [4] in string<64> arr[4])
    const additionalDims = this.extractArrayDimensionsSimple(arrayDim);
    const allDims =
      additionalDims.length > 0 ? [...additionalDims, stringDim] : [stringDim];
 
    CodeGenState.typeRegistry.set(registryName, {
      baseType: "char",
      bitWidth: 8,
      isArray: true,
      arrayDimensions: allDims,
      isConst,
      isString: true,
      stringCapacity: capacity,
      overflowBehavior,
      isAtomic,
    });
    return true;
  }
 
  /**
   * Resolve base type name from a type context
   * Handles scoped, global, qualified, and user types
   */
  private resolveBaseTypeFromContext(
    typeCtx: Parser.TypeContext,
  ): string | null {
    if (typeCtx.primitiveType()) {
      return typeCtx.primitiveType()!.getText();
    }
 
    if (typeCtx.scopedType()) {
      // ADR-016: Handle this.Type for scoped types (e.g., this.State -> Motor_State)
      const typeName = typeCtx.scopedType()!.IDENTIFIER().getText();
      return CodeGenState.currentScope
        ? `${CodeGenState.currentScope}_${typeName}`
        : typeName;
    }
 
    if (typeCtx.globalType()) {
      // Issue #478: Handle global.Type for global types inside scope
      return typeCtx.globalType()!.IDENTIFIER().getText();
    }
 
    if (typeCtx.qualifiedType()) {
      // ADR-016: Handle Scope.Type from outside scope
      // Issue #388: Also handles C++ namespace types
      const identifiers = typeCtx.qualifiedType()!.IDENTIFIER();
      const identifierNames = identifiers.map((id) => id.getText());
      return this.resolveQualifiedType(identifierNames);
    }
 
    if (typeCtx.userType()) {
      return typeCtx.userType()!.getText();
    }
 
    return null;
  }
 
  /**
   * Track variable type with a specific name (for namespace/class members)
   * This allows tracking with mangled names for proper scope resolution
   */
  private trackVariableTypeWithName(
    varDecl: Parser.VariableDeclarationContext,
    registryName: string,
  ): void {
    const typeCtx = varDecl.type();
    const arrayDim = varDecl.arrayDimension();
    const isConst = varDecl.constModifier() !== null;
 
    // ADR-044: Extract overflow modifier (clamp is default)
    const overflowMod = varDecl.overflowModifier();
    const overflowBehavior: TOverflowBehavior =
      overflowMod?.getText() === "wrap" ? "wrap" : "clamp";
 
    // ADR-049: Extract atomic modifier
    const isAtomic = varDecl.atomicModifier() !== null;
 
    // ADR-045: Handle bounded string type first (special case)
    if (
      this.tryRegisterStringType(
        registryName,
        typeCtx,
        arrayDim,
        isConst,
        overflowBehavior,
        isAtomic,
      )
    ) {
      return;
    }
 
    // Handle array type syntax: u8[10]
    Iif (typeCtx.arrayType()) {
      this._registerArrayTypeVariable(
        registryName,
        typeCtx.arrayType()!,
        arrayDim,
        isConst,
        overflowBehavior,
        isAtomic,
      );
      return;
    }
 
    // Resolve base type from context (handles scoped, global, qualified, user types)
    const baseType = this.resolveBaseTypeFromContext(typeCtx);
    if (!baseType) {
      return;
    }
 
    // ADR-017/ADR-034: Check if enum or bitmap type (reuse existing helper)
    if (
      this._tryRegisterEnumOrBitmapType(
        registryName,
        baseType,
        isConst,
        arrayDim,
        overflowBehavior,
        isAtomic,
      )
    ) {
      return;
    }
 
    // Standard type registration
    this._registerStandardType(
      registryName,
      baseType,
      arrayDim,
      isConst,
      overflowBehavior,
      isAtomic,
    );
  }
 
  /**
   * Register an array type variable (u8[10] syntax)
   */
  private _registerArrayTypeVariable(
    registryName: string,
    arrayTypeCtx: Parser.ArrayTypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
  ): void {
    let baseType = "";
    let bitWidth = 0;
 
    if (arrayTypeCtx.primitiveType()) {
      baseType = arrayTypeCtx.primitiveType()!.getText();
      bitWidth = TYPE_WIDTH[baseType] || 0;
    }
 
    if (!baseType) {
      return;
    }
 
    const arrayDimensions = this._collectArrayDimensions(
      arrayTypeCtx,
      arrayDim,
    );
 
    CodeGenState.typeRegistry.set(registryName, {
      baseType,
      bitWidth,
      isArray: true,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      isConst,
      overflowBehavior,
      isAtomic,
    });
  }
 
  /**
   * Collect array dimensions from array type and additional dimensions
   */
  private _collectArrayDimensions(
    arrayTypeCtx: Parser.ArrayTypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
  ): number[] {
    const arrayDimensions: number[] = [];
 
    // Get dimension from array type syntax
    const sizeExpr = arrayTypeCtx.expression();
    if (sizeExpr) {
      const size = Number.parseInt(sizeExpr.getText(), 10);
      if (!Number.isNaN(size)) {
        arrayDimensions.push(size);
      }
    }
 
    // Add additional dimensions using const evaluation
    const additionalDims = this._evaluateArrayDimensions(arrayDim);
    if (additionalDims) {
      arrayDimensions.push(...additionalDims);
    }
 
    return arrayDimensions;
  }
 
  /**
   * Register a standard (non-array-syntax, non-special) type
   */
  private _registerStandardType(
    registryName: string,
    baseType: string,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
  ): void {
    const bitWidth = TYPE_WIDTH[baseType] || 0;
    // Issue #665: Check array syntax presence first, then try to resolve dimensions
    // This matches the pattern in trackVariableType() - unresolved dimensions (e.g., enum
    // members like EIndex.COUNT) should still mark the variable as an array
    const isArray = arrayDim !== null && arrayDim.length > 0;
    const arrayDimensions = isArray
      ? this._evaluateArrayDimensions(arrayDim)
      : undefined;
 
    CodeGenState.typeRegistry.set(registryName, {
      baseType,
      bitWidth,
      isArray,
      arrayDimensions: isArray ? arrayDimensions : undefined,
      isConst,
      overflowBehavior,
      isAtomic,
    });
  }
 
  /**
   * Issue #322: Check if a type name is a user-defined struct
   * Part of IOrchestrator interface.
   */
  isStructType(typeName: string): boolean {
    return this.typeResolver!.isStructType(typeName);
  }
 
  /**
   * Set up parameter tracking for a function
   */
  private _setParameters(params: Parser.ParameterListContext | null): void {
    CodeGenState.currentParameters.clear();
    CodeGenState.currentParameters.clear();
    if (!params) return;
 
    for (const param of params.parameter()) {
      this._processParameter(param);
    }
  }
 
  /**
   * Process a single parameter declaration
   */
  private _processParameter(param: Parser.ParameterContext): void {
    const name = param.IDENTIFIER().getText();
    const isArray = param.arrayDimension().length > 0;
    const isConst = param.constModifier() !== null;
    const typeCtx = param.type();
 
    // Resolve type information
    const typeInfo = this._resolveParameterTypeInfo(typeCtx);
 
    // Register in currentParameters
    const paramInfo = {
      name,
      baseType: typeInfo.typeName,
      isArray,
      isStruct: typeInfo.isStruct,
      isConst,
      isCallback: typeInfo.isCallback,
      isString: typeInfo.isString,
    };
    CodeGenState.currentParameters.set(name, paramInfo);
 
    // Register in typeRegistry
    this._registerParameterType(name, typeInfo, param, isArray, isConst);
  }
 
  /**
   * Resolve type name and flags from a type context
   */
  private _resolveParameterTypeInfo(typeCtx: Parser.TypeContext): {
    typeName: string;
    isStruct: boolean;
    isCallback: boolean;
    isString: boolean;
  } {
    if (typeCtx.primitiveType()) {
      return {
        typeName: typeCtx.primitiveType()!.getText(),
        isStruct: false,
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.userType()) {
      const typeName = typeCtx.userType()!.getText();
      return {
        typeName,
        isStruct: this.isStructType(typeName),
        isCallback: CodeGenState.callbackTypes.has(typeName),
        isString: false,
      };
    }
 
    if (typeCtx.qualifiedType()) {
      const identifierNames = typeCtx
        .qualifiedType()!
        .IDENTIFIER()
        .map((id) => id.getText());
      const typeName = this.resolveQualifiedType(identifierNames);
      return {
        typeName,
        isStruct: this.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.scopedType()) {
      const localTypeName = typeCtx.scopedType()!.IDENTIFIER().getText();
      const typeName = CodeGenState.currentScope
        ? `${CodeGenState.currentScope}_${localTypeName}`
        : localTypeName;
      return {
        typeName,
        isStruct: this.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.globalType()) {
      const typeName = typeCtx.globalType()!.IDENTIFIER().getText();
      return {
        typeName,
        isStruct: this.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    Eif (typeCtx.stringType()) {
      return {
        typeName: "string",
        isStruct: false,
        isCallback: false,
        isString: true,
      };
    }
 
    // Fallback
    return {
      typeName: typeCtx.getText(),
      isStruct: false,
      isCallback: false,
      isString: false,
    };
  }
 
  /**
   * Register a parameter in the type registry
   */
  private _registerParameterType(
    name: string,
    typeInfo: { typeName: string; isString: boolean },
    param: Parser.ParameterContext,
    isArray: boolean,
    isConst: boolean,
  ): void {
    const { typeName, isString } = typeInfo;
    const typeCtx = param.type();
 
    const isEnum = CodeGenState.symbols!.knownEnums.has(typeName);
    const isBitmap = CodeGenState.symbols!.knownBitmaps.has(typeName);
 
    // Extract array dimensions
    const arrayDimensions = isArray
      ? ArrayDimensionParser.parseForParameters(param.arrayDimension())
      : [];
 
    // Get string capacity if applicable
    const stringCapacity = this._getStringCapacity(typeCtx, isString);
    if (isArray && stringCapacity !== undefined) {
      arrayDimensions.push(stringCapacity + 1);
    }
 
    const registeredType = {
      baseType: typeName,
      bitWidth: isBitmap
        ? CodeGenState.symbols!.bitmapBitWidth.get(typeName) || 0
        : TYPE_WIDTH[typeName] || 0,
      isArray,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      isConst,
      isEnum,
      enumTypeName: isEnum ? typeName : undefined,
      isBitmap,
      bitmapTypeName: isBitmap ? typeName : undefined,
      isString,
      stringCapacity,
      isParameter: true,
    };
    CodeGenState.typeRegistry.set(name, registeredType);
  }
 
  /**
   * Extract string capacity from a string type context
   */
  private _getStringCapacity(
    typeCtx: Parser.TypeContext,
    isString: boolean,
  ): number | undefined {
    if (!isString || !typeCtx.stringType()) return undefined;
    const intLiteral = typeCtx.stringType()!.INTEGER_LITERAL();
    Iif (!intLiteral) return undefined;
    return Number.parseInt(intLiteral.getText(), 10);
  }
 
  /**
   * Clear parameter tracking when leaving a function
   */
  private _clearParameters(): void {
    // ADR-025: Remove parameter types from typeRegistry
    for (const name of CodeGenState.currentParameters.keys()) {
      CodeGenState.typeRegistry.delete(name);
      CodeGenState.typeRegistry.delete(name);
    }
    CodeGenState.currentParameters.clear();
    CodeGenState.localArrays.clear();
    CodeGenState.currentParameters.clear();
    CodeGenState.localArrays.clear();
  }
 
  /**
   * 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
        const isArray = param.arrayDimension().length > 0;
        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 isArray = dims.length > 0;
 
        // 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;
        }
 
        const arrayDims = isArray
          ? dims.map((d) => this.generateArrayDimension(d)).join("")
          : "";
        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 {
    const text = ctx.getText();
 
    // Check for integer literals
    if (
      /^-?\d+$/.exec(text) ||
      /^0[xX][0-9a-fA-F]+$/.exec(text) ||
      /^0[bB][01]+$/.exec(text)
    ) {
      return true;
    }
 
    // Check if it's a variable of primitive integer type
    if (/^[a-zA-Z_]\w*$/.exec(text)) {
      const typeInfo = CodeGenState.typeRegistry.get(text);
      if (
        typeInfo &&
        !typeInfo.isEnum &&
        TypeCheckUtils.isInteger(typeInfo.baseType)
      ) {
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * ADR-045: Check if an expression is a string concatenation (contains + with string operands).
   * Returns the operand expressions if it is, null otherwise.
   */
  private _getStringConcatOperands(ctx: Parser.ExpressionContext): {
    left: string;
    right: string;
    leftCapacity: number;
    rightCapacity: number;
  } | null {
    // Navigate to the additive expression level using ExpressionUnwrapper
    // Issue #707: Deduplicated expression tree navigation
    const add = ExpressionUnwrapper.getAdditiveExpression(ctx);
    Iif (!add) return null;
    const multExprs = add.multiplicativeExpression();
 
    // Need exactly 2 operands for simple concatenation
    if (multExprs.length !== 2) return null;
 
    // Check if this is addition (not subtraction)
    const text = add.getText();
    Iif (text.includes("-")) return null;
 
    // Get the operand texts
    const leftText = multExprs[0].getText();
    const rightText = multExprs[1].getText();
 
    // Check if at least one operand is a string
    const leftCapacity = this.getStringExprCapacity(leftText);
    const rightCapacity = this.getStringExprCapacity(rightText);
 
    Iif (leftCapacity === null && rightCapacity === null) {
      return null; // Neither is a string
    }
 
    // If one is null, it's not a valid string concatenation
    Iif (leftCapacity === null || rightCapacity === null) {
      return null;
    }
 
    return {
      left: leftText,
      right: rightText,
      leftCapacity,
      rightCapacity,
    };
  }
 
  /**
   * ADR-045: Get the capacity of a string expression.
   * For string literals, capacity is the literal length.
   * For string variables, capacity is from the type registry.
   */
  /**
   * ADR-045: Check if an expression is a substring extraction (string[start, length]).
   * Returns the source string, start, length, and source capacity if it is.
   * Issue #707: Uses ExpressionUnwrapper for tree navigation.
   */
  private _getSubstringOperands(ctx: Parser.ExpressionContext): {
    source: string;
    start: string;
    length: string;
    sourceCapacity: number;
  } | null {
    // Navigate to the postfix expression level using shared utility
    const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
    Iif (!postfix) return null;
 
    const primary = postfix.primaryExpression();
    const ops = postfix.postfixOp();
 
    // Need exactly one postfix operation (the [start, length])
    if (ops.length !== 1) return null;
 
    const op = ops[0];
    const exprs = op.expression();
 
    // Get the source variable name first
    const sourceId = primary.IDENTIFIER();
    Iif (!sourceId) return null;
 
    const sourceName = sourceId.getText();
 
    // Check if source is a string type
    const typeInfo = CodeGenState.typeRegistry.get(sourceName);
    Iif (!typeInfo?.isString || typeInfo.stringCapacity === undefined) {
      return null;
    }
 
    // Issue #140: Handle both [start, length] pattern (2 expressions)
    // and single-character access [index] pattern (1 expression, treated as [index, 1])
    if (exprs.length === 2) {
      return {
        source: sourceName,
        start: this.generateExpression(exprs[0]),
        length: this.generateExpression(exprs[1]),
        sourceCapacity: typeInfo.stringCapacity,
      };
    E} else if (exprs.length === 1) {
      // Single-character access: source[i] is sugar for source[i, 1]
      return {
        source: sourceName,
        start: this.generateExpression(exprs[0]),
        length: "1",
        sourceCapacity: typeInfo.stringCapacity,
      };
    }
 
    return null;
  }
 
  // ========================================================================
  // 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 this.typeResolver!.isIntegerType(typeName);
  }
 
  private _isFloatType(typeName: string): boolean {
    return this.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 this.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 this.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 {
    this.typeResolver!.validateLiteralFitsType(literalText, targetType);
  }
 
  /**
   * ADR-024: Get the type of a unary expression (for cast validation).
   */
  private getUnaryExpressionType(
    ctx: Parser.UnaryExpressionContext,
  ): string | null {
    return this.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 {
    this.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 {
    Eif (!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();
    Iif (!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.typeRegistry.get(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);
    if (!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();
    if (!baseId) return false;
 
    const typeInfo = CodeGenState.typeRegistry.get(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.typeRegistry.get(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
    Iif (!memberInfo) {
      return "unknown";
    }
 
    return memberInfo.isArray ? "array" : "not-array";
  }
 
  /**
   * Generate a function argument with proper ADR-006 semantics.
   * - Local variables get & (address-of)
   * - Member access (cursor.x) gets & (address-of)
   * - Array access (arr[i]) gets & (address-of)
   * - Parameters are passed as-is (already pointers)
   * - Arrays are passed as-is (naturally decay to pointers)
   * - Literals use compound literals for pointer params: &(type){value}
   * - Complex expressions are passed as-is
   */
  private _generateFunctionArg(
    ctx: Parser.ExpressionContext,
    targetParamBaseType?: string,
  ): string {
    const id = CodegenParserUtils.getSimpleIdentifier(ctx);
    if (id) {
      return this._handleIdentifierArg(id);
    }
 
    const lvalueType = this.getLvalueType(ctx);
    Eif (lvalueType) {
      return this._handleLvalueArg(ctx, lvalueType, targetParamBaseType);
    }
 
    return this._handleRvalueArg(ctx, targetParamBaseType);
  }
 
  /**
   * Handle simple identifier argument (parameter, local array, scope member, or variable)
   */
  private _handleIdentifierArg(id: string): string {
    // Parameters are already pointers
    if (CodeGenState.currentParameters.get(id)) {
      return id;
    }
 
    // Local arrays decay to pointers
    if (CodeGenState.localArrays.has(id)) {
      return id;
    }
 
    // Global arrays also decay to pointers (check typeRegistry)
    // But NOT strings - strings need & (they're char arrays but passed by reference)
    const typeInfo = CodeGenState.typeRegistry.get(id);
    if (typeInfo?.isArray && !typeInfo.isString) {
      return id;
    }
 
    // Scope member - may need prefixing
    Iif (CodeGenState.currentScope) {
      const members = CodeGenState.scopeMembers.get(CodeGenState.currentScope);
      if (members?.has(id)) {
        const scopedName = `${CodeGenState.currentScope}_${id}`;
        return this.cppHelper!.maybeAddressOf(scopedName);
      }
    }
 
    // Local variable - add & (except in C++ mode)
    return this.cppHelper!.maybeAddressOf(id);
  }
 
  /**
   * Handle lvalue argument (member access or array access)
   */
  private _handleLvalueArg(
    ctx: Parser.ExpressionContext,
    lvalueType: string,
    targetParamBaseType?: string,
  ): string {
    // Member access to array field - arrays decay to pointers
    Eif (lvalueType === "member") {
      const memberResult = this._handleMemberAccessArg(
        ctx,
        targetParamBaseType,
      );
      if (memberResult) return memberResult;
    }
 
    // Generate expression with address-of
    const generatedExpr = this.generateExpression(ctx);
    const expr = this.cppHelper!.maybeAddressOf(generatedExpr);
 
    // String subscript access may need cast
    Iif (lvalueType === "array") {
      return this._maybeCastStringSubscript(ctx, expr, targetParamBaseType);
    }
 
    return expr;
  }
 
  /**
   * Handle member access argument - may need special handling for arrays or C++ conversions
   */
  private _handleMemberAccessArg(
    ctx: Parser.ExpressionContext,
    targetParamBaseType?: string,
  ): string | null {
    const arrayStatus = this.getMemberAccessArrayStatus(ctx);
 
    // Array member - no address-of needed
    if (arrayStatus === "array") {
      return this.generateExpression(ctx);
    }
 
    // C++ mode may need temp variable for type conversion
    Iif (
      arrayStatus === "not-array" &&
      this.needsCppMemberConversion(ctx, targetParamBaseType)
    ) {
      return this._createCppMemberConversionTemp(ctx, targetParamBaseType!);
    }
 
    return null; // Fall through to default lvalue handling
  }
 
  /**
   * Create temp variable for C++ member conversion
   */
  private _createCppMemberConversionTemp(
    ctx: Parser.ExpressionContext,
    targetParamBaseType: string,
  ): string {
    const cType = TYPE_MAP[targetParamBaseType] || "uint8_t";
    const value = this.generateExpression(ctx);
    const tempName = `_cnx_tmp_${CodeGenState.tempVarCounter++}`;
    const castExpr = this.cppHelper!.cast(cType, value);
    CodeGenState.pendingTempDeclarations.push(
      `${cType} ${tempName} = ${castExpr};`,
    );
    return this.cppHelper!.maybeAddressOf(tempName);
  }
 
  /**
   * Maybe cast string subscript access for integer pointer parameters
   */
  private _maybeCastStringSubscript(
    ctx: Parser.ExpressionContext,
    expr: string,
    targetParamBaseType?: string,
  ): string {
    if (!targetParamBaseType || !this.isStringSubscriptAccess(ctx)) {
      return expr;
    }
 
    const cType = TYPE_MAP[targetParamBaseType];
    if (cType && !["float", "double", "bool", "void"].includes(cType)) {
      return this.cppHelper!.reinterpretCast(`${cType}*`, expr);
    }
 
    return expr;
  }
 
  /**
   * Handle rvalue argument (literals or complex expressions)
   */
  private _handleRvalueArg(
    ctx: Parser.ExpressionContext,
    targetParamBaseType?: string,
  ): string {
    if (!targetParamBaseType) {
      return this.generateExpression(ctx);
    }
 
    const cType = TYPE_MAP[targetParamBaseType];
    if (!cType || cType === "void") {
      return this.generateExpression(ctx);
    }
 
    const value = this.generateExpression(ctx);
 
    // C++ mode: rvalues can bind to const T&
    if (CodeGenState.cppMode) {
      return value;
    }
 
    // C mode: Use compound literal syntax
    return `&(${cType}){${value}}`;
  }
 
  // ========================================================================
  // 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 = `${scopeName}_${varName}`;
    const prefix = isPrivate ? "static " : "";
 
    const arrayDims = varDecl.arrayDimension();
    const isArray = arrayDims.length > 0;
 
    let decl = `${prefix}${type} ${fullName}`;
    if (isArray) {
      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 = `${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;
    Iif (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);
 
    Iif (!fieldList) {
      // Empty initializer: Point {} -> (Point){ 0 } or {} for C++ classes
      return isCppClass ? "{}" : `(${typeName}){ 0 }`;
    }
 
    // Get field type info for nested initializers
    // Issue #502: Check both local struct fields and SymbolTable (for C++ header structs)
    const structFieldTypes = CodeGenState.symbols!.structFields.get(typeName);
 
    const fields = fieldList.fieldInitializer().map((field) => {
      const fieldName = field.IDENTIFIER().getText();
 
      // Set expected type for nested initializers
      const savedExpectedType = CodeGenState.expectedType;
      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)
        let 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("::");
          }
        }
        CodeGenState.expectedType = fieldType;
      }
 
      const value = this.generateExpression(field.expression());
 
      // Restore expected type
      CodeGenState.expectedType = savedExpectedType;
 
      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}`);
    return `(${typeName}){ ${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
   */
  private _setupFunctionContext(
    name: string,
    ctx: Parser.FunctionDeclarationContext,
  ): void {
    // Issue #269: Set current function name for pass-by-value lookup
    const fullFuncName = CodeGenState.currentScope
      ? `${CodeGenState.currentScope}_${name}`
      : name;
    CodeGenState.currentFunctionName = fullFuncName;
    // Issue #477: Set return type for enum inference in return statements
    CodeGenState.currentFunctionReturnType = ctx.type().getText();
 
    // Track parameters for ADR-006 pointer semantics
    this._setParameters(ctx.parameterList() ?? null);
 
    // ADR-016: Clear local variables and mark that we're in a function body
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.inFunctionBody = true;
  }
 
  /**
   * Resolve return type and initial params for function
   */
  private _resolveReturnTypeAndParams(
    name: string,
    returnType: string,
    isMainWithArgs: boolean,
    ctx: Parser.FunctionDeclarationContext,
  ): { actualReturnType: string; initialParams: string } {
    if (isMainWithArgs) {
      // Special case: main(u8 args[][]) -> int main(int argc, char *argv[])
      const argsParam = ctx.parameterList()!.parameter()[0];
      CodeGenState.mainArgsName = argsParam.IDENTIFIER().getText();
      return {
        actualReturnType: "int",
        initialParams: "int argc, char *argv[]",
      };
    }
 
    // For main() without args, always use int return type for C++ compatibility
    const actualReturnType = name === "main" ? "int" : returnType;
    return { actualReturnType, initialParams: "" };
  }
 
  /**
   * Clean up context after function generation
   */
  private _cleanupFunctionContext(): void {
    CodeGenState.inFunctionBody = false;
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.mainArgsName = null;
    CodeGenState.currentFunctionName = null;
    CodeGenState.currentFunctionReturnType = null;
    this._clearParameters();
  }
 
  /**
   * 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): string {
    const constMod = ctx.constModifier() ? "const " : "";
    const typeName = this.getTypeName(ctx.type());
    const name = ctx.IDENTIFIER().getText();
    const dims = ctx.arrayDimension();
 
    // ADR-029: Check if this is a callback type parameter
    if (CodeGenState.callbackTypes.has(typeName)) {
      const callbackInfo = CodeGenState.callbackTypes.get(typeName)!;
      return `${callbackInfo.typedefName} ${name}`;
    }
 
    const type = this.generateType(ctx.type());
 
    // Try special cases first
    const stringArrayResult = this._tryGenerateStringArrayParam(
      ctx,
      constMod,
      name,
      dims,
    );
    if (stringArrayResult) return stringArrayResult;
 
    const arrayResult = this._tryGenerateArrayParam(constMod, type, name, dims);
    if (arrayResult) return arrayResult;
 
    // Pass-by-value types
    if (this._isPassByValueType(typeName, name)) {
      return `${constMod}${type} ${name}`;
    }
 
    // Non-array string parameters
    const stringResult = this._tryGenerateStringParam(
      ctx,
      constMod,
      name,
      dims,
    );
    if (stringResult) return stringResult;
 
    // Pass-by-reference types
    const refResult = this._tryGenerateRefParam(constMod, type, typeName, name);
    if (refResult) return refResult;
 
    // Unknown types use pass-by-value (standard C semantics)
    return `${constMod}${type} ${name}`;
  }
 
  /**
   * Try to generate string array parameter: string<N>[] -> char arr[n][N+1]
   */
  private _tryGenerateStringArrayParam(
    ctx: Parser.ParameterContext,
    constMod: string,
    name: string,
    dims: Parser.ArrayDimensionContext[],
  ): string | null {
    if (!ctx.type().stringType() || dims.length === 0) {
      return null;
    }
 
    const stringType = ctx.type().stringType()!;
    const capacity = stringType.INTEGER_LITERAL()
      ? Number.parseInt(stringType.INTEGER_LITERAL()!.getText(), 10)
      : 256;
    const dimStr = dims.map((d) => this.generateArrayDimension(d)).join("");
    return `${constMod}char ${name}${dimStr}[${capacity + 1}]`;
  }
 
  /**
   * Try to generate array parameter with auto-const
   */
  private _tryGenerateArrayParam(
    constMod: string,
    type: string,
    name: string,
    dims: Parser.ArrayDimensionContext[],
  ): string | null {
    if (dims.length === 0) {
      return null;
    }
 
    const dimStr = dims.map((d) => this.generateArrayDimension(d)).join("");
    const wasModified = this._isCurrentParameterModified(name);
    const autoConst = !wasModified && !constMod ? "const " : "";
    return `${autoConst}${constMod}${type} ${name}${dimStr}`;
  }
 
  /**
   * 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 &&
      this._isParameterPassByValueByName(CodeGenState.currentFunctionName, name)
    ) {
      return true;
    }
 
    return false;
  }
 
  /**
   * Try to generate non-array string parameter: string<N> -> char*
   */
  private _tryGenerateStringParam(
    ctx: Parser.ParameterContext,
    constMod: string,
    name: string,
    dims: Parser.ArrayDimensionContext[],
  ): string | null {
    if (!ctx.type().stringType() || dims.length !== 0) {
      return null;
    }
 
    const wasModified = this._isCurrentParameterModified(name);
    const autoConst = !wasModified && !constMod ? "const " : "";
    return `${autoConst}${constMod}char* ${name}`;
  }
 
  /**
   * Try to generate pass-by-reference parameter for known types
   */
  private _tryGenerateRefParam(
    constMod: string,
    type: string,
    typeName: string,
    name: string,
  ): string | null {
    if (!this.isKnownStruct(typeName) && !this._isKnownPrimitive(typeName)) {
      return null;
    }
 
    const wasModified = this._isCurrentParameterModified(name);
    const autoConst = !wasModified && !constMod ? "const " : "";
    const refOrPtr = this.cppHelper!.refOrPtr();
    return `${autoConst}${constMod}${type}${refOrPtr} ${name}`;
  }
 
  // ========================================================================
  // Variables
  // ========================================================================
 
  private generateVariableDecl(ctx: Parser.VariableDeclarationContext): string {
    // Issue #375: Check for C++ constructor syntax - early return
    const constructorArgList = ctx.constructorArgumentList();
    Iif (constructorArgList) {
      return this._generateConstructorDecl(ctx, constructorArgList);
    }
 
    // Issue #696: Use helper for modifier extraction and validation
    const modifiers = VariableModifierBuilder.build(
      ctx,
      CodeGenState.inFunctionBody,
    );
 
    const name = ctx.IDENTIFIER().getText();
    const typeCtx = ctx.type();
    const type = this._inferVariableType(ctx, name);
 
    // Track local variable metadata
    this._trackLocalVariable(ctx, name);
 
    // ADR-045: Handle bounded string type specially - early return
    const stringResult = this.stringDeclHelper!.generateStringDecl(
      typeCtx,
      name,
      ctx.expression() ?? null,
      ctx.arrayDimension(),
      modifiers,
      ctx.constModifier() !== null,
    );
    if (stringResult.handled) {
      return stringResult.code;
    }
 
    // Build base declaration
    const modifierPrefix = VariableModifierBuilder.toPrefix(modifiers);
    let decl = `${modifierPrefix}${type} ${name}`;
 
    // Handle array declarations - early return if array init handled
    const arrayResult = this._handleArrayDeclaration(ctx, typeCtx, name, decl);
    if (arrayResult.handled) {
      return arrayResult.code;
    }
    decl = arrayResult.decl;
 
    // Handle initialization
    decl = this._generateVariableInitializer(
      ctx,
      typeCtx,
      decl,
      arrayResult.isArray,
    );
 
    // Handle pending C++ class field assignments
    return this._finalizeCppClassAssignments(ctx, typeCtx, name, decl);
  }
 
  /**
   * Issue #696: Infer variable type, handling nullable C pointer types.
   */
  private _inferVariableType(
    ctx: Parser.VariableDeclarationContext,
    name: string,
  ): string {
    let type = this.generateType(ctx.type());
 
    // ADR-046: Handle nullable C pointer types (c_ prefix variables)
    Eif (!name.startsWith("c_") || !ctx.expression()) {
      return type;
    }
 
    const exprText = ctx.expression()!.getText();
    for (const funcName of NullCheckAnalyzer.getStructPointerFunctions()) {
      if (exprText.includes(`${funcName}(`)) {
        return `${type}*`;
      }
    }
    return type;
  }
 
  /**
   * Issue #696: Track local variable for type registry and const values.
   */
  private _trackLocalVariable(
    ctx: Parser.VariableDeclarationContext,
    name: string,
  ): void {
    if (!CodeGenState.inFunctionBody) {
      return;
    }
 
    this.trackVariableType(ctx);
    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 #696: Handle array declaration with dimension parsing and init.
   */
  private _handleArrayDeclaration(
    ctx: Parser.VariableDeclarationContext,
    typeCtx: Parser.TypeContext,
    name: string,
    decl: string,
  ): { handled: boolean; code: string; decl: string; isArray: boolean } {
    const arrayDims = ctx.arrayDimension();
    const isArray = arrayDims.length > 0;
 
    if (!isArray) {
      return { handled: false, code: "", decl, isArray: false };
    }
 
    const hasEmptyArrayDim = arrayDims.some((dim) => !dim.expression());
    const declaredSize = this._parseFirstArrayDimension(arrayDims);
 
    // ADR-035: Handle array initializers with size inference
    if (ctx.expression()) {
      const arrayInitResult = this.arrayInitHelper!.processArrayInit(
        name,
        typeCtx,
        ctx.expression()!,
        arrayDims,
        hasEmptyArrayDim,
        declaredSize,
      );
      Eif (arrayInitResult) {
        return {
          handled: true,
          code: `${decl}${arrayInitResult.dimensionSuffix} = ${arrayInitResult.initValue};`,
          decl,
          isArray: true,
        };
      }
    }
 
    // Generate dimensions and track as local array
    const newDecl = decl + this.generateArrayDimensions(arrayDims);
    CodeGenState.localArrays.add(name);
 
    return { handled: false, code: "", decl: newDecl, isArray: true };
  }
 
  /**
   * Issue #696: Parse first array dimension for validation.
   */
  private _parseFirstArrayDimension(
    arrayDims: Parser.ArrayDimensionContext[],
  ): number | null {
    if (arrayDims.length === 0 || !arrayDims[0].expression()) {
      return null;
    }
    const sizeText = arrayDims[0].expression()!.getText();
    if (/^\d+$/.exec(sizeText)) {
      return Number.parseInt(sizeText, 10);
    }
    return null;
  }
 
  /**
   * Issue #696: Generate variable initializer with validation.
   */
  private _generateVariableInitializer(
    ctx: Parser.VariableDeclarationContext,
    typeCtx: Parser.TypeContext,
    decl: string,
    isArray: boolean,
  ): string {
    if (!ctx.expression()) {
      // ADR-015: Zero initialization for uninitialized variables
      return `${decl} = ${this.getZeroInitializer(typeCtx, isArray)}`;
    }
 
    const typeName = this.getTypeName(typeCtx);
    const savedExpectedType = CodeGenState.expectedType;
    CodeGenState.expectedType = typeName;
 
    // ADR-017: Validate enum type for initialization
    this.enumValidator!.validateEnumAssignment(typeName, ctx.expression()!);
 
    // ADR-024: Validate integer literals and type conversions
    this._validateIntegerInitializer(ctx, typeName);
 
    const result = `${decl} = ${this.generateExpression(ctx.expression()!)}`;
    CodeGenState.expectedType = savedExpectedType;
 
    return result;
  }
 
  /**
   * Issue #696: Validate integer initializer using helper.
   */
  private _validateIntegerInitializer(
    ctx: Parser.VariableDeclarationContext,
    typeName: string,
  ): void {
    if (!this._isIntegerType(typeName)) {
      return;
    }
 
    const exprText = ctx.expression()!.getText().trim();
    const line = ctx.start?.line ?? 0;
    const col = ctx.start?.column ?? 0;
    const isLiteral = LiteralUtils.parseIntegerLiteral(exprText) !== undefined;
 
    try {
      if (isLiteral) {
        // Direct literal - validate it fits in the target type
        this._validateLiteralFitsType(exprText, typeName);
      } else {
        // Not a literal - check for narrowing/sign conversions
        const sourceType = this.getExpressionType(ctx.expression()!);
        this._validateTypeConversion(typeName, sourceType);
      }
    } catch (validationError) {
      const msg =
        validationError instanceof Error
          ? validationError.message
          : String(validationError);
      throw new Error(`${line}:${col} ${msg}`, { cause: validationError });
    }
  }
 
  /**
   * Issue #696: Handle pending C++ class field assignments.
   */
  private _finalizeCppClassAssignments(
    _ctx: Parser.VariableDeclarationContext,
    typeCtx: Parser.TypeContext,
    name: string,
    decl: string,
  ): string {
    Eif (CodeGenState.pendingCppClassAssignments.length === 0) {
      return `${decl};`;
    }
 
    if (CodeGenState.inFunctionBody) {
      const assignments = CodeGenState.pendingCppClassAssignments
        .map((a) => `${name}.${a}`)
        .join("\n");
      CodeGenState.pendingCppClassAssignments = [];
      return `${decl};\n${assignments}`;
    }
 
    // At global scope, we can't emit assignment statements.
    CodeGenState.pendingCppClassAssignments = [];
    throw new Error(
      `Error: C++ class '${this.getTypeName(typeCtx)}' with constructor cannot use struct initializer ` +
        `syntax at global scope. Use constructor syntax or initialize fields separately.`,
    );
  }
 
  /**
   * Issue #375: Generate C++ constructor-style declaration
   * Validates that all arguments are const variables.
   * Example: `Adafruit_MAX31856 thermocouple(pinConst);` -> `Adafruit_MAX31856 thermocouple(pinConst);`
   */
  private _generateConstructorDecl(
    ctx: Parser.VariableDeclarationContext,
    argListCtx: Parser.ConstructorArgumentListContext,
  ): string {
    const type = this.generateType(ctx.type());
    const name = ctx.IDENTIFIER().getText();
    const line = ctx.start?.line ?? 0;
 
    // Collect and validate all arguments
    const argIdentifiers = argListCtx.IDENTIFIER();
    const resolvedArgs: string[] = [];
 
    for (const argNode of argIdentifiers) {
      const argName = argNode.getText();
 
      // Check if it exists in type registry
      const typeInfo = CodeGenState.typeRegistry.get(argName);
 
      // Also check scoped variables if inside a scope
      let scopedArgName = argName;
      let scopedTypeInfo = typeInfo;
      if (!typeInfo && CodeGenState.currentScope) {
        scopedArgName = `${CodeGenState.currentScope}_${argName}`;
        scopedTypeInfo = CodeGenState.typeRegistry.get(scopedArgName);
      }
 
      if (!typeInfo && !scopedTypeInfo) {
        throw new Error(
          `Error at line ${line}: Constructor argument '${argName}' is not declared`,
        );
      }
 
      const finalTypeInfo = typeInfo ?? scopedTypeInfo!;
      const finalArgName = typeInfo ? argName : scopedArgName;
 
      // Check if it's const
      if (!finalTypeInfo.isConst) {
        throw new Error(
          `Error at line ${line}: Constructor argument '${argName}' must be const. ` +
            `C++ constructors in C-Next only accept const variables.`,
        );
      }
 
      resolvedArgs.push(finalArgName);
    }
 
    // Track the variable in type registry (as an external C++ type)
    CodeGenState.typeRegistry.set(name, {
      baseType: type,
      bitWidth: 0, // Unknown for C++ types
      isArray: false,
      arrayDimensions: [],
      isConst: false,
      isExternalCppType: true,
    });
 
    // Track as local variable if inside function body
    if (CodeGenState.inFunctionBody) {
      CodeGenState.localVariables.add(name);
    }
 
    return `${type} ${name}(${resolvedArgs.join(", ")});`;
  }
 
  /**
   * 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
    if (typeCtx.userType()) {
      const typeName = typeCtx.userType()!.getText();
      Iif (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: Build handler dependencies for assignment dispatch
  private buildHandlerDeps(): IHandlerDeps {
    return {
      symbols: CodeGenState.symbols!,
      typeRegistry: CodeGenState.typeRegistry,
      currentScope: CodeGenState.currentScope,
      currentParameters: CodeGenState.currentParameters,
      targetCapabilities: CodeGenState.targetCapabilities,
      generateExpression: (ctx) => this.generateExpression(ctx),
      tryEvaluateConstant: (ctx) => this.tryEvaluateConstant(ctx),
      generateAssignmentTarget: (ctx) => this.generateAssignmentTarget(ctx),
      isKnownStruct: (name) => this.isKnownStruct(name),
      isKnownScope: (name) => this.isKnownScope(name),
      getMemberTypeInfo: (structType, memberName) =>
        this.getMemberTypeInfo(structType, memberName),
      validateBitmapFieldLiteral: (expr, width, fieldName) =>
        this.typeValidator!.validateBitmapFieldLiteral(expr, width, fieldName),
      validateCrossScopeVisibility: (scopeName, memberName) =>
        this.validateCrossScopeVisibility(scopeName, memberName),
      checkArrayBounds: (arrayName, dimensions, indexExprs, line) =>
        this.typeValidator!.checkArrayBounds(
          arrayName,
          [...dimensions],
          [...indexExprs],
          line,
          (expr) => this.tryEvaluateConstant(expr),
        ),
      analyzeMemberChainForBitAccess: (targetCtx) =>
        this.analyzeMemberChainForBitAccess(targetCtx),
      generateFloatBitWrite: (name, typeInfo, bitIndex, width, value) =>
        this.generateFloatBitWrite(name, typeInfo, bitIndex, width, value),
      foldBooleanToInt: (expr) => this.foldBooleanToInt(expr),
      markNeedsString: () => {
        this.requireInclude("string");
      },
      markClampOpUsed: (op, typeName) => this.markClampOpUsed(op, typeName),
      generateAtomicRMW: (target, cOp, value, typeInfo) =>
        this.generateAtomicRMW(target, cOp, value, typeInfo),
    };
  }
 
  /**
   * Analyze a member chain target to detect bit access at the end.
   * Issue #644: Delegates to MemberChainAnalyzer.
   */
  private analyzeMemberChainForBitAccess(
    targetCtx: Parser.AssignmentTargetContext,
  ): {
    isBitAccess: boolean;
    baseTarget?: string;
    bitIndex?: string;
    baseType?: string;
  } {
    return this.memberChainAnalyzer!.analyze(targetCtx);
  }
 
  /**
   * Generate float bit write using shadow variable + memcpy.
   * Issue #644: Delegates to FloatBitHelper.
   */
  private generateFloatBitWrite(
    name: string,
    typeInfo: TTypeInfo,
    bitIndex: string,
    width: string | null,
    value: string,
  ): string | null {
    return this.floatBitHelper!.generateFloatBitWrite(
      name,
      typeInfo,
      bitIndex,
      width,
      value,
    );
  }
 
  // 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 savedExpectedType = CodeGenState.expectedType;
    const savedAssignmentContext = { ...CodeGenState.assignmentContext };
 
    const resolved = this.expectedTypeResolver!.resolve(targetCtx);
    if (resolved.expectedType) {
      CodeGenState.expectedType = resolved.expectedType;
    }
    if (resolved.assignmentContext) {
      CodeGenState.assignmentContext = resolved.assignmentContext;
    }
 
    const value = this.generateExpression(ctx.expression());
 
    // Restore expected type and assignment context
    CodeGenState.expectedType = savedExpectedType;
    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
    this.assignmentValidator!.validate(
      targetCtx,
      ctx.expression(),
      isCompound,
      ctx.start?.line ?? 0,
    );
 
    // ADR-109: Dispatch to assignment handlers
    // Build context, classify, and dispatch - all patterns handled by handlers
    const assignCtx = buildAssignmentContext(ctx, {
      typeRegistry: CodeGenState.typeRegistry,
      generateExpression: () => value,
    });
    const handlerDeps = this.buildHandlerDeps();
    const classifier = new AssignmentClassifier({
      symbols: handlerDeps.symbols,
      typeRegistry: handlerDeps.typeRegistry,
      currentScope: handlerDeps.currentScope,
      isKnownStruct: handlerDeps.isKnownStruct,
      isKnownScope: handlerDeps.isKnownScope,
      getMemberTypeInfo: handlerDeps.getMemberTypeInfo,
    });
    const assignmentKind = classifier.classify(assignCtx);
    const handler = AssignmentHandlerRegistry.getHandler(assignmentKind);
    return handler(assignCtx, handlerDeps);
  }
 
  /**
   * ADR-049: Generate atomic Read-Modify-Write operation
   * Uses LDREX/STREX on platforms that support it, otherwise PRIMASK
   */
  private 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) =>
        this.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();
 
    const separatorCtx: ISeparatorContext =
      MemberSeparatorResolver.buildContext(
        firstId,
        hasGlobal,
        hasThis,
        CodeGenState.currentScope,
        isStructParam,
        separatorDeps,
        isCppAccess,
      );
 
    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 = this.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);
    Iif (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 {
    // Type-aware resolution: check only the expected enum type
    if (
      CodeGenState.expectedType &&
      CodeGenState.symbols!.knownEnums.has(CodeGenState.expectedType)
    ) {
      const members = CodeGenState.symbols!.enumMembers.get(
        CodeGenState.expectedType,
      );
      Iif (members?.has(id)) {
        return `${CodeGenState.expectedType}${this.getScopeSeparator(false)}${id}`;
      }
      return null;
    }
 
    // No expected enum type - search all enums but error on ambiguity
    const matchingEnums: string[] = [];
    for (const [enumName, members] of CodeGenState.symbols!.enumMembers) {
      if (members.has(id)) {
        matchingEnums.push(enumName);
      }
    }
 
    Iif (matchingEnums.length === 1) {
      return `${matchingEnums[0]}${this.getScopeSeparator(false)}${id}`;
    }
    if (matchingEnums.length > 1) {
      throw new Error(
        `Error: Ambiguous enum member '${id}' exists in multiple enums: ${matchingEnums.join(", ")}. Use qualified access (e.g., ${matchingEnums[0]}.${id})`,
      );
    }
 
    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 this.cppHelper!.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 this.cppHelper!.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 this.cppHelper!.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
    const finalCast = this.cppHelper!.cast(targetType, `(${expr})`);
    return `((${expr}) > ${maxComparison} ? ${maxValue} : (${expr}) < ${minComparison} ? ${minValue} : ${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,
    );
  }
 
  /**
   * 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)
    Eif (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);
  }
}