All files / transpiler/output/codegen/generators/expressions PostfixExpressionGenerator.ts

93.23% Statements 496/532
85.3% Branches 354/415
100% Functions 51/51
93.51% Lines 490/524

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                                                                                                                14x                   2092x       2092x       2092x       2092x       2092x     2092x 2092x 2x     2092x                                                                                             14x           2096x   2096x 2096x     2096x 2096x     2096x   2096x     2096x   2096x     2096x 4x   2092x     2092x       2096x                 2096x                   2096x 516x 319x 319x 197x 84x                                     84x 84x 84x   84x   84x     113x             113x 113x                 2063x 2x               2061x                     14x           319x                 30x       288x                 2x       285x                     37x       232x                                         232x 232x   319x 319x   319x   319x   319x 319x           14x             319x 288x     31x 31x 31x     31x 1x           30x 1x   30x 1x       30x 30x 1x     30x             14x             288x 285x   3x 1x   2x 2x       2x 2x 2x 2x       1x   2x                       14x           5x 5x     5x 3x       2x 2x       2x 2x 2x 2x                                 14x     47x                       14x       32x 32x 32x             14x                 47x   47x 47x   12x 12x   6x 6x   9x 9x   20x             20x     32x 32x 32x                     14x                   285x 1x               284x           284x 47x                     237x 3x           3x 3x 3x 3x     234x 2x           2x 2x 2x 2x     232x                                                     14x       3x 3x         3x 1x     3x 1x 1x   3x             14x             12x 1x           11x 1x       1x 1x         10x       12x 1x         9x             14x       4x 4x 4x 4x 1x   3x   3x           14x     2x 1x   1x 1x 1x 1x               14x         2x 2x     2x 2x 1x       1x                             1x 1x 1x                     14x                 3x 1x     2x 2x                               14x               5x 5x 2x   5x     5x           14x                   6x 6x 1x         5x 5x 1x         4x 4x 1x     3x           14x                               12x 3x 2x   1x           9x 3x       6x             14x             6x 1x           5x 1x       1x 1x           1x 1x 1x             4x       6x 1x         3x         3x 3x 3x               14x       4x 4x           14x       8x 6x     2x         2x       1x       1x               14x       6x       6x 1x         5x 1x         4x 4x 1x         3x 3x                       14x             9x 1x       8x 8x 1x   6x           6x             14x               20x 1x           19x 2x       2x 1x 1x     1x           17x       20x 1x           16x 1x         15x     15x         2x         13x                                                                                     14x   226x                             14x                 232x                       232x                                       14x         231x 57x   174x 174x 170x     4x 4x             4x 4x 4x           14x           227x 197x   30x 1x     29x 29x 29x 29x 28x 28x 28x 14x 14x       1x       1x 1x   29x           14x           197x 167x     30x 25x           29x           29x 29x 29x 29x 29x           29x           14x           167x 80x         87x                 87x 87x 87x           14x         80x 74x     6x                 6x               6x 6x 6x 6x           14x       74x 39x         35x           74x 74x 74x 74x 74x 33x       33x 9x 9x     35x           14x         39x 37x     2x 2x 2x             2x 2x 2x           14x         37x       35x     2x 2x             2x 2x 2x           14x       35x 35x 35x 35x 35x 35x 31x       31x 15x 15x 15x     35x                                                                               14x             84x 84x               84x 41x 43x 43x                                 14x                 41x 41x       41x   41x 41x     41x     1x       1x 1x     1x 1x       39x 1x 1x 1x 1x       38x 31x         7x 41x                                 7x 1x                   6x           14x       41x   1x 1x 41x                 14x       40x 39x 38x           14x       40x 40x               14x         31x 31x 31x   31x 28x   31x           14x             1x 1x     1x 1x 1x       1x           14x           6x           6x     3x       3x 3x 1x   3x   3x     6x           14x                     43x           43x     43x 22x                         21x     21x 11x   10x         21x 21x 17x     17x           4x       42x                                 14x 21x             14x           22x 1x         21x   21x 21x 21x 22x 22x   22x 22x 17x   17x         21x 21x     21x 17x         21x 16x   5x                   14x       123x            
/**
 * Postfix Expression Generator (Issue #644)
 *
 * Handles postfix expressions including:
 * - Member access (obj.field)
 * - Array subscripts (arr[i])
 * - Bit access (value[3] or value[0, 8])
 * - Function calls (func())
 * - Property access (.length, .capacity, .size)
 *
 * This generator was extracted from CodeGenerator._generatePostfixExpr
 * to reduce the size and complexity of CodeGenerator.ts.
 */
import * as Parser from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorOutput from "../IGeneratorOutput";
import TGeneratorEffect from "../TGeneratorEffect";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
import accessGenerators from "./AccessExprGenerator";
import generateFunctionCall from "./CallExprGenerator";
import memberAccessChain from "../../memberAccessChain";
import MemberAccessValidator from "../../helpers/MemberAccessValidator";
import BitmapAccessHelper from "./BitmapAccessHelper";
import NarrowingCastHelper from "../../helpers/NarrowingCastHelper";
import TypeCheckUtils from "../../../../../utils/TypeCheckUtils";
import SubscriptClassifier from "../../subscript/SubscriptClassifier";
import TYPE_WIDTH from "../../types/TYPE_WIDTH";
import C_TYPE_WIDTH from "../../types/C_TYPE_WIDTH";
import TTypeInfo from "../../types/TTypeInfo";
import CodeGenState from "../../../../state/CodeGenState";
 
// ========================================================================
// Tracking State
// ========================================================================
 
/**
 * Mutable tracking state threaded through the postfix op loop.
 */
interface ITrackingState {
  result: string;
  isRegisterChain: boolean;
  currentMemberIsArray: boolean;
  currentStructType: string | undefined;
  previousStructType: string | undefined;
  previousMemberName: string | undefined;
  resolvedIdentifier: string | undefined;
  remainingArrayDims: number;
  subscriptDepth: number;
  isGlobalAccess: boolean;
  isCppAccessChain: boolean;
}
 
/**
 * Initialize tracking state from the primary expression.
 */
const initializeTrackingState = (
  rootIdentifier: string | undefined,
  result: string,
  primaryTypeInfo:
    | { baseType: string; arrayDimensions?: (number | string)[] }
    | undefined,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): ITrackingState => {
  const isRegisterChain = rootIdentifier
    ? input.symbols!.knownRegisters.has(rootIdentifier)
    : false;
 
  const primaryBaseType = rootIdentifier
    ? CodeGenState.getVariableTypeInfo(rootIdentifier)?.baseType
    : undefined;
  const currentStructType =
    primaryBaseType && orchestrator.isKnownStruct(primaryBaseType)
      ? primaryBaseType
      : undefined;
 
  const primaryParamInfo = rootIdentifier
    ? state.currentParameters.get(rootIdentifier)
    : undefined;
  const remainingArrayDims =
    primaryTypeInfo?.arrayDimensions?.length ??
    (primaryParamInfo?.isArray ? 1 : 0);
 
  let isCppAccessChain = false;
  if (rootIdentifier && orchestrator.isCppScopeSymbol(rootIdentifier)) {
    isCppAccessChain = true;
  }
 
  return {
    result,
    isRegisterChain,
    currentMemberIsArray: false,
    currentStructType,
    previousStructType: undefined,
    previousMemberName: undefined,
    resolvedIdentifier: rootIdentifier,
    remainingArrayDims,
    subscriptDepth: 0,
    isGlobalAccess: false,
    isCppAccessChain,
  };
};
 
/**
 * Context for the postfix expression being processed.
 * Bundles values that don't change during the postfix op loop,
 * except for `effects` which accumulates side effects via push().
 */
