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

94.22% Statements 375/398
84.27% Branches 268/318
100% Functions 36/36
94.4% Lines 371/393

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                                                                                                            13x                   1799x       1799x       1799x       1799x       1799x     1799x 1799x 2x     1799x                                                                                         13x           1803x   1803x 1803x     1803x 1803x     1803x     1803x   1803x     1803x 4x   1799x     1799x       1803x                 1803x                 1803x 442x 280x 280x 162x 76x                                     76x 76x 76x   76x   76x     86x             86x 86x         1787x 2x               1785x                     13x           280x                 27x       252x                 2x       249x                     34x       215x                                       215x 215x   280x 280x   280x   280x   280x 280x           13x             280x 252x     28x 28x 28x     28x 1x           27x 1x   27x 1x       27x 27x 1x     27x             13x             252x 249x   3x 1x   2x 2x       2x 2x 2x 2x       1x   2x                       13x           4x 4x 4x 2x       2x 2x       2x 2x 2x 2x                                   13x                 249x 30x                           30x 30x 30x 30x 30x         219x 2x           2x 2x 2x 2x     217x 2x           2x 2x 2x 2x     215x                                             13x               30x 1x       29x 4x       4x 4x                       25x       30x 1x     24x                           13x               4x 4x 4x   4x 1x 1x         3x 1x 1x 2x         1x 1x             1x             13x                                     24x 17x                   7x 1x       6x 1x       5x 5x         5x 4x       1x           13x                 17x     17x 2x       15x 3x   12x               13x                         1x         1x           1x 1x         1x 1x               13x 1x 1x       1x 1x                                                                                       13x   210x                             13x             215x                                 13x         215x 57x   158x 158x 154x     4x 4x             4x 4x 4x           13x           211x 181x   30x 1x     29x 29x 29x 29x 28x 28x 28x 14x 14x       1x       1x 1x   29x           13x           181x 151x     30x 25x           29x           29x 29x 29x 29x 29x           29x           13x           151x 68x     83x               83x 83x 83x           13x         68x 63x     5x               5x               5x 5x 5x 5x           13x       63x 34x     29x       29x 29x 29x 29x 29x 27x       27x 27x 27x     29x           13x         34x 32x     2x 2x 2x             2x 2x 2x           13x         32x       30x     2x 2x             2x 2x 2x           13x       30x 30x 30x 30x 30x 30x 26x       26x 26x 26x 26x     30x                                                                               13x             76x 76x               76x 36x 40x 40x                                 13x             36x     36x   36x 36x     36x 1x 1x       34x 2x 2x 2x 2x       32x 26x         6x 36x             6x 1x                   5x           13x       36x   1x 1x 36x                 13x       35x 34x 33x           13x       35x 35x               13x         26x 26x 26x   26x 21x   26x           13x             1x 1x     1x 1x 1x       1x           13x           5x           5x         5x           13x                 40x 40x     40x     40x 20x                         20x 20x 10x   10x       39x                                 13x           20x 1x         19x         19x 19x 20x 20x   20x 20x 15x 15x     19x 19x   19x 4x 1x   3x   15x 13x   2x                   13x       95x            
/**
 * 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 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";
 
// ========================================================================
// 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
    ? input.typeRegistry.get(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;
  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 #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
    ? input.typeRegistry.get(rootIdentifier)
    : undefined;
 
  const tracking = initializeTrackingState(
    rootIdentifier,
    result,
    primaryTypeInfo,
    input,
    state,
    orchestrator,
  );
 
  const postfixCtx: IPostfixContext = {
    rootIdentifier,
    isStructParam,
    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)
  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,
      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 = input.typeRegistry.get(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 = input.typeRegistry.get(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 ? input.typeRegistry.get(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;
};
 
/**
 * Try handling property access (.length, .capacity, .size).
 * Returns true if handled.
 */
const tryPropertyAccess = (
  memberName: string,
  tracking: ITrackingState,
  rootIdentifier: string | undefined,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): boolean => {
  if (memberName === "length") {
    const lengthResult = generateLengthProperty(
      {
        result: tracking.result,
        rootIdentifier,
        resolvedIdentifier: tracking.resolvedIdentifier,
        previousStructType: tracking.previousStructType,
        previousMemberName: tracking.previousMemberName,
        subscriptDepth: tracking.subscriptDepth,
      },
      input,
      state,
      orchestrator,
      effects,
    );
    Eif (lengthResult !== null) {
      tracking.result = lengthResult;
      tracking.previousStructType = undefined;
      tracking.previousMemberName = undefined;
      return true;
    }
    return false;
  }
 
  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;
};
 
