All files / TRANSPILE/2-Plan AssignmentClassifier.ts

94.31% Statements 249/264
92% Branches 253/275
100% Functions 32/32
94.04% Lines 237/252

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                                          50x                                                                                               393x     393x       216x                         296x 218x   78x                     478x 478x 16x         462x 462x 21x       441x 441x 25x       416x 416x 49x       367x 367x 62x       305x       305x 11x         294x 11x       283x                       478x 377x     101x 101x       101x 74x             27x 13x                 14x 13x     1x                     74x 71x     3x         3x       3x                               13x 1x         1x 1x         1x 1x             12x 6x     6x       6x       6x         6x 1x     5x                   13x 13x 2x         11x 11x       11x         11x       11x         11x 11x                             462x 425x       37x 4x     33x 33x                 33x         33x 9x           24x           24x 5x         19x 3x       16x 2x             14x 14x                                   2x       2x     2x       1x     1x                     40x     40x 7x 7x 6x             34x 6x         28x                       14x       14x 12x     2x         2x 2x                         441x 399x     42x 10x     32x 15x     17x                   10x   10x               7x         7x 3x           4x           4x                             4x 3x                 1x     3x                                                                           28x 28x 28x 20x           8x 2x             6x 5x           1x                   15x       15x 15x         15x 7x               8x       5x         5x 5x       3x                                     7x 2x 1x   2x                 5x                                 416x 106x     310x 261x     49x 49x                                                         62x 62x       62x               62x         62x                               62x 62x           62x   62x   10x   3x         12x             38x 6x     32x         5x   27x     2x                     367x 266x     101x 101x 2x           99x 367x 10x     89x 52x     37x                                           173x 132x 128x 124x                 305x 201x 201x                       299x 12x 12x                     297x 3x 3x                         78x 11x   67x                             78x       78x 11x               67x       78x                     296x 229x   67x         67x 11x   56x                           295x           284x   11x         11x       11x 11x 11x 11x         295x           295x                         305x 305x     299x       299x     297x 297x     296x 296x         296x     295x         295x   294x                       23x 23x 18x   5x                       17x 17x          
/**
 * Assignment classifier for dispatch-based code generation (ADR-065).
 *
 * Analyzes an assignment context and determines which AssignmentKind it is.
 * The classification order matches the original generateAssignment() method's
 * if-else chain to ensure identical behavior.
 *
 * Migrated to use CodeGenState instead of constructor DI.
 */
import AssignmentKind from "../../types/AssignmentKind";
import IAssignmentContext from "./types/IAssignmentContext";
import invariant from "../../utils/invariant";
import SubscriptDepthValidator from "./SubscriptDepthValidator";
import TTypeInfo from "../../types/TTypeInfo";
import OperandTyper from "../../utils/OperandTyper";
import TypeCheckUtils from "../../utils/TypeCheckUtils";
import QualifiedCName from "../../utils/QualifiedCName";
import ScopeUtils from "../../utils/ScopeUtils";
import type TranspileState from "../TranspileState";
 
/** ADR-044: the clamp helper each overflowing compound operator lowers to. */
const CLAMP_HELPER_FOR_COMPOUND: Readonly<Partial<Record<string, string>>> = {
  "+=": "add",
  "-=": "sub",
  "*=": "mul",
};
 
/**
 * Classifies assignment statements by analyzing their structure.
 *
 * Classification priority (higher = checked first):
 * 1. Bitmap field assignments (memberAccess patterns)
 * 2. Register bit/bitmap assignments
 * 3. Global/this prefix patterns
 * 4. Array/bit access patterns
 * 5. Atomic/overflow special cases
 * 6. String assignments
 * 7. Simple fallback
 */
class AssignmentClassifier {
  /**
   * Check if typeInfo represents a simple string type (not a 2D+ string array).
   */
  /**
   * The type info of the assignment TARGET, for the three simple patterns.
   *
   * #1450: one decision, and it was derived twice. `classifySpecialCompound`
   * resolved it across three branches to classify atomics and overflow clamps;
   * the three string classifiers resolved it again, branch for branch, sixty
   * lines below. They agreed, which is the failure mode rather than the
   * defense -- changing how a target resolves (qualifying `global.member`, say)
   * meant editing both, and nothing said so.
   *
   * The pattern GUARD stays with each caller, because the pattern is what picks
   * the `AssignmentKind`. Only the resolution is shared: what a target is named
   * is one question, and which kind that makes the assignment is another.
   *
   * `undefined` for a target that is none of the three, which is exactly what
   * its callers already treated a missing type info as.
   *
   * #1668 (C7): the resolution is the target's binding now, made once where
   * the target is typed. This used to re-spell the target as a registry key --
   * the bare name, or `qualifyInScope` for `this.` -- and a bare spelling of a
   * scope member only agreed with the qualified one because an unrelated
   * cross-file fallback caught the registry's miss. The binder reads `this.`
   * and `global.` off the target itself, so there is no key to get right.
   */
  static targetTypeInfo(ctx: IAssignmentContext): TTypeInfo | undefined {
    const isSimple =
      ctx.isSimpleIdentifier ||
      ctx.isSimpleThisAccess ||
      ctx.isSimpleGlobalAccess;
    return isSimple ? ctx.target.typeInfo : undefined;
  }
 