interface IPostfixContext {
  rootIdentifier: string | undefined;
  isStructParam: boolean;
  /** Issue #895: Force pointer semantics for callback-compatible params */
  forcePointerSemantics: boolean;
  input: IGeneratorInput;
  state: IGeneratorState;
  orchestrator: IOrchestrator;
  effects: TGeneratorEffect[];
}
 
// ========================================================================
// Main Entry Point
// ========================================================================
 
/**
 * Generate C code for a postfix expression.
 *
 * A postfix expression consists of a primary expression followed by
 * zero or more postfix operations (member access, subscripts, function calls).
 *
 * @param ctx - The postfix expression context
 * @param input - Generator input (type registry, symbols, etc.)
 * @param state - Generator state (current scope, parameters, etc.)
 * @param orchestrator - Orchestrator for callbacks into CodeGenerator
 * @returns Generated code and effects
 */
const generatePostfixExpression = (
  ctx: Parser.PostfixExpressionContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  const primary = ctx.primaryExpression();
  const ops = ctx.postfixOp();
 
  // Check if this is a struct parameter - we may need to handle -> access
  const rootIdentifier = primary.IDENTIFIER()?.getText();
  const paramInfo = rootIdentifier
    ? state.currentParameters.get(rootIdentifier)
    : null;
  const isStructParam = paramInfo?.isStruct ?? false;
  // Issue #895: Callback-compatible params need pointer semantics even in C++ mode
  const forcePointerSemantics = paramInfo?.forcePointerSemantics ?? false;
 
  // Issue #579: Check if we have subscript access on a non-array parameter
  const hasSubscriptOps = ops.some((op) => op.expression().length > 0);
  const isNonArrayParamWithSubscript =
    paramInfo && !paramInfo.isArray && !paramInfo.isStruct && hasSubscriptOps;
 
  let result: string;
  if (isNonArrayParamWithSubscript) {
    result = rootIdentifier!;
  } else {
    result = orchestrator.generatePrimaryExpr(primary);
  }
 
  const primaryTypeInfo = rootIdentifier
    ? CodeGenState.getVariableTypeInfo(rootIdentifier)
    : undefined;
 
  const tracking = initializeTrackingState(
    rootIdentifier,
    result,
    primaryTypeInfo,
    input,
    state,
    orchestrator,
  );
 
  const postfixCtx: IPostfixContext = {
    rootIdentifier,
    isStructParam,
    forcePointerSemantics,
    input,
    state,
    orchestrator,
    effects,
  };
 
  for (const op of ops) {
    if (op.IDENTIFIER()) {
      const memberName = op.IDENTIFIER()!.getText();
      handleMemberOp(memberName, tracking, postfixCtx);
    } else if (op.expression().length > 0) {
      const subscriptResult = generateSubscriptAccess(
        {
          result: tracking.result,
          op,
          rootIdentifier,
          primaryTypeInfo,
          resolvedIdentifier: tracking.resolvedIdentifier,
          currentStructType: tracking.currentStructType,
          currentMemberIsArray: tracking.currentMemberIsArray,
          remainingArrayDims: tracking.remainingArrayDims,
          subscriptDepth: tracking.subscriptDepth,
          isRegisterChain: tracking.isRegisterChain,
        },
        input,
        state,
        orchestrator,
        effects,
      );
 
      tracking.result = subscriptResult.result;
      tracking.currentStructType = subscriptResult.currentStructType;
      tracking.currentMemberIsArray =
        subscriptResult.currentMemberIsArray ?? false;
      tracking.remainingArrayDims =
        subscriptResult.remainingArrayDims ?? tracking.remainingArrayDims;
      tracking.subscriptDepth =
        subscriptResult.subscriptDepth ?? tracking.subscriptDepth;
    } else {
      const callResult = generateFunctionCall(
        tracking.result,
        op.argumentList() || null,
        input,
        state,
        orchestrator,
      );
      applyAccessEffects(callResult.effects, effects);
      tracking.result = callResult.code;
    }
  }
 
  // ADR-006: If a struct parameter is used as a whole value (no postfix ops)
  // This applies to both normal struct params AND callback-promoted struct params.
  // When used as a value (assignments, etc.), we need to dereference to get the struct.
  // Issue #937: For function arguments expecting pointers, CallExprGenerator handles
  // using the identifier directly instead of the dereferenced form.
  if (isStructParam && ops.length === 0) {
    return {
      code: memberAccessChain.wrapStructParamValue(result, {
        cppMode: orchestrator.isCppMode(),
      }),
      effects,
    };
  }
 
  return { code: tracking.result, effects };
};
 
// ========================================================================
// Member Operation Handling
// ========================================================================
 
/**
 * Handle a member access operation (the `.identifier` part of postfix).
 * Mutates `tracking` in place.
 */
const handleMemberOp = (
  memberName: string,
  tracking: ITrackingState,
  ctx: IPostfixContext,
): void => {
  // ADR-016: Handle global. prefix
  if (
    handleGlobalPrefix(
      memberName,
      tracking,
      ctx.input,
      ctx.state,
      ctx.orchestrator,
    )
  ) {
    return;
  }
 
  // Issue #212: Check if 'length' is a scope variable before treating as property
  if (
    handleThisScopeLength(
      memberName,
      tracking,
      ctx.input,
      ctx.state,
      ctx.orchestrator,
    )
  ) {
    return;
  }
 
  // Handle property access (.length, .capacity, .size)
  if (
    tryPropertyAccess(
      memberName,
      tracking,
      ctx.rootIdentifier,
      ctx.input,
      ctx.state,
      ctx.orchestrator,
      ctx.effects,
    )
  ) {
    return;
  }
 
  // Handle bitmap field access, scope member access, enum member access, etc.
  const memberResult = generateMemberAccess(
    {
      result: tracking.result,
      memberName,
      rootIdentifier: ctx.rootIdentifier,
      isStructParam: ctx.isStructParam,
      forcePointerSemantics: ctx.forcePointerSemantics,
      isGlobalAccess: tracking.isGlobalAccess,
      isCppAccessChain: tracking.isCppAccessChain,
      currentStructType: tracking.currentStructType,
      resolvedIdentifier: tracking.resolvedIdentifier,
      previousStructType: tracking.previousStructType,
      previousMemberName: tracking.previousMemberName,
      isRegisterChain: tracking.isRegisterChain,
    },
    ctx.input,
    ctx.state,
    ctx.orchestrator,
    ctx.effects,
  );
 
  tracking.result = memberResult.result;
  tracking.resolvedIdentifier =
    memberResult.resolvedIdentifier ?? tracking.resolvedIdentifier;
  tracking.currentStructType = memberResult.currentStructType;
  tracking.currentMemberIsArray =
    memberResult.currentMemberIsArray ?? tracking.currentMemberIsArray;
  tracking.isRegisterChain =
    memberResult.isRegisterChain ?? tracking.isRegisterChain;
  tracking.isCppAccessChain =
    memberResult.isCppAccessChain ?? tracking.isCppAccessChain;
  tracking.previousStructType = memberResult.previousStructType;
  tracking.previousMemberName = memberResult.previousMemberName;
};
 
/**
 * Handle `global.X` prefix. Returns true if handled (caller should skip).
 */
const handleGlobalPrefix = (
  memberName: string,
  tracking: ITrackingState,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): boolean => {
  if (tracking.result !== "__GLOBAL_PREFIX__") {
    return false;
  }
 
  tracking.result = memberName;
  tracking.resolvedIdentifier = memberName;
  tracking.isGlobalAccess = true;
 
  // ADR-057: Check if global variable would be shadowed by a local
  if (state.localVariables.has(memberName)) {
    throw new Error(
      `Error: Cannot use 'global.${memberName}' when local variable '${memberName}' shadows it. ` +
        `Rename the local variable to avoid shadowing.`,
    );
  }
 
  if (orchestrator.isCppScopeSymbol(memberName)) {
    tracking.isCppAccessChain = true;
  }
  if (input.symbols!.knownRegisters.has(memberName)) {
    tracking.isRegisterChain = true;
  }
 
  // Issue #612: Set currentStructType for global struct variables
  const globalTypeInfo = CodeGenState.getVariableTypeInfo(memberName);
  if (globalTypeInfo && orchestrator.isKnownStruct(globalTypeInfo.baseType)) {
    tracking.currentStructType = globalTypeInfo.baseType;
  }
 
  return true;
};
 