// ========================================================================
// Length Property
// ========================================================================
 
/**
 * Context for .length property generation.
 */
interface ILengthContext {
  result: string;
  rootIdentifier: string | undefined;
  resolvedIdentifier: string | undefined;
  previousStructType: string | undefined;
  previousMemberName: string | undefined;
  subscriptDepth: number;
}
 
/**
 * Generate .length property access.
 * Returns null if not applicable (falls through to member access).
 */
const generateLengthProperty = (
  ctx: ILengthContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): string | null => {
  // Special case: main function's args.length -> argc
  if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
    return "argc";
  }
 
  // Check if we're accessing a struct member (cfg.magic.length)
  if (ctx.previousStructType && ctx.previousMemberName) {
    const fieldInfo = orchestrator.getStructFieldInfo(
      ctx.previousStructType,
      ctx.previousMemberName,
    );
    Eif (fieldInfo) {
      return generateStructFieldLength(
        ctx.result,
        fieldInfo,
        ctx.subscriptDepth,
        input,
        orchestrator,
        effects,
      );
    }
  }
 
  // Fall back to checking the current resolved identifier's type
  const typeInfo = ctx.resolvedIdentifier
    ? input.typeRegistry.get(ctx.resolvedIdentifier)
    : undefined;
 
  if (!typeInfo) {
    return `/* .length: unknown type for ${ctx.result} */0`;
  }
 
  return generateTypeInfoLength(
    ctx.result,
    typeInfo,
    ctx.subscriptDepth,
    ctx.resolvedIdentifier,
    input,
    state,
    effects,
  );
};
 
/**
 * Generate .length for a struct field.
 */
const generateStructFieldLength = (
  result: string,
  fieldInfo: { type: string; dimensions?: (number | string)[] },
  subscriptDepth: number,
  input: IGeneratorInput,
  orchestrator: IOrchestrator,
  effects: TGeneratorEffect[],
): string => {
  const memberType = fieldInfo.type;
  const dimensions = fieldInfo.dimensions;
  const isStringField = TypeCheckUtils.isString(memberType);
 
  if (dimensions?.length && dimensions.length > 1 && isStringField) {
    if (subscriptDepth === 0) {
      return String(dimensions[0]);
    } else E{
      effects.push({ type: "include", header: "string" });
      return `strlen(${result})`;
    }
  } else if (dimensions?.length === 1 && isStringField) {
    effects.push({ type: "include", header: "string" });
    return `strlen(${result})`;
  } else if (
    dimensions?.length &&
    dimensions.length > 0 &&
    subscriptDepth < dimensions.length
  ) {
    return String(dimensions[subscriptDepth]);
  I} else if (
    dimensions?.length &&
    dimensions.length > 0 &&
    subscriptDepth >= dimensions.length
  ) {
    return getTypeBitWidth(memberType, input);
  } else {
    return getTypeBitWidth(memberType, input);
  }
};
 
/**
 * Generate .length from type info.
 */
const generateTypeInfoLength = (
  result: string,
  typeInfo: {
    isString?: boolean;
    isArray?: boolean;
    isEnum?: boolean;
    arrayDimensions?: (number | string)[];
    baseType: string;
    bitWidth?: number;
    isBitmap?: boolean;
    bitmapTypeName?: string;
  },
  subscriptDepth: number,
  resolvedIdentifier: string | undefined,
  input: IGeneratorInput,
  state: IGeneratorState,
  effects: TGeneratorEffect[],
): string => {
  // ADR-045: String type handling
  if (typeInfo.isString) {
    return generateStringLength(
      result,
      typeInfo,
      subscriptDepth,
      resolvedIdentifier,
      state,
    );
  }
 
  // Non-string enum - always 32 bits
  if (typeInfo.isEnum && !typeInfo.isArray) {
    return "32";
  }
 
  // Non-string, non-enum, non-array - use bitWidth
  if (!typeInfo.isArray) {
    return String(typeInfo.bitWidth || 0);
  }
 
  // Array without dimensions - unknown length
  const dims = typeInfo.arrayDimensions;
  Iif (!dims || dims.length === 0) {
    return `/* .length unknown for ${resolvedIdentifier} */0`;
  }
 
  // Array with subscript within bounds - return that dimension
  if (subscriptDepth < dims.length) {
    return String(dims[subscriptDepth]);
  }
 
  // Subscript past array bounds - return element type's length
  return generateElementTypeLength(result, typeInfo, input, effects);
};
 
/**
 * Generate .length for string types.
 */