  private static isSimpleStringType(typeInfo: TTypeInfo | undefined): boolean {
    return (
      typeInfo?.isString === true &&
      typeInfo.stringCapacity !== undefined &&
      (!typeInfo.arrayDimensions || typeInfo.arrayDimensions.length <= 1)
    );
  }
 
  /**
   * Extract struct name and field name from a 2-identifier context.
   */
  private static getStructFieldNames(
    ctx: IAssignmentContext,
  ): { structName: string; fieldName: string } | null {
    if (ctx.identifiers.length !== 2) {
      return null;
    }
    return { structName: ctx.identifiers[0], fieldName: ctx.identifiers[1] };
  }
 
  /**
   * Classify an assignment context into an AssignmentKind.
   */
  static classify(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind {
    // === Priority 1: Bitmap field assignments ===
    const bitmapKind = AssignmentClassifier.classifyBitmapField(ctx, state);
    if (bitmapKind !== null) {
      return bitmapKind;
    }
 
    // === Priority 2: Member access with subscripts (arrays, register bits) ===
    const memberSubscriptKind =
      AssignmentClassifier.classifyMemberWithSubscript(ctx, state);
    if (memberSubscriptKind !== null) {
      return memberSubscriptKind;
    }
 
    // === Priority 3: Global/this prefix patterns ===
    const prefixKind = AssignmentClassifier.classifyPrefixPattern(ctx, state);
    if (prefixKind !== null) {
      return prefixKind;
    }
 
    // === Priority 4: Simple array/bit access ===
    const arrayBitKind = AssignmentClassifier.classifyArrayOrBitAccess(ctx);
    if (arrayBitKind !== null) {
      return arrayBitKind;
    }
 
    // === Priority 5: Atomic/overflow compound assignments ===
    const specialKind = AssignmentClassifier.classifySpecialCompound(ctx);
    if (specialKind !== null) {
      return specialKind;
    }
 
    // === Priority 6: String assignments ===
    const stringKind = AssignmentClassifier.classifyStringAssignment(
      ctx,
      state,
    );
    if (stringKind !== null) {
      return stringKind;
    }
 
    // === Priority 7: Member chain fallback ===
    // Any member access with subscripts that didn't match a more specific pattern
    if (ctx.hasMemberAccess && ctx.hasArrayAccess) {
      return AssignmentKind.MEMBER_CHAIN;
    }
 
    // === Fallback: Simple assignment ===
    return AssignmentKind.SIMPLE;
  }
 
  /**
   * Classify bitmap field assignments.
   * Patterns: var.field, struct.bitmapMember.field, REG.MEMBER.field, Scope.REG.MEMBER.field
   */
  private static classifyBitmapField(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind | null {
    // Must have member access without subscripts
    if (!ctx.hasMemberAccess || ctx.hasArrayAccess) {
      return null;
    }
 
    const ids = ctx.identifiers;
    Iif (ctx.subscriptCount !== 0) {
      return null;
    }
 
    if (ids.length === 2) {
      return AssignmentClassifier.classifySimpleBitmapField(
        ctx.target.rootTypeInfo,
        ids[1],
        state,
      );
    }
 
    if (ids.length === 3) {
      return AssignmentClassifier.classifyThreeIdBitmapField(
        ids[0],
        ids[1],
        ids[2],
        ctx.target.rootTypeInfo,
        state,
      );
    }
 
    if (ids.length === 4) {
      return AssignmentClassifier.classifyScopedRegisterBitmapField(ids, state);
    }
 
    return null;
  }
 
  /**
   * Classify 2-id bitmap field: var.field
   */
  private static classifySimpleBitmapField(
    typeInfo: TTypeInfo | undefined,
    fieldName: string,
    state: TranspileState,
  ): AssignmentKind | null {
    if (!typeInfo?.isBitmap || !typeInfo.bitmapTypeName) {
      return null;
    }
 
    const width = AssignmentClassifier.lookupBitmapFieldWidth(
      typeInfo.bitmapTypeName,
      fieldName,
      state,
    );
    Iif (width === null) {
      return null;
    }
 
    return width === 1
      ? AssignmentKind.BITMAP_FIELD_SINGLE_BIT
      : AssignmentKind.BITMAP_FIELD_MULTI_BIT;
  }
 
  /**
   * Classify 3-id bitmap field: REG.MEMBER.field or struct.bitmapMember.field
   */
  private static classifyThreeIdBitmapField(
    firstName: string,
    secondName: string,
    fieldName: string,
    structTypeInfo: TTypeInfo | undefined,
    state: TranspileState,
  ): AssignmentKind | null {
    // Check if register member bitmap field: REG.MEMBER.field
    if (state.symbols!.knownRegisters.has(firstName)) {
      const bitmapType = AssignmentClassifier.lookupRegisterMemberBitmapType(
        firstName,
        secondName,
        state,
      );
      Eif (bitmapType) {
        const width = AssignmentClassifier.lookupBitmapFieldWidth(
          bitmapType,
          fieldName,
          state,
        );
        Eif (width !== null) {
          return AssignmentKind.REGISTER_MEMBER_BITMAP_FIELD;
        }
      }
      return null;
    }
 
    // Check if struct member bitmap field: struct.bitmapMember.field
    if (!structTypeInfo || !state.isKnownStruct(structTypeInfo.baseType)) {
      return null;
    }
 
    const memberInfo = state.getMemberTypeInfo(
      structTypeInfo.baseType,
      secondName,
    );
    Iif (!memberInfo) {
      return null;
    }
 
    const width = AssignmentClassifier.lookupBitmapFieldWidth(
      memberInfo.baseType,
      fieldName,
      state,
    );
    if (width !== null) {
      return AssignmentKind.STRUCT_MEMBER_BITMAP_FIELD;
    }
 
    return null;
  }
 
  /**
   * Classify 4-id scoped register bitmap field: Scope.REG.MEMBER.field
   */
  private static classifyScopedRegisterBitmapField(
    ids: readonly string[],
    state: TranspileState,
  ): AssignmentKind | null {
    const scopeName = ids[0];
    if (!state.isKnownScope(scopeName)) {
      return null;
    }
 
    // #1285: textual candidate built from parse-tree identifiers, not scope
    // qualification.
    const fullRegName = QualifiedCName.fromParts([scopeName, ids[1]]);
    Iif (!state.symbols!.knownRegisters.has(fullRegName)) {
      return null;
    }
 
    const bitmapType = AssignmentClassifier.lookupRegisterMemberBitmapType(
      fullRegName,
      ids[2],
      state,
    );
    Iif (!bitmapType) {
      return null;
    }
 
    const width = AssignmentClassifier.lookupBitmapFieldWidth(
      bitmapType,
      ids[3],
      state,
    );
    Eif (width !== null) {
      return AssignmentKind.SCOPED_REGISTER_MEMBER_BITMAP_FIELD;
    }
 
    return null;
  }
 
  /**
   * Classify member access with subscripts.
   * Patterns: arr[i][j], struct.arr[i], REG.MEMBER[bit], matrix[i][j][bit]
   */
  private static classifyMemberWithSubscript(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind | null {
    // Need subscripts through memberAccess pattern
    if (!ctx.hasMemberAccess || ctx.subscriptCount === 0) {
      return null;
    }
 
    // Skip this.* and global.* patterns - they're handled by classifyPrefixPattern
    if (ctx.hasThis || ctx.hasGlobal) {
      return null;
    }
 
    const ids = ctx.identifiers;
    const typeInfo = ctx.target.rootTypeInfo;
 
    // Registers are asked FIRST, before any subscript-shape test. A bit range
    // is two expressions in ONE op, so the struct-chain branch below claimed
    // `REG.MEMBER[start, width]` and `Scope.REG.MEMBER[start, width]` before
    // either could be recognized as a register, emitting `PORT__Set.Set` and
    // `Hw__GPIO__Mode.GPIO.Mode` — neither of which compiles (#1244, #1052).
    // The single-bit spellings did reach this check, which is why only bit
    // ranges were broken.
    const registerKind = AssignmentClassifier.classifyRegisterBitAccess(
      ids,
      ctx.subscriptCount,
      state,
    );
    if (registerKind !== null) {
      return registerKind;
    }
 
    // Bare `Scope.member[...]`: the fourth ADR-016 spelling (#1116). A bare
    // name resolves through ADR-057's tiers, so `resolvesBareName` is true.
    const scopeQualifiedKind =
      AssignmentClassifier.classifyScopeQualifiedSubscript(
        ctx,
        "",
        true,
        state,
      );
    if (scopeQualifiedKind !== null) {
      return scopeQualifiedKind;
    }
 
    // Check for bit range through struct chain: devices[0].control[0, 4]
    // Detected by last subscript having 2 expressions (start, width)
    if (ctx.lastSubscriptExprCount === 2) {
      return AssignmentKind.STRUCT_CHAIN_BIT_RANGE;
    }
 
    // Multi-dimensional array element: arr[i][j] (1 identifier, multiple subscripts)
    if (ids.length === 1) {
      return AssignmentClassifier.classifyMultiDimArrayAccess(
        typeInfo,
        ctx.subscriptCount,
      );
    }
 
    // 2+ identifiers with subscripts: bitmap array (registers handled above)
    Eif (ids.length >= 2) {
      return AssignmentClassifier.classifyBitmapArrayField(
        ids[1],
        typeInfo,
        ctx.subscriptCount,
        state,
      );
    }
 
    return null;
  }
 
  /**
   * Classify multi-dimensional array access: arr[i][j] or arr[i][j][bit]
   */
  private static classifyMultiDimArrayAccess(
    typeInfo: TTypeInfo | undefined,
    subscriptCount: number,
  ): AssignmentKind | null {
    Iif (!typeInfo?.isArray || !typeInfo.arrayDimensions) {
      return null;
    }
 
    const numDims = typeInfo.arrayDimensions.length;
 
    // Check for bit indexing on array element
    if (
      subscriptCount === numDims + 1 &&
      TypeCheckUtils.isInteger(typeInfo.baseType)
    ) {
      return AssignmentKind.ARRAY_ELEMENT_BIT;
    }
 
    return AssignmentKind.MULTI_DIM_ARRAY_ELEMENT;
  }
 
  /**
   * Classify register bit access: REG.MEMBER[bit] or Scope.REG.MEMBER[bit]
   */
  private static classifyRegisterBitAccess(
    ids: readonly string[],
    subscriptCount: number,
    state: TranspileState,
  ): AssignmentKind | null {
    const firstId = ids[0];
 
    // Check for scoped register: Scope.REG.MEMBER[bit]
    if (state.isKnownScope(firstId) && ids.length >= 3) {
      const scopedRegName = QualifiedCName.fromParts([firstId, ids[1]]);
      if (state.symbols!.knownRegisters.has(scopedRegName)) {
        return subscriptCount === 2
          ? AssignmentKind.REGISTER_BIT_RANGE
          : AssignmentKind.REGISTER_BIT;
      }
    }
 
    // Check for non-scoped register: REG.MEMBER[bit]
    if (state.symbols!.knownRegisters.has(firstId)) {
      return subscriptCount === 2
        ? AssignmentKind.REGISTER_BIT_RANGE
        : AssignmentKind.REGISTER_BIT;
    }
 
    return null;
  }
 
  /**
   * Classify bitmap array element field: bitmapArr[i].field
   */
  private static classifyBitmapArrayField(
    secondId: string,
    typeInfo: TTypeInfo | undefined,
    subscriptCount: number,
    state: TranspileState,
  ): AssignmentKind | null {
    Iif (subscriptCount !== 1) {
      return null;
    }
 
    if (!typeInfo?.isBitmap || !typeInfo.isArray || !typeInfo.bitmapTypeName) {
      return null;
    }
 
    const width = AssignmentClassifier.lookupBitmapFieldWidth(
      typeInfo.bitmapTypeName,
      secondId,
      state,
    );
    Eif (width !== null) {
      return AssignmentKind.BITMAP_ARRAY_ELEMENT_FIELD;
    }
 
    return null;
  }
 
  /**
   * Classify global.* and this.* prefix patterns.
   */
  private static classifyPrefixPattern(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind | null {
    if (!ctx.hasGlobal && !ctx.hasThis) {
      return null;
    }
 
    if (ctx.hasGlobal && ctx.postfixOpsCount > 0) {
      return AssignmentClassifier.classifyGlobalPrefix(ctx, state);
    }
 
    if (ctx.hasThis && ctx.postfixOpsCount > 0) {
      return AssignmentClassifier.classifyThisPrefix(ctx, state);
    }
 
    return null;
  }
 
  /**
   * Classify global.* patterns: global.reg[bit], global.arr[i], global.member
   */
  private static classifyGlobalPrefix(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind {
    const firstId = ctx.identifiers[0];
 
    if (ctx.hasArrayAccess) {
      // Registers: `global.REG.MEMBER[bit]` and `global.Scope.REG.MEMBER[bit]`.
      // The same single decision the bare and `this.` spellings make — the
      // prefix does not change which register is named, so it must not select
      // a different handler. `GLOBAL_REGISTER_BIT` used to fork here into a
      // handler that skips the MMIO byte-aligned-write optimization, so the
      // two spellings of one write emitted different C for a write-only
      // register (#1244).
      const registerKind = AssignmentClassifier.classifyRegisterBitAccess(
        ctx.identifiers,
        ctx.subscriptCount,
        state,
      );
      if (registerKind !== null) {
        return registerKind;
      }
 
      // Scope-qualified variable: global.Scope.member[...]. Shared with the
      // bare spelling — see classifyScopeQualifiedSubscript.
      const scopeQualifiedKind =
        AssignmentClassifier.classifyScopeQualifiedSubscript(
          ctx,
          "global.",
          false,
          state,
        );
      Iif (scopeQualifiedKind !== null) {
        return scopeQualifiedKind;
      }
 
      // Issue #1115: when the subscript applies to the named VARIABLE,
      // `global.x[...]` means exactly what `x[...]` means, so it makes the same
      // decision. This branch used to return GLOBAL_ARRAY for every non-register
      // target without consulting SubscriptClassifier at all, which emitted the
      // raw subscript chain and broke every operation:
      //   global.buf[3][1] <- true  ->  buf[3][1] = true      (indexes a u8)
      //   global.s[0, 4] <- magic   ->  s[0, 4] = magic       (C comma operator)
      //   global.f[4, 3] <- 5       ->  f[4, 3] = 5           (C comma operator)
      // Cross-scope visibility is still enforced: the check runs during
      // `generateAssignmentTarget` (MemberSeparatorResolver), not in the
      // GLOBAL_ARRAY handler, so it applies to the delegated kinds too.
      if (ctx.identifiers.length === 1) {
        return AssignmentClassifier.classifySubscriptAccess(
          ctx,
          `global.${firstId}`,
        );
      }
 
      // Member chain (`global.config.items[0].assigned`): the subscript applies
      // to a struct field, not to `config`, so the general variable-subscript
      // classification does not apply. Handled as a chain.
      return AssignmentKind.GLOBAL_ARRAY;
    }
 
    return AssignmentKind.GLOBAL_MEMBER;
  }
 
  /**
   * Decide a subscript chain whose base name is scope-qualified:
   * `Scope.REG.MEMBER[bit]` or `Scope.member[...]`.
   *
   * Issue #1244: the `global.` prefix is a grammar token, not an identifier, so
   * `global.Other.buffer[3]` and the bare `Other.buffer[3]` arrive with
   * identical `ctx.identifiers` and mean the same thing. They are therefore ONE
   * decision, made here for both spellings.
   *
   * The bare spelling used to reach none of this. It landed in
   * `classifyMemberWithSubscript`, which had no scope-resolution step at all,
   * so the struct-chain branch claimed every bit range before the register or
   * the variable was ever recognized — emitting `Hw_GPIO_Mode.GPIO.Mode`
   * (#1244), `Other_flags.flags` on a scalar (#1116), and a 4-byte slice copy
   * silently rewritten as a 4-bit mask/shift.
   *
   * The ADR-057 precondition lives HERE rather than in each caller. When it sat
   * in the callers, the bare one gated on a lookup that silently covered only
   * two of the three tiers, and the `global.` one gated on nothing — the two
   * spellings shared the mechanism while each derived its own entry condition,
   * which is the divergence this method exists to remove.
   *
   * @param displayPrefix Diagnostic prefix matching the spelling written
   * @param resolvesBareName Whether the base name goes through ADR-057's
   *        local -> scope -> global order. False for `global.`, which names the
   *        global tier outright and must not be shadowed by a nearer variable.
   * @returns null when the base is not a scope-qualified name, leaving the
   *          caller's remaining cases (member chains, plain globals) untouched
   */
  private static classifyScopeQualifiedSubscript(
    ctx: IAssignmentContext,
    displayPrefix: string,
    resolvesBareName: boolean,
    state: TranspileState,
  ): AssignmentKind | null {
    const ids = ctx.identifiers;
    const scopeName = ids[0];
    if (!state.isKnownScope(scopeName)) {
      return null;
    }
 
    // ADR-057: a variable of that name at any tier wins, so the target is a
    // struct chain rather than a scope reference -- the binder's local ->
    // scope -> global order, applied where the target is (#1668)
    if (resolvesBareName && ctx.target.rootTypeInfo !== undefined) {
      return null;
    }
 
    // Only the variable case remains: registers are decided by
    // classifyRegisterBitAccess, which every caller asks before this method.
    // Once `Scope.member` resolves, this is exactly the decision the bare
    // `member[...]` spelling makes, so it delegates rather than re-deriving it.
    if (ids.length === 2) {
      return AssignmentClassifier.classifySubscriptAccess(
        ctx,
        `${displayPrefix}${ids.join(".")}`,
      );
    }
 
    return null;
  }
 
  /**
   * Classify this.* patterns: this.reg[bit], this.member, this.REG.MEMBER.field
   */
  private static classifyThisPrefix(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind {
    Iif (!state.currentScopePath) {
      return AssignmentKind.THIS_MEMBER;
    }
 
    const firstId = ctx.identifiers[0];
    const scopedRegName = ScopeUtils.qualifyInScope(
      firstId,
      state.currentScopePath,
    );
 
    if (ctx.hasArrayAccess) {
      return AssignmentClassifier.classifyThisWithArrayAccess(
        ctx,
        scopedRegName,
        state,
      );
    }
 
    // this.REG.MEMBER.field (scoped register bitmap field)
    if (
      ctx.identifiers.length === 3 &&
      state.symbols!.knownRegisters.has(scopedRegName)
    ) {
      const bitmapType = AssignmentClassifier.lookupRegisterMemberBitmapType(
        scopedRegName,
        ctx.identifiers[1],
        state,
      );
      Eif (bitmapType) {
        return AssignmentKind.SCOPED_REGISTER_MEMBER_BITMAP_FIELD;
      }
    }
 
    return AssignmentKind.THIS_MEMBER;
  }
 
  /**
   * Classify this.reg[bit] / this.arr[i] / this.flags[3] patterns with array access.
   * Issue #954: array vs bit access is the typer's subscript kind (#1668, C12).
   *
   * Issue #1115: only the scoped-register check is `this.`-specific. Everything
   * after it is the same decision the bare path makes, so it delegates rather
   * than re-deriving it — this method used to carry a truncated copy of that
   * switch, which silently lost ARRAY_ELEMENT_BIT, ARRAY_SLICE,
   * MULTI_DIM_ARRAY_ELEMENT and STRING_ARRAY_ELEMENT for `this.` targets.
   */
  private static classifyThisWithArrayAccess(
    ctx: IAssignmentContext,
    scopedRegName: string,
    state: TranspileState,
  ): AssignmentKind {
    // Check for scoped register first
    if (state.symbols!.knownRegisters.has(scopedRegName)) {
      const hasBitRange = ctx.postfixOps.some(
        (op) => op.kind === "subscript" && op.indexCount === 2,
      );
      return hasBitRange
        ? AssignmentKind.SCOPED_REGISTER_BIT_RANGE
        : AssignmentKind.SCOPED_REGISTER_BIT;
    }
 
    // Diagnostics quote the source spelling (`this.flags`) rather than the
    // resolved `scopedRegName`, so the suggested fix is the text the developer
    // actually wrote. (`Sensor_flags` does resolve as a bare name, but nobody
    // writes it — echoing it back would read as a different variable.)
    return AssignmentClassifier.classifySubscriptAccess(
      ctx,
      `this.${ctx.identifiers[0]}`,
    );
  }
 
  /**
   * Classify simple array/bit access (no prefix, no member access).
   * Pattern: arr[i] or flags[bit]
   *
   * Issue #579: the subscript's kind is the typer's, the same one the
   * expression path reads (#1668, C12).
   */
  private static classifyArrayOrBitAccess(
    ctx: IAssignmentContext,
  ): AssignmentKind | null {
    // Must have arrayAccess without memberAccess or prefix
    if (ctx.hasGlobal || ctx.hasThis || ctx.hasMemberAccess) {
      return null;
    }
 
    if (!ctx.hasArrayAccess || ctx.subscriptCount === 0) {
      return null;
    }
 
    const name = ctx.identifiers[0];
    return AssignmentClassifier.classifySubscriptAccess(ctx, name);
  }
 
  /**
   * Decide what a subscript chain on a single variable means.
   *
   * Issue #1115: the SINGLE source of truth for that decision. `arr[i]` and
   * `this.arr[i]` differ only in how the base name resolves — once resolved,
   * the type lookup, depth validation and array-vs-bit classification are
   * identical, and the handlers already share generation (THIS_BIT and
   * INTEGER_BIT both map to `handleIntegerBit`, since `resolvedTarget` and
   * `resolvedBaseIdentifier` already carry the scope prefix). Keeping two
   * copies of this switch is what let the `this.` form diverge.
   *
   * #1668 (C7): the variable is the target's binding, so its spelling no
   * longer matters here -- only the diagnostic's.
   *
   * @param displayName  Name for diagnostics: what the developer actually wrote
   */
  private static classifySubscriptAccess(
    ctx: IAssignmentContext,
    displayName: string,
  ): AssignmentKind {
    // A chain that ends in a member (`this.buffer[i].value`) writes that
    // member, and its subscripts index on the way there -- a member chain, as
    // the bare spelling `buffer[i].value` is. The rules below are about a
    // FINAL subscript; this reached them and was classified by the
    // classifier's default for an unknown type, whose handler wrote the right
    // text by coincidence (#1668 review).
    const last = ctx.target.last;
    Iif (last?.subscript === null) {
      return AssignmentKind.MEMBER_CHAIN;
    }
 
    const typeInfo = ctx.target.typeInfo ?? null;
 
    // `assignmentTarget` consumes the leading `IDENTIFIER` (and any `this .` /
    // `global .` prefix) in the grammar rule itself, so op 0 is a subscript for
    // `flags[4][3]`, `this.flags[4][3]` and `global.flags[4][3]` alike. Only a
    // scope-qualified chain such as `global.Other.buf[3][1]` carries extra
    // member ops first — exactly one per identifier past the base, hence
    // `identifiers.length - 1` for every spelling.
    const memberOpCount = ctx.identifiers.length - 1;
 
    // Issue #1106: reject over-indexing a scalar/array base (e.g. flags[4][3]
    // on a scalar u8). Counting is delegated to SubscriptDepthValidator so
    // this path and the read path share the decision, not just the check.
    SubscriptDepthValidator.validate(
      typeInfo ?? undefined,
      // #1445: counted off the PLANNED ops, which carry `kind` -- the node's
      // `expression().length` said the same thing and is no longer here.
      SubscriptDepthValidator.countLeadingSubscripts(
        ctx.postfixOps.slice(memberOpCount),
      ),
      displayName,
    );
 
    // #1668 (C12): what the final subscript reads, and so whether it is an
    // element, a slice, a bit or a bit range, is the one operand typer's
    // answer -- the one 2.1 already checked. Classifying from the ROOT's type
    // called `row[2][0, 4]` a slice of `row`, and a valid program failed with
    // an internal error. The typer types every subscript it walks, an
    // untyped value's included (the classifier's default for an unknown type).
    const subscriptKind = last?.subscript ?? null;
    invariant(
      subscriptKind !== null,
      "the typer typed this target's final subscript",
    );
    // The subscripts are flattened, so anything before the final op's own
    // expressions indexed an array element first
    const indexesAnElement = ctx.subscriptCount > ctx.lastSubscriptExprCount;
 
    switch (subscriptKind) {
      case "bit_single":
        if (!indexesAnElement) return AssignmentKind.INTEGER_BIT;
        // e.g. matrix[i][j][bit] on an integer array's element
        return OperandTyper.hasWritableBits(last?.before ?? null)
          ? AssignmentKind.ARRAY_ELEMENT_BIT
          : AssignmentKind.MULTI_DIM_ARRAY_ELEMENT;
 
      case "bit_range":
        return indexesAnElement
          ? AssignmentKind.ARRAY_ELEMENT_BIT_RANGE
          : AssignmentKind.INTEGER_BIT_RANGE;
 
      case "array_element":
        // Multi-dimensional array: matrix[i][j] has multiple subscript operations
        // but each with 1 expression (vs slice [0, 5] with 2 expressions in 1 op)
        if (ctx.subscriptCount > 1) {
          return AssignmentKind.MULTI_DIM_ARRAY_ELEMENT;
        }
        // String array element (special case for 2D string arrays)
        if (
          typeInfo?.isString &&
          typeInfo.arrayDimensions &&
          typeInfo.arrayDimensions.length > 1
        ) {
          return AssignmentKind.STRING_ARRAY_ELEMENT;
        }
        return AssignmentKind.ARRAY_ELEMENT;
 
      case "array_slice":
        return AssignmentKind.ARRAY_SLICE;
    }
  }
 
  /**
   * Classify atomic and overflow-clamped compound assignments.
   * Handles simple identifiers, this.member, and global.member patterns.
   */
  private static classifySpecialCompound(
    ctx: IAssignmentContext,
  ): AssignmentKind | null {
    if (!ctx.isCompound) {
      return null;
    }
 
    const typeInfo = AssignmentClassifier.targetTypeInfo(ctx);
    if (!typeInfo) {
      return null;
    }
 
    // Atomic RMW - for global atomic variables (simple identifiers or global.member)
    // Scoped atomics (this.member) use overflow behavior, not LDREX/STREX
    const isGlobalAtomic =
      typeInfo.isAtomic && (ctx.isSimpleIdentifier || ctx.isSimpleGlobalAccess);
    if (isGlobalAtomic) {
      return AssignmentKind.ATOMIC_RMW;
    }
 
    if (AssignmentClassifier.compoundClampOp(ctx, typeInfo) !== null) {
      return AssignmentKind.OVERFLOW_CLAMP;
    }
 
    return null;
  }
 
  /**
   * ADR-044: the saturating helper operation (`add`, `sub`, `mul`) that a
   * compound assignment lowers to, or null when it is plain C arithmetic.
   *
   * Only a `clamp` integer target qualifies, and only for the arithmetic
   * operators that can overflow; a bitwise compound cannot, so it stays plain.
   * This is the one decision: the classifier asks it to pick OVERFLOW_CLAMP,
   * the overflow handler asks it for the helper, and the atomic handler asks it
   * for the inner operation of its read-modify-write. The atomic generator used
   * to decide the same thing from its own operator map and its own integer test.
   *
   * #1668: null when the value has a floating operand. `y *<- 2.5` is
   * `y <- y * 2.5`, and routing it into `cnx_clamp_mul_u32` truncated the 2.5
   * to 2 before multiplying.
   */
  static compoundClampOp(
    ctx: IAssignmentContext,
    typeInfo: TTypeInfo,
  ): string | null {
    if (typeInfo.overflowBehavior !== "clamp") return null;
    if (!TypeCheckUtils.isInteger(typeInfo.baseType)) return null;
    if (ctx.valueHasFloatingOperand()) return null;
    return CLAMP_HELPER_FOR_COMPOUND[ctx.cOp] ?? null;
  }
 
  /**
   * Check if a simple identifier is a string variable.
   */
  private static _classifySimpleStringVar(
    ctx: IAssignmentContext,
  ): AssignmentKind | null {
    if (!ctx.isSimpleIdentifier) return null;
    const typeInfo = AssignmentClassifier.targetTypeInfo(ctx);
    return AssignmentClassifier.isSimpleStringType(typeInfo)
      ? AssignmentKind.STRING_SIMPLE
      : null;
  }
 
  /**
   * Check if this.member is a string.
   */
  private static _classifyThisMemberString(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind | null {
    if (!ctx.isSimpleThisAccess || !state.currentScopePath) return null;
    const typeInfo = AssignmentClassifier.targetTypeInfo(ctx);
    return AssignmentClassifier.isSimpleStringType(typeInfo)
      ? AssignmentKind.STRING_THIS_MEMBER
      : null;
  }
 
  /**
   * Check if global.member is a string.
   */
  private static _classifyGlobalString(
    ctx: IAssignmentContext,
  ): AssignmentKind | null {
    if (!ctx.isSimpleGlobalAccess) return null;
    const typeInfo = AssignmentClassifier.targetTypeInfo(ctx);
    return AssignmentClassifier.isSimpleStringType(typeInfo)
      ? AssignmentKind.STRING_GLOBAL
      : null;
  }
 
  /**
   * Resolve struct type from variable name.
   * Returns the base struct type if valid, null if not a known struct.
   */
  private static _resolveStructType(
    structTypeInfo: TTypeInfo | undefined,
    state: TranspileState,
  ): string | null {
    if (!structTypeInfo || !state.isKnownStruct(structTypeInfo.baseType)) {
      return null;
    }
    return structTypeInfo.baseType;
  }
 
  /**
   * Resolve struct field type from struct variable name and field name.
   * Returns null if struct type can't be resolved or field doesn't exist.
   */
  private static _resolveStructFieldType(
    structFieldNames: {
      structName: string;
      fieldName: string;
    },
    rootTypeInfo: TTypeInfo | undefined,
    state: TranspileState,
  ): { structType: string; fieldType: string | undefined } | null {
    const structType = AssignmentClassifier._resolveStructType(
      rootTypeInfo,
      state,
    );
    if (!structType) {
      return null;
    }
    // Issue #831: Use SymbolTable as single source of truth for struct fields
    // Through the accessor, not `symbolTable` directly: #1322's
    // scope-declared-struct key fallback lives there, so a bare table lookup
    // answers `undefined` for a struct declared inside a scope. `fe474b3f5`
    // moved two sibling lookups for exactly this reason and left three behind,
    // which is three answers to "what type is this field".
    const fieldType = state.getStructFieldInfo(
      structType,
      structFieldNames.fieldName,
    )?.type;
    return { structType, fieldType };
  }
 
  /**
   * Check if struct.field is a string field.
   */
  private static _classifyStructFieldString(
    ctx: IAssignmentContext,
    structFieldNames: { structName: string; fieldName: string } | null,
    state: TranspileState,
  ): AssignmentKind | null {
    if (!ctx.hasMemberAccess || ctx.hasArrayAccess || !structFieldNames) {
      return null;
    }
    const resolved = AssignmentClassifier._resolveStructFieldType(
      structFieldNames,
      ctx.target.rootTypeInfo,
      state,
    );
    if (!resolved) {
      return null;
    }
    return resolved.fieldType &&
      TypeCheckUtils.isSizedStringName(resolved.fieldType)
      ? AssignmentKind.STRING_STRUCT_FIELD
      : null;
  }
 
  /**
   * Check if struct.arr[i] is a string array element.
   */
  private static _classifyStructArrayElementString(
    ctx: IAssignmentContext,
    structFieldNames: { structName: string; fieldName: string } | null,
    state: TranspileState,
  ): AssignmentKind | null {
    if (
      !ctx.hasMemberAccess ||
      !ctx.hasArrayAccess ||
      !structFieldNames ||
      ctx.subscriptCount !== 1
    ) {
      return null;
    }
    const resolved = AssignmentClassifier._resolveStructFieldType(
      structFieldNames,
      ctx.target.rootTypeInfo,
      state,
    );
    Iif (!resolved) {
      return null;
    }
 
    const { structType, fieldType } = resolved;
    const { fieldName } = structFieldNames;
    const fieldArrays = state.symbols!.structFieldArrays.get(structType);
    const dimensions = state
      .symbols!.structFieldDimensions.get(structType)
      ?.get(fieldName);
 
    const isStringArrayField =
      fieldType &&
      TypeCheckUtils.isSizedStringName(fieldType) &&
      fieldArrays?.has(fieldName) &&
      dimensions &&
      dimensions.length >= 1;
 
    return isStringArrayField
      ? AssignmentKind.STRING_STRUCT_ARRAY_ELEMENT
      : null;
  }
 
  /**
   * Classify string assignments.
   */
  private static classifyStringAssignment(
    ctx: IAssignmentContext,
    state: TranspileState,
  ): AssignmentKind | null {
    // Simple string variable
    const simpleVar = AssignmentClassifier._classifySimpleStringVar(ctx);
    if (simpleVar) return simpleVar;
 
    // this.member string
    const thisMember = AssignmentClassifier._classifyThisMemberString(
      ctx,
      state,
    );
    if (thisMember) return thisMember;
 
    // global.member string
    const globalMember = AssignmentClassifier._classifyGlobalString(ctx);
    if (globalMember) return globalMember;
 
    // struct.field or struct.arr[i] string
    const structFieldNames = AssignmentClassifier.getStructFieldNames(ctx);
    const structField = AssignmentClassifier._classifyStructFieldString(
      ctx,
      structFieldNames,
      state,
    );
    if (structField) return structField;
 
    const structArrayElement =
      AssignmentClassifier._classifyStructArrayElementString(
        ctx,
        structFieldNames,
        state,
      );
    if (structArrayElement) return structArrayElement;
 
    return null;
  }
 
  /**
   * Look up a bitmap field's width by bitmap type name and field name.
   * Returns the field width if found, or null if the bitmap/field doesn't exist.
   */
  private static lookupBitmapFieldWidth(
    bitmapTypeName: string,
    fieldName: string,
    state: TranspileState,
  ): number | null {
    const fields = state.symbols!.bitmapFields.get(bitmapTypeName);
    if (fields?.has(fieldName)) {
      return fields.get(fieldName)!.width;
    }
    return null;
  }
 
  /**
   * Look up the bitmap type for a register member (e.g., "REG_MEMBER" -> "BitmapType").
   * Returns the bitmap type name if found, or null.
   */
  private static lookupRegisterMemberBitmapType(
    registerName: string,
    memberName: string,
    state: TranspileState,
  ): string | null {
    const key = QualifiedCName.fromParts([registerName, memberName]);
    return state.symbols!.registerMemberTypes.get(key) ?? null;
  }
}
 
export default AssignmentClassifier;