/**
 * Handle `this.length` when length is a scope member variable.
 * Returns true if handled (caller should skip).
 */
const handleThisScopeLength = (
  memberName: string,
  tracking: ITrackingState,
  _input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): boolean => {
  if (tracking.result !== "__THIS_SCOPE__" || memberName !== "length") {
    return false;
  }
  if (!state.currentScope) {
    throw new Error("Error: 'this' can only be used inside a scope");
  }
  const members = state.scopeMembers.get(state.currentScope);
  Iif (!members?.has("length")) {
    return false;
  }
 
  tracking.result = `${state.currentScope}_${memberName}`;
  tracking.resolvedIdentifier = tracking.result;
  const resolvedTypeInfo = CodeGenState.getVariableTypeInfo(tracking.result);
  if (
    resolvedTypeInfo &&
    orchestrator.isKnownStruct(resolvedTypeInfo.baseType)
  ) {
    tracking.currentStructType = resolvedTypeInfo.baseType;
  }
  return true;
};
 
/**
 * Resolve the TTypeInfo for .capacity/.size on the current expression.
 *
 * Tries in order:
 * 1. resolvedIdentifier (tracks the resolved identifier through member chains)
 * 2. rootIdentifier (the leftmost identifier)
 * 3. Struct field lookup via previousStructType/previousMemberName
 *    (handles alice.name.capacity where resolvedIdentifier is undefined)
 */
const resolveStringTypeInfo = (
  tracking: ITrackingState,
  rootIdentifier: string | undefined,
  input: IGeneratorInput,
  orchestrator: IOrchestrator,
): TTypeInfo | undefined => {
  const identifier = tracking.resolvedIdentifier ?? rootIdentifier;
  const typeInfo = identifier
    ? CodeGenState.getVariableTypeInfo(identifier)
    : undefined;
  if (typeInfo?.isString) {
    return typeInfo;
  }
 
  // Struct member path: look up the field type to build a synthetic TTypeInfo
  Eif (tracking.previousStructType && tracking.previousMemberName) {
    const fieldInfo = orchestrator.getStructFieldInfo(
      tracking.previousStructType,
      tracking.previousMemberName,
    );
    Eif (fieldInfo && TypeCheckUtils.isString(fieldInfo.type)) {
      const capacityMatch = /^string<(\d+)>$/.exec(fieldInfo.type);
      const capacity = capacityMatch ? Number(capacityMatch[1]) : undefined;
      return {
        baseType: "char",
        bitWidth: 8,
        isArray: false,
        isConst: false,
        isString: true,
        stringCapacity: capacity,
      } as TTypeInfo;
    }
  }
 
  return typeInfo;
};
 
/**
 * Create context object for explicit length property generators.
 */
const createExplicitLengthContext = (
  tracking: ITrackingState,
  rootIdentifier: string | undefined,
): IExplicitLengthContext => ({
  result: tracking.result,
  rootIdentifier,
  resolvedIdentifier: tracking.resolvedIdentifier,
  previousStructType: tracking.previousStructType,
  previousMemberName: tracking.previousMemberName,
  subscriptDepth: tracking.subscriptDepth,
});
 
/**
 * Apply property result to tracking state.
 */
const applyPropertyResult = (
  tracking: ITrackingState,
  result: string,
): void => {
  tracking.result = result;
  tracking.previousStructType = undefined;
  tracking.previousMemberName = undefined;
};
 
/**
 * Try handling explicit length property (ADR-058).
 * Returns true if handled.
 */
const tryExplicitLengthProperty = (
  memberName: string,
  tracking: ITrackingState,
  rootIdentifier: string | undefined,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): boolean => {
  const ctx = createExplicitLengthContext(tracking, rootIdentifier);
 
  let result: string | null = null;
  switch (memberName) {
    case "bit_length":
      result = generateBitLengthProperty(ctx, input, state, orchestrator);
      break;
    case "byte_length":
      result = generateByteLengthProperty(ctx, input, state, orchestrator);
      break;
    case "element_count":
      result = generateElementCountProperty(ctx, input, state, orchestrator);
      break;
    case "char_count":
      result = generateCharCountProperty(
        ctx,
        input,
        state,
        orchestrator,
        effects,
      );
      break;
  }
 
  Eif (result !== null) {
    applyPropertyResult(tracking, result);
    return true;
  }
  return false;
};
 
/**
 * Try handling property access (.capacity, .size, .bit_length, .byte_length, .element_count, .char_count).
 * Returns true if handled.
 *
 * Note: .length was removed in favor of explicit properties (ADR-058).
 */
const tryPropertyAccess = (
  memberName: string,
  tracking: ITrackingState,
  rootIdentifier: string | undefined,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): boolean => {
  // ADR-058: .length is deprecated - use explicit properties instead
  if (memberName === "length") {
    throw new Error(
      `Error: '.length' on '${tracking.result}' is deprecated. Use explicit properties: ` +
        `.bit_length (bit width), .byte_length (byte size), ` +
        `.element_count (array size), or .char_count (string length)`,
    );
  }
 
  // ADR-058: Explicit length properties
  const explicitProps = new Set([
    "bit_length",
    "byte_length",
    "element_count",
    "char_count",
  ]);
  if (explicitProps.has(memberName)) {
    return tryExplicitLengthProperty(
      memberName,
      tracking,
      rootIdentifier,
      input,
      state,
      orchestrator,
      effects,
    );
  }
 
  if (memberName === "capacity") {
    const typeInfo = resolveStringTypeInfo(
      tracking,
      rootIdentifier,
      input,
      orchestrator,
    );
    const capResult = accessGenerators.generateCapacityProperty(typeInfo);
    applyAccessEffects(capResult.effects, effects);
    tracking.result = capResult.code;
    return true;
  }
 
  if (memberName === "size") {
    const typeInfo = resolveStringTypeInfo(
      tracking,
      rootIdentifier,
      input,
      orchestrator,
    );
    const sizeResult = accessGenerators.generateSizeProperty(typeInfo);
    applyAccessEffects(sizeResult.effects, effects);
    tracking.result = sizeResult.code;
    return true;
  }
 
  return false;
};
 
// ========================================================================
// ADR-058: Explicit Length Properties
// ========================================================================
 
/**
 * Context for explicit length property generation.
 */
interface IExplicitLengthContext {
  result: string;
  rootIdentifier: string | undefined;
  resolvedIdentifier: string | undefined;
  previousStructType: string | undefined;
  previousMemberName: string | undefined;
  subscriptDepth: number;
}
 
/**
 * Get the numeric bit width for a type (internal helper for ADR-058).
 * Returns 0 if type is unknown.
 *
 * Note: This differs from getTypeBitWidth() which returns a string and is
 * used for the legacy .length property. This function returns a number for
 * use in calculations (e.g., array total bits = elements * element width).
 */