const generateStringLength = (
  result: string,
  typeInfo: {
    arrayDimensions?: (number | string)[];
  },
  subscriptDepth: number,
  resolvedIdentifier: string | undefined,
  state: IGeneratorState,
): string => {
  const dims = typeInfo.arrayDimensions;
 
  // String array (2D): first dimension is array size, second is string capacity
  if (dims && dims.length > 1) {
    return subscriptDepth === 0 ? String(dims[0]) : `strlen(${result})`;
  }
 
  // Simple string: check length cache first, then use strlen
  if (resolvedIdentifier && state.lengthCache?.has(resolvedIdentifier)) {
    return state.lengthCache.get(resolvedIdentifier)!;
  }
  return resolvedIdentifier
    ? `strlen(${resolvedIdentifier})`
    : `strlen(${result})`;
};
 
/**
 * Generate .length for array element types (subscript past bounds).
 */
const generateElementTypeLength = (
  result: string,
  typeInfo: {
    isEnum?: boolean;
    isString?: boolean;
    baseType: string;
    isBitmap?: boolean;
    bitmapTypeName?: string;
  },
  input: IGeneratorInput,
  effects: TGeneratorEffect[],
): string => {
  // Enum element
  Iif (typeInfo.isEnum) {
    return "32";
  }
 
  // String element
  Iif (TypeCheckUtils.isString(typeInfo.baseType) || typeInfo.isString) {
    effects.push({ type: "include", header: "string" });
    return `strlen(${result})`;
  }
 
  // Numeric/bitmap element - get bit width
  let elementBitWidth = TYPE_WIDTH[typeInfo.baseType] || 0;
  Iif (elementBitWidth === 0 && typeInfo.isBitmap && typeInfo.bitmapTypeName) {
    elementBitWidth =
      input.symbols!.bitmapBitWidth.get(typeInfo.bitmapTypeName) || 0;
  }
 
  Eif (elementBitWidth > 0) {
    return String(elementBitWidth);
  }
  return `/* .length: unsupported element type ${typeInfo.baseType} */0`;
};
 
/**
 * Get bit width for a type.
 */
const getTypeBitWidth = (typeName: string, input: IGeneratorInput): string => {
  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;
  }
  if (bitWidth > 0) {
    return String(bitWidth);
  } else E{
    return `/* .length: unsupported type ${typeName} */0`;
  }
};
 
// ========================================================================
// 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;
  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 =>
  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 = input.typeRegistry.get(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 = input.typeRegistry.get(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 = input.typeRegistry.get(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;
  }
 
  MemberAccessValidator.validateGlobalEntityAccess(
    ctx.result,
    ctx.memberName,
    "enum",
    state.currentScope,
    ctx.isGlobalAccess,
  );
 
  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,
  );
 
  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;
  }
 
  const structParamSep = 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,
    );
    Eif (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,
    );
    Eif (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 => {
  const index = 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) {
    output.result = `((${ctx.result} >> ${index}) & 1)`;
    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) {
    output.result = `((${ctx.result} >> ${index}) & 1)`;
    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
    ? input.typeRegistry.get(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,
  });
 
  output.result =
    subscriptKind === "bit_single"
      ? `((${ctx.result} >> ${index}) & 1)`
      : `${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 => {
  const start = orchestrator.generateExpression(exprs[0]);
  const width = 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);
    if (start === "0") {
      output.result = `((${ctx.result}) & ${mask})`;
    } else {
      output.result = `((${ctx.result} >> ${start}) & ${mask})`;
    }
  }
 
  return output;
};
 
/**
 * Context for float bit range access.
 */
interface IFloatBitRangeContext {
  result: string;
  rootIdentifier: string;
  baseType: string;
  start: string;
  width: string;
}
 
/**
 * Handle float bit range access with memcpy shadow variable.
 */
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: "string" },
    { type: "include", header: "float_static_assert" },
  );
 
  const isF64 = ctx.baseType === "f64";
  const shadowType = 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);
    orchestrator.addPendingTempDeclaration(`${shadowType} ${shadowName};`);
  }
 
  const shadowIsCurrent = orchestrator.isFloatShadowCurrent(shadowName);
  orchestrator.markFloatShadowCurrent(shadowName);
 
  if (shadowIsCurrent) {
    if (ctx.start === "0") {
      return `(${shadowName} & ${mask})`;
    }
    return `((${shadowName} >> ${ctx.start}) & ${mask})`;
  }
  if (ctx.start === "0") {
    return `(memcpy(&${shadowName}, &${ctx.result}, sizeof(${ctx.result})), (${shadowName} & ${mask}))`;
  }
  return `(memcpy(&${shadowName}, &${ctx.result}, sizeof(${ctx.result})), ((${shadowName} >> ${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;