const getNumericBitWidth = (
  typeName: string,
  input: IGeneratorInput,
): number => {
  let bitWidth = TYPE_WIDTH[typeName] ?? C_TYPE_WIDTH[typeName] ?? 0;
  Iif (bitWidth === 0 && input.symbolTable) {
    const enumWidth = input.symbolTable.getEnumBitWidth(typeName);
    if (enumWidth) bitWidth = enumWidth;
  }
  // Check if it's a known enum (default to 32 bits per ADR-017)
  if (bitWidth === 0 && input.symbols?.knownEnums?.has(typeName)) {
    bitWidth = 32;
  }
  // Check bitmap types
  if (bitWidth === 0 && input.symbols?.bitmapBitWidth) {
    const bitmapWidth = input.symbols.bitmapBitWidth.get(typeName);
    Iif (bitmapWidth) bitWidth = bitmapWidth;
  }
  return bitWidth;
};
 
/**
 * Generate .bit_length property access (ADR-058).
 * Returns the bit width of any type.
 */
const generateBitLengthProperty = (
  ctx: IExplicitLengthContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): string | null => {
  // Special case: main function's args.bit_length -> not supported
  if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
    throw new Error(
      `Error: .bit_length is not supported on 'args' parameter. Use .element_count for argc.`,
    );
  }
 
  // Check struct member access
  if (ctx.previousStructType && ctx.previousMemberName) {
    const fieldInfo = orchestrator.getStructFieldInfo(
      ctx.previousStructType,
      ctx.previousMemberName,
    );
    Eif (fieldInfo) {
      return generateStructFieldBitLength(fieldInfo, ctx.subscriptDepth, input);
    }
  }
 
  // Get type info for the resolved identifier
  const typeInfo = ctx.resolvedIdentifier
    ? CodeGenState.getVariableTypeInfo(ctx.resolvedIdentifier)
    : undefined;
 
  if (!typeInfo) {
    throw new Error(
      `Error: Cannot determine .bit_length for '${ctx.result}' - type not found in registry.`,
    );
  }
 
  return generateTypeInfoBitLength(typeInfo, ctx.subscriptDepth, input);
};
 
/**
 * Calculate product of remaining array dimensions from subscript depth.
 * Returns null if a dynamic dimension (C macro) is encountered.
 */
const calculateRemainingDimensionsProduct = (
  dimensions: (number | string)[],
  subscriptDepth: number,
): { product: number } | { dynamicDim: string } => {
  let product = 1;
  for (let i = subscriptDepth; i < dimensions.length; i++) {
    const dim = dimensions[i];
    if (typeof dim !== "number") {
      return { dynamicDim: dim };
    }
    product *= dim;
  }
  return { product };
};
 
/**
 * Generate bit length for string type from type name.
 */
const generateStringBitLengthFromTypeName = (
  typeName: string,
): string | null => {
  if (!typeName.startsWith("string<")) {
    return null;
  }
  const capacityMatch = /^string<(\d+)>$/.exec(typeName);
  Eif (capacityMatch) {
    const capacity = Number(capacityMatch[1]);
    return String((capacity + 1) * 8);
  }
  return null;
};
 
/**
 * Generate .bit_length for a struct field.
 */
const generateStructFieldBitLength = (
  fieldInfo: { type: string; dimensions?: (number | string)[] },
  subscriptDepth: number,
  input: IGeneratorInput,
): string => {
  const memberType = fieldInfo.type;
  const dimensions = fieldInfo.dimensions;
 
  // String field: bit_length = (capacity + 1) * 8
  const stringBitLength = generateStringBitLengthFromTypeName(memberType);
  if (stringBitLength !== null) {
    return stringBitLength;
  }
 
  // Array field: total bits = product of dimensions * element bit width
  Iif (dimensions && dimensions.length > subscriptDepth) {
    const elementBitWidth = getNumericBitWidth(memberType, input);
    if (elementBitWidth > 0) {
      const dimResult = calculateRemainingDimensionsProduct(
        dimensions,
        subscriptDepth,
      );
      if ("dynamicDim" in dimResult) {
        return `/* .bit_length: dynamic dimension ${dimResult.dynamicDim} */0`;
      }
      return String(dimResult.product * elementBitWidth);
    }
  }
 
  // Scalar or fully subscripted: return element bit width
  const bitWidth = getNumericBitWidth(memberType, input);
  Eif (bitWidth > 0) {
    return String(bitWidth);
  }
 
  throw new Error(
    `Error: Cannot determine .bit_length for unsupported type '${memberType}'.`,
  );
};
 
/**
 * Generate bit length for a scalar (non-array) type.
 */
const generateScalarBitLength = (
  typeInfo: {
    isEnum?: boolean;
    baseType: string;
    bitWidth?: number;
  },
  input: IGeneratorInput,
): string => {
  // Enum type: always 32 bits
  if (typeInfo.isEnum) {
    return "32";
  }
 
  Eif (typeInfo.bitWidth) {
    return String(typeInfo.bitWidth);
  }
 
  // Try lookup by base type
  const bitWidth = getNumericBitWidth(typeInfo.baseType, input);
  if (bitWidth > 0) {
    return String(bitWidth);
  }
  throw new Error(
    `Error: Cannot determine .bit_length for unsupported type '${typeInfo.baseType}'.`,
  );
};
 
/**
 * Get element bit width for array type.
 */
const getArrayElementBitWidth = (
  typeInfo: {
    isEnum?: boolean;
    baseType: string;
    bitWidth?: number;
  },
  input: IGeneratorInput,
): number => {
  let elementBitWidth = typeInfo.bitWidth || 0;
  if (elementBitWidth === 0) {
    elementBitWidth = getNumericBitWidth(typeInfo.baseType, input);
  }
  Iif (elementBitWidth === 0 && typeInfo.isEnum) {
    elementBitWidth = 32;
  }
  return elementBitWidth;
};
 
/**
 * Generate bit length for an array type.
 */
const generateArrayBitLength = (
  typeInfo: {
    isEnum?: boolean;
    arrayDimensions?: (number | string)[];
    baseType: string;
    bitWidth?: number;
  },
  subscriptDepth: number,
  input: IGeneratorInput,
): string => {
  const dims = typeInfo.arrayDimensions;
  if (!dims || dims.length === 0) {
    throw new Error(
      `Error: Cannot determine .bit_length for array with unknown dimensions.`,
    );
  }
 
  const elementBitWidth = getArrayElementBitWidth(typeInfo, input);
  if (elementBitWidth === 0) {
    throw new Error(
      `Error: Cannot determine .bit_length for array with unsupported element type '${typeInfo.baseType}'.`,
    );
  }
 
  const dimResult = calculateRemainingDimensionsProduct(dims, subscriptDepth);
  if ("dynamicDim" in dimResult) {
    return `/* .bit_length: dynamic dimension ${dimResult.dynamicDim} */0`;
  }
 
  return String(dimResult.product * elementBitWidth);
};
 
/**
 * Generate .bit_length from type info.
 */
const generateTypeInfoBitLength = (
  typeInfo: {
    isString?: boolean;
    isArray?: boolean;
    isEnum?: boolean;
    arrayDimensions?: (number | string)[];
    baseType: string;
    bitWidth?: number;
    isBitmap?: boolean;
    bitmapTypeName?: string;
    stringCapacity?: number;
  },
  subscriptDepth: number,
  input: IGeneratorInput,
): string => {
  // String type: bit_length = (capacity + 1) * 8 (buffer size in bits)
  if (typeInfo.isString) {
    if (typeInfo.stringCapacity !== undefined) {
      return String((typeInfo.stringCapacity + 1) * 8);
    }
    throw new Error(
      `Error: Cannot determine .bit_length for string with unknown capacity.`,
    );
  }
 
  // Non-array scalar: return bit width
  if (!typeInfo.isArray) {
    return generateScalarBitLength(typeInfo, input);
  }
 
  // Array: calculate total bits
  return generateArrayBitLength(typeInfo, subscriptDepth, input);
};
 
/**
 * Generate .byte_length property access (ADR-058).
 * Returns the byte size of any type (bit_length / 8).
 */
const generateByteLengthProperty = (
  ctx: IExplicitLengthContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): string | null => {
  // Special case: main function's args
  if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
    throw new Error(
      `Error: .byte_length is not supported on 'args' parameter. Use .element_count for argc.`,
    );
  }
 
  // Check struct member access
  if (ctx.previousStructType && ctx.previousMemberName) {
    const fieldInfo = orchestrator.getStructFieldInfo(
      ctx.previousStructType,
      ctx.previousMemberName,
    );
    Eif (fieldInfo) {
      const bitLength = generateStructFieldBitLength(
        fieldInfo,
        ctx.subscriptDepth,
        input,
      );
      // Parse and convert to bytes
      const bitValue = Number.parseInt(bitLength, 10);
      Eif (!Number.isNaN(bitValue)) {
        return String(bitValue / 8);
      }
      return bitLength.replace(".bit_length", ".byte_length");
    }
  }
 
  // Get type info for the resolved identifier
  const typeInfo = ctx.resolvedIdentifier
    ? CodeGenState.getVariableTypeInfo(ctx.resolvedIdentifier)
    : undefined;
 
  if (!typeInfo) {
    throw new Error(
      `Error: Cannot determine .byte_length for '${ctx.result}' - type not found in registry.`,
    );
  }
 
  const bitLength = generateTypeInfoBitLength(
    typeInfo,
    ctx.subscriptDepth,
    input,
  );
  const bitValue = Number.parseInt(bitLength, 10);
  Eif (!Number.isNaN(bitValue)) {
    return String(bitValue / 8);
  }
  return bitLength.replace(".bit_length", ".byte_length");
};
 
/**
 * Get dimension value at subscript depth as string.
 */
const getDimensionAtDepth = (
  dimensions: (number | string)[],
  subscriptDepth: number,
): string => {
  const dim = dimensions[subscriptDepth];
  return typeof dim === "number" ? String(dim) : dim;
};
 
/**
 * Generate element_count for struct field.
 */
const generateStructFieldElementCount = (
  ctx: IExplicitLengthContext,
  orchestrator: IOrchestrator,
): string | null => {
  if (!ctx.previousStructType || !ctx.previousMemberName) {
    return null;
  }
 
  const fieldInfo = orchestrator.getStructFieldInfo(
    ctx.previousStructType,
    ctx.previousMemberName,
  );
 
  if (
    fieldInfo?.dimensions &&
    fieldInfo.dimensions.length > ctx.subscriptDepth
  ) {
    return getDimensionAtDepth(fieldInfo.dimensions, ctx.subscriptDepth);
  }
 
  // Non-array field - element_count not applicable
  throw new Error(
    `Error: .element_count is only available on arrays, not on '${fieldInfo?.type || ctx.previousMemberName}'.`,
  );
};
 
/**
 * Generate element_count from type info.
 */
const generateTypeInfoElementCount = (
  ctx: IExplicitLengthContext,
  _input: IGeneratorInput,
): string => {
  const typeInfo = ctx.resolvedIdentifier
    ? CodeGenState.getVariableTypeInfo(ctx.resolvedIdentifier)
    : undefined;
 
  if (!typeInfo) {
    throw new Error(
      `Error: Cannot determine .element_count for '${ctx.result}' - type not found in registry.`,
    );
  }
 
  if (!typeInfo.isArray) {
    throw new Error(
      `Error: .element_count is only available on arrays, not on '${typeInfo.baseType}'.`,
    );
  }
 
  const dims = typeInfo.arrayDimensions;
  if (!dims || dims.length === 0) {
    throw new Error(
      `Error: Cannot determine .element_count for array with unknown dimensions.`,
    );
  }
 
  Eif (ctx.subscriptDepth < dims.length) {
    return getDimensionAtDepth(dims, ctx.subscriptDepth);
  }
 
  throw new Error(
    `Error: .element_count is not available on array elements. Array is fully subscripted.`,
  );
};
 
/**
 * Generate .element_count property access (ADR-058).
 * Returns element count for arrays or argc for args.
 */
const generateElementCountProperty = (
  ctx: IExplicitLengthContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): string | null => {
  // Special case: main function's args.element_count -> argc
  if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
    return "argc";
  }
 
  // Check struct member access for array fields
  const structResult = generateStructFieldElementCount(ctx, orchestrator);
  if (structResult !== null) {
    return structResult;
  }
  Iif (ctx.previousStructType) {
    // generateStructFieldElementCount threw or returned null but struct context existed
    return null;
  }
 
  // Get type info for variable
  return generateTypeInfoElementCount(ctx, input);
};
 
/**
 * Generate .char_count property access (ADR-058).
 * Returns strlen() for strings.
 */
const generateCharCountProperty = (
  ctx: IExplicitLengthContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): string | null => {
  // Special case: main function's args
  if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
    throw new Error(
      `Error: .char_count is only available on strings, not on 'args'. Use .element_count for argc.`,
    );
  }
 
  // Check struct member access for string fields
  if (ctx.previousStructType && ctx.previousMemberName) {
    const fieldInfo = orchestrator.getStructFieldInfo(
      ctx.previousStructType,
      ctx.previousMemberName,
    );
    if (fieldInfo?.type.startsWith("string<")) {
      effects.push({ type: "include", header: "string" });
      return `strlen(${ctx.result})`;
    }
    // Non-string field
    throw new Error(
      `Error: .char_count is only available on strings, not on '${fieldInfo?.type || ctx.previousMemberName}'.`,
    );
  }
 
  // Get type info
  const typeInfo = ctx.resolvedIdentifier
    ? CodeGenState.getVariableTypeInfo(ctx.resolvedIdentifier)
    : undefined;
 
  if (!typeInfo) {
    throw new Error(
      `Error: Cannot determine .char_count for '${ctx.result}' - type not found in registry.`,
    );
  }
 
  // Must be a string type
  if (!typeInfo.isString) {
    throw new Error(
      `Error: .char_count is only available on strings, not on '${typeInfo.baseType}'.`,
    );
  }
 
  effects.push({ type: "include", header: "string" });
 
  // Check length cache first (only for simple variable access, not indexed)
  if (
    ctx.subscriptDepth === 0 &&
    ctx.resolvedIdentifier &&
    state.lengthCache?.has(ctx.resolvedIdentifier)
  ) {
    return state.lengthCache.get(ctx.resolvedIdentifier)!;
  }
 
  // Use ctx.result which contains the full expression including any subscripts
  // e.g., for arr[0].char_count, ctx.result is "arr[0]" not "arr"
  return `strlen(${ctx.result})`;
};
 
// ========================================================================
// Member Access
// ========================================================================
 
/**
 * Member access result.
 */
interface MemberAccessResult {
  result: string;
  resolvedIdentifier?: string;
  currentStructType?: string;
  currentMemberIsArray?: boolean;
  isRegisterChain?: boolean;
  isCppAccessChain?: boolean;
  previousStructType?: string;
  previousMemberName?: string;
}
 
/**
 * Context for member access generation.
 */
interface IMemberAccessContext {
  result: string;
  memberName: string;
  rootIdentifier: string | undefined;
  isStructParam: boolean;
  /** Issue #895: Force pointer semantics for callback-compatible params */
  forcePointerSemantics: boolean;
  isGlobalAccess: boolean;
  isCppAccessChain: boolean;
  currentStructType: string | undefined;
  resolvedIdentifier: string | undefined;
  previousStructType: string | undefined;
  previousMemberName: string | undefined;
  isRegisterChain: boolean;
}
 
/**
 * Initialize the default member access output from context.
 */
const initializeMemberOutput = (
  ctx: IMemberAccessContext,
): MemberAccessResult => ({
  result: ctx.result,
  resolvedIdentifier: ctx.resolvedIdentifier,
  currentStructType: ctx.currentStructType,
  currentMemberIsArray: false,
  isRegisterChain: ctx.isRegisterChain,
  isCppAccessChain: ctx.isCppAccessChain,
  previousStructType: ctx.currentStructType,
  previousMemberName: ctx.memberName,
});
 
/**
 * Generate member access (obj.field).
 * Dispatches to specialized handlers via null-coalescing chain.
 */
const generateMemberAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): MemberAccessResult => {
  // Check for enum shadowing before dispatch - catches case where identifier
  // was resolved to a scope member that shadows a global enum
  MemberAccessValidator.validateGlobalEntityAccess(
    ctx.result,
    ctx.memberName,
    "enum",
    state.currentScope,
    ctx.isGlobalAccess,
    {
      rootIdentifier: ctx.rootIdentifier,
      knownEnums: input.symbols!.knownEnums,
    },
  );
 
  return (
    tryBitmapFieldAccess(ctx, input, effects) ??
    tryScopeMemberAccess(ctx, input, state, orchestrator) ??
    tryKnownScopeAccess(ctx, input, state, orchestrator) ??
    tryEnumMemberAccess(ctx, input, state, orchestrator) ??
    tryRegisterMemberAccess(ctx, input, state) ??
    tryStructParamAccess(ctx, orchestrator) ??
    tryRegisterBitmapAccess(ctx, input, effects) ??
    tryStructBitmapAccess(ctx, input, effects) ??
    generateDefaultAccess(ctx, orchestrator)
  );
};
 
// ========================================================================
// Member Access Handlers
// ========================================================================
 
/**
 * Check for primary bitmap type field access (e.g., status.Running).
 */
const tryBitmapFieldAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  effects: TGeneratorEffect[],
): MemberAccessResult | null => {
  if (!ctx.rootIdentifier) {
    return null;
  }
  const typeInfo = CodeGenState.getVariableTypeInfo(ctx.rootIdentifier);
  if (!typeInfo?.isBitmap || !typeInfo.bitmapTypeName) {
    return null;
  }
 
  const output = initializeMemberOutput(ctx);
  const bitmapResult = BitmapAccessHelper.generate(
    ctx.result,
    ctx.memberName,
    typeInfo.bitmapTypeName,
    input.symbols!.bitmapFields,
    `type '${typeInfo.bitmapTypeName}'`,
  );
  applyAccessEffects(bitmapResult.effects, effects);
  output.result = bitmapResult.code;
  return output;
};
 
/**
 * Check for scope member access (this.member).
 */
const tryScopeMemberAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): MemberAccessResult | null => {
  if (ctx.result !== "__THIS_SCOPE__") {
    return null;
  }
  if (!state.currentScope) {
    throw new Error("Error: 'this' can only be used inside a scope");
  }
 
  const output = initializeMemberOutput(ctx);
  const fullName = `${state.currentScope}_${ctx.memberName}`;
  const constValue = input.symbols!.scopePrivateConstValues.get(fullName);
  if (constValue === undefined) {
    output.result = fullName;
    output.resolvedIdentifier = fullName;
    if (!input.symbols!.knownEnums.has(fullName)) {
      const resolvedTypeInfo = CodeGenState.getVariableTypeInfo(fullName);
      if (
        resolvedTypeInfo &&
        orchestrator.isKnownStruct(resolvedTypeInfo.baseType)
      ) {
        output.currentStructType = resolvedTypeInfo.baseType;
      }
    }
  } else {
    output.result = constValue;
    output.resolvedIdentifier = fullName;
  }
  return output;
};
 
/**
 * Check for known scope access (e.g., LED.on).
 */
const tryKnownScopeAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): MemberAccessResult | null => {
  if (!orchestrator.isKnownScope(ctx.result)) {
    return null;
  }
 
  if (!ctx.isGlobalAccess) {
    MemberAccessValidator.validateNotSelfScopeReference(
      ctx.result,
      ctx.memberName,
      state.currentScope,
    );
  }
  orchestrator.validateCrossScopeVisibility(
    ctx.result,
    ctx.memberName,
    ctx.isGlobalAccess,
  );
 
  const output = initializeMemberOutput(ctx);
  output.result = `${ctx.result}${orchestrator.getScopeSeparator(ctx.isCppAccessChain)}${ctx.memberName}`;
  output.resolvedIdentifier = output.result;
  const resolvedTypeInfo = CodeGenState.getVariableTypeInfo(output.result);
  Iif (
    resolvedTypeInfo &&
    orchestrator.isKnownStruct(resolvedTypeInfo.baseType)
  ) {
    output.currentStructType = resolvedTypeInfo.baseType;
  }
  return output;
};
 
/**
 * Check for enum member access (e.g., Color.Red).
 */
const tryEnumMemberAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): MemberAccessResult | null => {
  if (!input.symbols!.knownEnums.has(ctx.result)) {
    return null;
  }
 
  // Shadowing check already done in generateMemberAccess; this catches
  // direct conflicts where ctx.result is the enum name (no resolution happened)
  MemberAccessValidator.validateGlobalEntityAccess(
    ctx.result,
    ctx.memberName,
    "enum",
    state.currentScope,
    ctx.isGlobalAccess,
    { scopeMembers: state.scopeMembers },
  );
 
  const output = initializeMemberOutput(ctx);
  output.result = `${ctx.result}${orchestrator.getScopeSeparator(ctx.isCppAccessChain)}${ctx.memberName}`;
  return output;
};
 
/**
 * Check for register member access (e.g., GPIO.PIN0).
 */
const tryRegisterMemberAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
): MemberAccessResult | null => {
  if (!input.symbols!.knownRegisters.has(ctx.result)) {
    return null;
  }
 
  MemberAccessValidator.validateGlobalEntityAccess(
    ctx.result,
    ctx.memberName,
    "register",
    state.currentScope,
    ctx.isGlobalAccess,
    { scopeMembers: state.scopeMembers },
  );
 
  MemberAccessValidator.validateRegisterReadAccess(
    `${ctx.result}_${ctx.memberName}`,
    ctx.memberName,
    `${ctx.result}.${ctx.memberName}`,
    input.symbols!.registerMemberAccess,
    false,
  );
 
  const output = initializeMemberOutput(ctx);
  output.result = `${ctx.result}_${ctx.memberName}`;
  output.isRegisterChain = true;
  return output;
};
 
/**
 * Check for struct parameter access (e.g., point->x or point.x in C++).
 */
const tryStructParamAccess = (
  ctx: IMemberAccessContext,
  orchestrator: IOrchestrator,
): MemberAccessResult | null => {
  if (!ctx.isStructParam || ctx.result !== ctx.rootIdentifier) {
    return null;
  }
 
  // Issue #895: Force pointer semantics for callback-compatible params
  // even in C++ mode (use -> instead of .)
  const structParamSep = ctx.forcePointerSemantics
    ? "->"
    : memberAccessChain.getStructParamSeparator({
        cppMode: orchestrator.isCppMode(),
      });
 
  const output = initializeMemberOutput(ctx);
  output.result = `${ctx.result}${structParamSep}${ctx.memberName}`;
  output.previousStructType = ctx.currentStructType;
  output.previousMemberName = ctx.memberName;
  if (ctx.currentStructType) {
    const memberTypeInfo = orchestrator.getMemberTypeInfo(
      ctx.currentStructType,
      ctx.memberName,
    );
    if (memberTypeInfo) {
      output.currentMemberIsArray = memberTypeInfo.isArray;
      output.currentStructType = memberTypeInfo.baseType;
    }
  }
  return output;
};
 
/**
 * Check for register member with bitmap type (e.g., MOTOR_CTRL.Running).
 */
const tryRegisterBitmapAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  effects: TGeneratorEffect[],
): MemberAccessResult | null => {
  if (!input.symbols!.registerMemberTypes.has(ctx.result)) {
    return null;
  }
 
  const bitmapType = input.symbols!.registerMemberTypes.get(ctx.result)!;
  const output = initializeMemberOutput(ctx);
  const bitmapResult = BitmapAccessHelper.generate(
    ctx.result,
    ctx.memberName,
    bitmapType,
    input.symbols!.bitmapFields,
    `register member '${ctx.result}' (bitmap type '${bitmapType}')`,
  );
  applyAccessEffects(bitmapResult.effects, effects);
  output.result = bitmapResult.code;
  return output;
};
 
/**
 * Check for struct member with bitmap type (e.g., device.flags.Active).
 */
const tryStructBitmapAccess = (
  ctx: IMemberAccessContext,
  input: IGeneratorInput,
  effects: TGeneratorEffect[],
): MemberAccessResult | null => {
  if (
    !ctx.currentStructType ||
    !input.symbols!.bitmapFields.has(ctx.currentStructType)
  ) {
    return null;
  }
 
  const output = initializeMemberOutput(ctx);
  const bitmapResult = BitmapAccessHelper.generate(
    ctx.result,
    ctx.memberName,
    ctx.currentStructType,
    input.symbols!.bitmapFields,
    `struct member '${ctx.result}' (bitmap type '${ctx.currentStructType}')`,
  );
  applyAccessEffects(bitmapResult.effects, effects);
  output.result = bitmapResult.code;
  return output;
};
 
/**
 * Default member access (dot or :: separator with struct type tracking).
 */
const generateDefaultAccess = (
  ctx: IMemberAccessContext,
  orchestrator: IOrchestrator,
): MemberAccessResult => {
  const separator = ctx.isCppAccessChain ? "::" : ".";
  const output = initializeMemberOutput(ctx);
  output.result = `${ctx.result}${separator}${ctx.memberName}`;
  output.previousStructType = ctx.currentStructType;
  output.previousMemberName = ctx.memberName;
  if (ctx.currentStructType) {
    const memberTypeInfo = orchestrator.getMemberTypeInfo(
      ctx.currentStructType,
      ctx.memberName,
    );
    if (memberTypeInfo) {
      output.currentMemberIsArray = memberTypeInfo.isArray;
      output.currentStructType = memberTypeInfo.baseType;
      output.resolvedIdentifier = undefined;
    }
  }
  return output;
};
 
// ========================================================================
// Subscript Access
// ========================================================================
 
/**
 * Subscript access result.
 */
interface SubscriptAccessResult {
  result: string;
  currentStructType?: string;
  currentMemberIsArray?: boolean;
  remainingArrayDims?: number;
  subscriptDepth?: number;
}
 
/**
 * Context for subscript access generation.
 */
interface ISubscriptAccessContext {
  result: string;
  op: Parser.PostfixOpContext;
  rootIdentifier: string | undefined;
  primaryTypeInfo:
    | { baseType: string; arrayDimensions?: (number | string)[] }
    | undefined;
  resolvedIdentifier: string | undefined;
  currentStructType: string | undefined;
  currentMemberIsArray: boolean;
  remainingArrayDims: number;
  subscriptDepth: number;
  isRegisterChain: boolean;
}
 
/**
 * Generate subscript access (arr[i] or value[bit]).
 * Dispatches to single-index or dual-index handler.
 */
const generateSubscriptAccess = (
  ctx: ISubscriptAccessContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): SubscriptAccessResult => {
  const exprs = ctx.op.expression();
  const output: SubscriptAccessResult = {
    result: ctx.result,
    currentStructType: ctx.currentStructType,
    currentMemberIsArray: false,
    remainingArrayDims: ctx.remainingArrayDims,
    subscriptDepth: ctx.subscriptDepth,
  };
 
  if (exprs.length === 1) {
    return handleSingleSubscript(ctx, exprs[0], input, orchestrator, output);
  E} else if (exprs.length === 2) {
    return handleBitRangeSubscript(
      ctx,
      exprs,
      input,
      state,
      orchestrator,
      effects,
      output,
    );
  }
 
  return output;
};
 
/**
 * Handle single-index subscript (arr[i] or value[bit]).
 */
const handleSingleSubscript = (
  ctx: ISubscriptAccessContext,
  expr: Parser.ExpressionContext,
  input: IGeneratorInput,
  orchestrator: IOrchestrator,
  output: SubscriptAccessResult,
): SubscriptAccessResult => {
  // Set expectedType to size_t (unsigned) for array indices per MISRA 7.2
  // This ensures index literals get U suffix regardless of element type
  const index = CodeGenState.withExpectedType("size_t", () =>
    orchestrator.generateExpression(expr),
  );
 
  // Check if result is a register member with bitmap type (throws)
  validateNotBitmapMember(ctx, input);
 
  const isRegisterAccess = checkRegisterAccess(ctx, input);
  const identifierTypeInfo = getIdentifierTypeInfo(ctx, input);
 
  // Register access: bit extraction
  if (isRegisterAccess) {
    // Skip shift when index is 0 (either "0" or "0U" with MISRA suffix)
    let expr =
      index === "0" || index === "0U"
        ? `((${ctx.result}) & 1)`
        : `((${ctx.result} >> ${index}) & 1)`;
    // MISRA 10.3: Add narrowing cast if expected type is narrower than int
    const targetType = CodeGenState.expectedType;
    Iif (targetType) {
      expr = NarrowingCastHelper.wrap(expr, "int", targetType);
    }
    output.result = expr;
    return output;
  }
 
  // Member array access
  if (ctx.currentMemberIsArray) {
    output.result = `${ctx.result}[${index}]`;
    output.currentMemberIsArray = false;
    output.subscriptDepth = ctx.subscriptDepth + 1;
    return output;
  }
 
  // Multi-dimensional array access
  if (ctx.remainingArrayDims > 0) {
    return handleRemainingArrayDims(ctx, index, output);
  }
 
  // Primitive int member: bit access
  const isPrimitiveIntMember =
    ctx.currentStructType && TypeCheckUtils.isInteger(ctx.currentStructType);
  Iif (isPrimitiveIntMember) {
    // Skip shift when index is 0 (either "0" or "0U" with MISRA suffix)
    let expr =
      index === "0" || index === "0U"
        ? `((${ctx.result}) & 1)`
        : `((${ctx.result} >> ${index}) & 1)`;
    // MISRA 10.3: Add narrowing cast if expected type is narrower than int
    const targetType = CodeGenState.expectedType;
    if (targetType) {
      expr = NarrowingCastHelper.wrap(expr, "int", targetType);
    }
    output.result = expr;
    output.currentStructType = undefined;
    return output;
  }
 
  // Primary array access
  if (identifierTypeInfo?.isArray) {
    return handlePrimaryArraySubscript(
      ctx,
      index,
      identifierTypeInfo,
      orchestrator,
      output,
    );
  }
 
  // Default: classify subscript type
  return handleDefaultSubscript(ctx, index, identifierTypeInfo, output);
};
 
/**
 * Validate that result is not a bitmap member (which requires named access).
 */
const validateNotBitmapMember = (
  ctx: ISubscriptAccessContext,
  input: IGeneratorInput,
): void => {
  if (!input.symbols!.registerMemberTypes.has(ctx.result)) return;
 
  const bitmapType = input.symbols!.registerMemberTypes.get(ctx.result)!;
  const line = ctx.op.start?.line ?? 0;
  throw new Error(
    `Error at line ${line}: Cannot use bracket indexing on bitmap type '${bitmapType}'. ` +
      `Use named field access instead (e.g., ${ctx.result.split("_").at(-1)}.FIELD_NAME).`,
  );
};
 
/**
 * Check if this is a register access (bit extraction).
 */
const checkRegisterAccess = (
  ctx: ISubscriptAccessContext,
  input: IGeneratorInput,
): boolean => {
  if (ctx.isRegisterChain) return true;
  if (!ctx.rootIdentifier) return false;
  return input.symbols!.knownRegisters.has(ctx.rootIdentifier);
};
 
/**
 * Get type info for the identifier being subscripted.
 */
const getIdentifierTypeInfo = (
  ctx: ISubscriptAccessContext,
  _input: IGeneratorInput,
): TTypeInfo | undefined => {
  const identifierToCheck = ctx.resolvedIdentifier || ctx.rootIdentifier;
  return identifierToCheck
    ? CodeGenState.getVariableTypeInfo(identifierToCheck)
    : undefined;
};
 
/**
 * Handle subscript on array with remaining dimensions.
 */
const handleRemainingArrayDims = (
  ctx: ISubscriptAccessContext,
  index: string,
  output: SubscriptAccessResult,
): SubscriptAccessResult => {
  output.result = `${ctx.result}[${index}]`;
  output.remainingArrayDims = ctx.remainingArrayDims - 1;
  output.subscriptDepth = ctx.subscriptDepth + 1;
 
  if (output.remainingArrayDims === 0 && ctx.primaryTypeInfo) {
    output.currentStructType = ctx.primaryTypeInfo.baseType;
  }
  return output;
};
 
/**
 * Handle subscript on a primary array.
 */
const handlePrimaryArraySubscript = (
  ctx: ISubscriptAccessContext,
  index: string,
  typeInfo: TTypeInfo,
  orchestrator: IOrchestrator,
  output: SubscriptAccessResult,
): SubscriptAccessResult => {
  output.result = `${ctx.result}[${index}]`;
  output.subscriptDepth = ctx.subscriptDepth + 1;
 
  // Update struct type if element is a known struct
  Eif (!ctx.currentStructType) {
    const elementType = typeInfo.baseType;
    Iif (orchestrator.isKnownStruct(elementType)) {
      output.currentStructType = elementType;
    }
  }
  return output;
};
 
/**
 * Handle default subscript (classify and apply).
 */
const handleDefaultSubscript = (
  ctx: ISubscriptAccessContext,
  index: string,
  typeInfo: TTypeInfo | undefined,
  output: SubscriptAccessResult,
): SubscriptAccessResult => {
  const subscriptKind = SubscriptClassifier.classify({
    typeInfo: typeInfo ?? null,
    subscriptCount: 1,
    isRegisterAccess: false,
  });
 
  if (subscriptKind === "bit_single") {
    // Skip shift when index is 0 (either "0" or "0U" with MISRA suffix)
    let expr =
      index === "0" || index === "0U"
        ? `((${ctx.result}) & 1)`
        : `((${ctx.result} >> ${index}) & 1)`;
    // MISRA 10.3: Add narrowing cast if expected type is narrower than int
    const targetType = CodeGenState.expectedType;
    if (targetType) {
      expr = NarrowingCastHelper.wrap(expr, "int", targetType);
    }
    output.result = expr;
  } else {
    output.result = `${ctx.result}[${index}]`;
  }
 
  return output;
};
 
/**
 * Handle dual-index subscript (value[start, width] — bit range).
 */
const handleBitRangeSubscript = (
  ctx: ISubscriptAccessContext,
  exprs: Parser.ExpressionContext[],
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
  output: SubscriptAccessResult,
): SubscriptAccessResult => {
  // Set expectedType to size_t (unsigned) for bit indices per MISRA 7.2
  // Bit positions are inherently unsigned values
  const [start, width] = CodeGenState.withExpectedType("size_t", () => [
    orchestrator.generateExpression(exprs[0]),
    orchestrator.generateExpression(exprs[1]),
  ]);
 
  const isFloatType =
    ctx.primaryTypeInfo?.baseType === "f32" ||
    ctx.primaryTypeInfo?.baseType === "f64";
 
  if (isFloatType && ctx.rootIdentifier) {
    output.result = handleFloatBitRange(
      {
        result: ctx.result,
        rootIdentifier: ctx.rootIdentifier,
        baseType: ctx.primaryTypeInfo!.baseType,
        start,
        width,
      },
      state,
      orchestrator,
      effects,
    );
  } else {
    const mask = orchestrator.generateBitMask(width);
    // Skip shift when start is 0 (either "0" or "0U" with MISRA suffix)
    let expr: string;
    if (start === "0" || start === "0U") {
      expr = `((${ctx.result}) & ${mask})`;
    } else {
      expr = `((${ctx.result} >> ${start}) & ${mask})`;
    }
 
    // MISRA 10.3: Add narrowing cast if expected type is known
    // Bit operations promote to int, so wrap with cast when assigning to narrower types
    const targetType = CodeGenState.expectedType;
    if (targetType && ctx.primaryTypeInfo?.baseType) {
      const promotedSourceType = NarrowingCastHelper.getPromotedType(
        ctx.primaryTypeInfo.baseType,
      );
      output.result = NarrowingCastHelper.wrap(
        expr,
        promotedSourceType,
        targetType,
      );
    } else {
      output.result = expr;
    }
  }
 
  return output;
};
 
/**
 * Context for float bit range access.
 */
interface IFloatBitRangeContext {
  result: string;
  rootIdentifier: string;
  baseType: string;
  start: string;
  width: string;
}
 
/**
 * Get the C float type name for a C-Next float type.
 */
const getFloatTypeName = (baseType: string): string => {
  return baseType === "f64" ? "double" : "float";
};
 
/**
 * Handle float bit range access with union-based type punning.
 * Uses union { float f; uint32_t u; } for MISRA C:2012 Rule 21.15 compliance.
 */
const handleFloatBitRange = (
  ctx: IFloatBitRangeContext,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): string => {
  if (!state.inFunctionBody) {
    throw new Error(
      `Float bit indexing reads (${ctx.rootIdentifier}[${ctx.start}, ${ctx.width}]) cannot be used at global scope.`,
    );
  }
 
  effects.push({ type: "include", header: "float_static_assert" });
 
  const isF64 = ctx.baseType === "f64";
  const floatType = getFloatTypeName(ctx.baseType);
  const intType = isF64 ? "uint64_t" : "uint32_t";
  const shadowName = `__bits_${ctx.rootIdentifier}`;
  const mask = orchestrator.generateBitMask(ctx.width, isF64);
 
  const needsDeclaration = !orchestrator.hasFloatBitShadow(shadowName);
  if (needsDeclaration) {
    orchestrator.registerFloatBitShadow(shadowName);
    // Emit union declaration: union { float f; uint32_t u; } __bits_name;
    orchestrator.addPendingTempDeclaration(
      `union { ${floatType} f; ${intType} u; } ${shadowName};`,
    );
  }
 
  const shadowIsCurrent = orchestrator.isFloatShadowCurrent(shadowName);
  orchestrator.markFloatShadowCurrent(shadowName);
 
  // If shadow is not current, emit assignment: __bits_name.f = floatVar;
  if (!shadowIsCurrent) {
    orchestrator.addPendingTempDeclaration(`${shadowName}.f = ${ctx.result};`);
  }
 
  // Return just the bit read expression using union member .u
  // Skip shift when start is 0 (either "0" or "0U" with MISRA suffix)
  if (ctx.start === "0" || ctx.start === "0U") {
    return `(${shadowName}.u & ${mask})`;
  }
  return `((${shadowName}.u >> ${ctx.start}) & ${mask})`;
};
 
// ========================================================================
// Utilities
// ========================================================================
 
/**
 * Apply effects from access generators.
 */
const applyAccessEffects = (
  sourceEffects: readonly TGeneratorEffect[],
  targetEffects: TGeneratorEffect[],
): void => {
  for (const effect of sourceEffects) {
    targetEffects.push(effect);
  }
};
 
export default generatePostfixExpression;