All files / transpiler/state CodeGenState.ts

94.62% Statements 264/279
84.67% Branches 105/124
98.59% Functions 70/71
95.25% Lines 261/274

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                                                                          58x                                                                                 58x             58x           58x             58x                     58x     58x             58x     58x     58x     58x             58x             58x     58x     58x     58x     58x           58x           58x             58x     58x             58x     58x     58x     58x     58x     58x     58x     58x     58x             58x     58x     58x               58x     58x     58x             58x     58x     58x     58x             58x     58x     58x     58x     58x     58x     58x     58x                       58x             58x     58x     58x     58x     58x     58x             58x     58x     58x                       2303x     2303x         2303x 2303x     2303x 2303x 2303x 2303x           2303x 2303x 2303x 2303x 2303x       2303x 2303x     2303x 2303x 2303x 2303x 2303x 2303x 2303x 2303x 2303x     2303x 2303x 2303x 2303x 2303x 2303x         2303x 2303x 2303x 2303x     2303x 2303x 2303x 2303x 2303x 2303x 2303x 2303x     2303x 2303x 2303x 2303x 2303x 2303x     2303x     2303x 2303x 2303x               924x 924x 924x 924x 924x               896x 896x 896x 896x 896x                                 1239x 128x   1111x 1111x 1111x 1111x 69x   1111x 1111x   1111x 1111x                         183x 16x 12x 12x             49x             816x                                             75x                 71x                           4722x 4722x 3482x       1240x 1240x 42x           1198x 1198x 6x 6x       3x                   1195x               1x               9x 3x   6x 6x 1x     5x 5x 4x 4x         1x             1480x             246x                 10545x                       10x 10x 2x   10x           42x     42x 42x 42x 42x       42x   42x   42x         9x 9x                           12x                 113x 113x 127x 127x 127x 34x 32x     127x   113x                                                                                 769x 769x     769x                                                                     2x             2x             99x             175x             10240x             6x 5x               717x 69x 69x 40x     677x                   5x                     7x       7x 3x             4x 7x 4x 4x   4x 4x 4x                                   7x 7x     7x     7x       7x                         3x                     2x                 156x 156x   156x 11x 11x   18x       14x     11x 10x                 32x             17x                     1x             1x             1x             1x             1x             1x                     1x             1x             2x 2x 1x                     1x 1x             1x             1x             34x             1x                     2x             2x             2x             2x                           6x                     17x                     3x             1x 1x 1x             3x      
/**
 * CodeGenState - Global state for code generation
 *
 * Centralizes all code generation state in a single static class.
 * Eliminates dependency injection complexity and makes debugging easier.
 *
 * Usage:
 *   import CodeGenState from "../state/CodeGenState";
 *   const type = CodeGenState.typeRegistry.get(name);
 *   if (CodeGenState.isKnownStruct(name)) { ... }
 *
 * Lifecycle:
 *   1. CodeGenerator.generate() calls CodeGenState.reset()
 *   2. CodeGenerator sets CodeGenState.generator = this
 *   3. All generators/helpers read from CodeGenState directly
 *   4. State persists for the duration of one generate() call
 *
 * SymbolTable ownership:
 *   CodeGenState owns the single SymbolTable instance. It persists across
 *   reset() calls (which are per-file). The Transpiler clears it via
 *   CodeGenState.symbolTable.clear() at the start of each run().
 */
 
import SymbolTable from "../logic/symbols/SymbolTable";
import ICodeGenSymbols from "../types/ICodeGenSymbols";
import TTypeInfo from "../output/codegen/types/TTypeInfo";
import TParameterInfo from "../output/codegen/types/TParameterInfo";
import IFunctionSignature from "../output/codegen/types/IFunctionSignature";
import ICallbackTypeInfo from "../output/codegen/types/ICallbackTypeInfo";
import ITargetCapabilities from "../output/codegen/types/ITargetCapabilities";
import TOverflowBehavior from "../output/codegen/types/TOverflowBehavior";
import TYPE_WIDTH from "../output/codegen/types/TYPE_WIDTH";
import TypeResolver from "../../utils/TypeResolver";
 
/**
 * Default target capabilities (safe fallback)
 */
const DEFAULT_TARGET: ITargetCapabilities = {
  wordSize: 32,
  hasLdrexStrex: false,
  hasBasepri: false,
};
 
/**
 * Assignment context for overflow behavior tracking (ADR-044)
 */
interface IAssignmentContext {
  targetName: string | null;
  targetType: string | null;
  overflowBehavior: TOverflowBehavior;
}
 
/**
 * Function call graph entry for transitive modification analysis
 */
interface ICallGraphEntry {
  callee: string;
  paramIndex: number;
  argParamName: string;
}
 
/**
 * Global state for code generation.
 * All fields are static - import and use directly from any module.
 *
 * NOTE: All static properties are intentionally mutable (not readonly).
 * This class holds session state that is reset via reset() and modified
 * during code generation.
 */
export default class CodeGenState {
  // ===========================================================================
  // GENERATOR REFERENCE (for handler access)
  // ===========================================================================
 
  /**
   * Reference to the CodeGenerator instance for handlers to call methods.
   * Typed as unknown to avoid circular dependencies - handlers cast as needed.
   */
  static generator: unknown = null;
 
  // ===========================================================================
  // SYMBOL DATA (read-only after initialization)
  // ===========================================================================
 
  /** ADR-055: Pre-collected symbol info from CNextResolver + TSymbolInfoAdapter */
  static symbols: ICodeGenSymbols | null = null;
 
  /** External symbol table for cross-language interop (C headers).
   * Owned by CodeGenState; persists across per-file reset() calls.
   * Cleared via symbolTable.clear() at the start of each Transpiler run.
   */
  static symbolTable: SymbolTable = new SymbolTable();
 
  /**
   * External struct fields from C/C++ headers for initialization analysis.
   * Maps struct name -> Set of non-array field names.
   * Persists across per-file reset() calls, cleared at start of run.
   */
  static externalStructFields: Map<string, Set<string>> = new Map();
 
  // ===========================================================================
  // TYPE TRACKING
  // ===========================================================================
 
  /**
   * Track variable types for bit access, .length, and type inference.
   * PRIVATE: Use getVariableTypeInfo()/setVariableTypeInfo() instead.
   * This ensures cross-file variables from SymbolTable are also found.
   */
  private static typeRegistry: Map<string, TTypeInfo> = new Map();
 
  /** Bug #8: Compile-time const values for array size resolution */
  static constValues: Map<string, number> = new Map();
 
  // ===========================================================================
  // FUNCTION & CALLBACK TRACKING
  // ===========================================================================
 
  /** Track C-Next defined functions */
  static knownFunctions: Set<string> = new Set();
 
  /** ADR-013: Track function parameter const-ness for call-site validation */
  static functionSignatures: Map<string, IFunctionSignature> = new Map();
 
  /** ADR-029: Callback types registry (function-as-type pattern) */
  static callbackTypes: Map<string, ICallbackTypeInfo> = new Map();
 
  /** Callback field types: "Struct.field" -> callbackTypeName */
  static callbackFieldTypes: Map<string, string> = new Map();
 
  /**
   * Functions that are assigned to C callback typedefs.
   * Maps function name -> typedef name (e.g., "my_flush" -> "flush_cb_t")
   * Issue #895: We need the typedef name to look up parameter types.
   */
  static callbackCompatibleFunctions: Map<string, string> = new Map();
 
  // ===========================================================================
  // PASS-BY-VALUE ANALYSIS (Issue #269)
  // ===========================================================================
 
  /** Tracks which parameters are modified (directly or transitively) */
  static modifiedParameters: Map<string, Set<string>> = new Map();
 
  /** Issue #579: Parameters with subscript access (must become pointers) */
  static subscriptAccessedParameters: Map<string, Set<string>> = new Map();
 
  /** Parameters that should pass by value (small, unmodified primitives) */
  static passByValueParams: Map<string, Set<string>> = new Map();
 
  /** Function call relationships for transitive modification analysis */
  static functionCallGraph: Map<string, ICallGraphEntry[]> = new Map();
 
  /** Function parameter lists for call graph analysis */
  static functionParamLists: Map<string, string[]> = new Map();
 
  /** Issue #558: Cross-file modifications to inject */
  static pendingCrossFileModifications: ReadonlyMap<
    string,
    ReadonlySet<string>
  > | null = null;
 
  /** Issue #558: Cross-file parameter lists to inject */
  static pendingCrossFileParamLists: ReadonlyMap<
    string,
    readonly string[]
  > | null = null;
 
  // ===========================================================================
  // OVERFLOW & DIVISION HELPERS (ADR-044, ADR-051)
  // ===========================================================================
 
  /** Track which overflow helper types/operations are needed: "add_u8", etc. */
  static usedClampOps: Set<string> = new Set();
 
  /** Track which safe division helpers are needed: "div_u32", "mod_i16" */
  static usedSafeDivOps: Set<string> = new Set();
 
  // ===========================================================================
  // CURRENT CONTEXT (changes during AST traversal)
  // ===========================================================================
 
  /** ADR-016: Current scope for name resolution */
  static currentScope: string | null = null;
 
  /** Issue #269: Current function for modification tracking */
  static currentFunctionName: string | null = null;
 
  /** Issue #477: Current function return type for enum inference */
  static currentFunctionReturnType: string | null = null;
 
  /** ADR-006: Current function parameters for pointer semantics */
  static currentParameters: Map<string, TParameterInfo> = new Map();
 
  /** ADR-016: Local variables in current function (allowed as bare identifiers) */
  static localVariables: Set<string> = new Set();
 
  /** ADR-006: Local array variables (no & needed when passing) */
  static localArrays: Set<string> = new Set();
 
  /** Scope member names: scope -> Set of member names */
  private static scopeMembers: Map<string, Set<string>> = new Map();
 
  /** Float bit indexing: declared shadow variables */
  static floatBitShadows: Set<string> = new Set();
 
  /** Float bit indexing: shadows with current value (skip redundant reads) */
  static floatShadowCurrent: Set<string> = new Set();
 
  // ===========================================================================
  // GENERATION STATE
  // ===========================================================================
 
  /** Current indentation level */
  static indentLevel: number = 0;
 
  /** Whether we're inside a function body */
  static inFunctionBody: boolean = false;
 
  /** Expected type for struct initializers and enum inference */
  static expectedType: string | null = null;
 
  /**
   * Suppress bare enum resolution even when expectedType is set.
   * Issue #872: MISRA 7.2 requires expectedType for U suffix on function args,
   * but bare enum resolution in function args was never allowed and changing
   * that would require ADR approval.
   */
  static suppressBareEnumResolution: boolean = false;
 
  /** Track args parameter name for main() translation */
  static mainArgsName: string | null = null;
 
  /** ADR-044: Current assignment context for overflow behavior */
  static assignmentContext: IAssignmentContext = {
    targetName: null,
    targetType: null,
    overflowBehavior: "clamp",
  };
 
  /** ADR-035: Element count for array size inference */
  static lastArrayInitCount: number = 0;
 
  /** ADR-035: Fill-all value for array initialization */
  static lastArrayFillValue: string | undefined = undefined;
 
  /** strlen optimization: variable name -> temp variable name */
  static lengthCache: Map<string, string> | null = null;
 
  /** ADR-049: Target platform capabilities */
  static targetCapabilities: ITargetCapabilities = DEFAULT_TARGET;
 
  // ===========================================================================
  // INCLUDE FLAGS (track required standard library includes)
  // ===========================================================================
 
  /** For u8, u16, u32, u64, i8, i16, i32, i64 */
  static needsStdint: boolean = false;
 
  /** For bool type */
  static needsStdbool: boolean = false;
 
  /** ADR-045: For strlen, strncpy, etc. */
  static needsString: boolean = false;
 
  /** For float bit indexing size verification */
  static needsFloatStaticAssert: boolean = false;
 
  /** ADR-040: For ISR function pointer type */
  static needsISR: boolean = false;
 
  /** ADR-049/050: For atomic intrinsics and critical sections */
  static needsCMSIS: boolean = false;
 
  /** Issue #632: For float-to-int clamp casts */
  static needsLimits: boolean = false;
 
  /** Issue #473: IRQ wrappers for critical sections */
  static needsIrqWrappers: boolean = false;
 
  // ===========================================================================
  // OPAQUE TYPE SCOPE VARIABLES (Issue #948)
  // ===========================================================================
 
  /**
   * Tracks scope variables with opaque (forward-declared) struct types.
   * These are generated as pointers with NULL initialization and should
   * be passed directly (not with &) since they're already pointers.
   * Maps qualified name (e.g., "MyScope_widget") to true.
   */
  private static opaqueScopeVariables: Set<string> = new Set();
 
  // ===========================================================================
  // C++ MODE STATE (Issue #250)
  // ===========================================================================
 
  /** Use temp vars instead of compound literals */
  static cppMode: boolean = false;
 
  /** Debug mode generates panic-on-overflow helpers (ADR-044) */
  static debugMode: boolean = false;
 
  /** Pending temp variable declarations for C++ mode */
  static pendingTempDeclarations: string[] = [];
 
  /** Counter for unique temp variable names */
  static tempVarCounter: number = 0;
 
  /** Issue #517: Pending field assignments for C++ class struct init */
  static pendingCppClassAssignments: string[] = [];
 
  /** Issue #369: Whether self-include was added */
  static selfIncludeAdded: boolean = false;
 
  // ===========================================================================
  // SOURCE PATHS (ADR-010, Issue #349)
  // ===========================================================================
 
  /** Source file path for validating includes */
  static sourcePath: string | null = null;
 
  /** Include directories for resolving angle-bracket .cnx includes */
  static includeDirs: string[] = [];
 
  /** Input directories for calculating relative paths */
  static inputs: string[] = [];
 
  // ===========================================================================
  // LIFECYCLE METHODS
  // ===========================================================================
 
  /**
   * Reset all state for a fresh generation pass.
   * Called at the start of CodeGenerator.generate()
   */
  static reset(targetCapabilities?: ITargetCapabilities): void {
    // Generator reference
    this.generator = null;
 
    // Symbol data
    this.symbols = null;
    // Note: symbolTable is NOT reset here — it persists across per-file generates.
    // It is cleared via symbolTable.clear() at the start of each Transpiler run.
 
    // Type tracking
    this.typeRegistry = new Map();
    this.constValues = new Map();
 
    // Function & callback tracking
    this.knownFunctions = new Set();
    this.functionSignatures = new Map();
    this.callbackTypes = new Map();
    this.callbackFieldTypes = new Map();
    // Note: callbackCompatibleFunctions is NOT reset here — it's populated by
    // FunctionCallAnalyzer (which runs before CodeGenerator.generate()) and must
    // persist into code generation. It is cleared at the start of each Transpiler run.
 
    // Pass-by-value analysis
    this.modifiedParameters = new Map();
    this.subscriptAccessedParameters = new Map();
    this.passByValueParams = new Map();
    this.functionCallGraph = new Map();
    this.functionParamLists = new Map();
    // Note: pendingCrossFileModifications/ParamLists are set externally, not reset
 
    // Overflow & division helpers
    this.usedClampOps = new Set();
    this.usedSafeDivOps = new Set();
 
    // Current context
    this.currentScope = null;
    this.currentFunctionName = null;
    this.currentFunctionReturnType = null;
    this.currentParameters = new Map();
    this.localVariables = new Set();
    this.localArrays = new Set();
    this.scopeMembers = new Map();
    this.floatBitShadows = new Set();
    this.floatShadowCurrent = new Set();
 
    // Generation state
    this.indentLevel = 0;
    this.inFunctionBody = false;
    this.expectedType = null;
    this.suppressBareEnumResolution = false;
    this.mainArgsName = null;
    this.assignmentContext = {
      targetName: null,
      targetType: null,
      overflowBehavior: "clamp",
    };
    this.lastArrayInitCount = 0;
    this.lastArrayFillValue = undefined;
    this.lengthCache = null;
    this.targetCapabilities = targetCapabilities ?? DEFAULT_TARGET;
 
    // Include flags
    this.needsStdint = false;
    this.needsStdbool = false;
    this.needsString = false;
    this.needsFloatStaticAssert = false;
    this.needsISR = false;
    this.needsCMSIS = false;
    this.needsLimits = false;
    this.needsIrqWrappers = false;
 
    // C++ mode state
    this.cppMode = false;
    this.debugMode = false;
    this.pendingTempDeclarations = [];
    this.tempVarCounter = 0;
    this.pendingCppClassAssignments = [];
    this.selfIncludeAdded = false;
 
    // Issue #948: Opaque scope variables (reset per-file)
    this.opaqueScopeVariables = new Set();
 
    // Source paths
    this.sourcePath = null;
    this.includeDirs = [];
    this.inputs = [];
  }
 
  /**
   * Enter a function body context.
   * Clears local tracking and sets inFunctionBody flag.
   */
  static enterFunctionBody(): void {
    this.inFunctionBody = true;
    this.localVariables.clear();
    this.localArrays.clear();
    this.floatBitShadows.clear();
    this.floatShadowCurrent.clear();
  }
 
  /**
   * Exit a function body context.
   * Clears local tracking and sets inFunctionBody to false.
   */
  static exitFunctionBody(): void {
    this.inFunctionBody = false;
    this.localVariables.clear();
    this.localArrays.clear();
    this.floatBitShadows.clear();
    this.floatShadowCurrent.clear();
  }
 
  /**
   * Execute a function with a temporary expectedType, restoring on completion.
   * Issue #872: Extracted to eliminate duplicate save/restore pattern and add exception safety.
   *
   * @param type - The expected type to set (if falsy, no change is made)
   * @param fn - The function to execute
   * @param suppressEnumResolution - If true, suppress bare enum resolution (for MISRA-only contexts)
   * @returns The result of the function
   */
  static withExpectedType<T>(
    type: string | undefined | null,
    fn: () => T,
    suppressEnumResolution: boolean = false,
  ): T {
    if (!type) {
      return fn();
    }
    const savedType = this.expectedType;
    const savedSuppress = this.suppressBareEnumResolution;
    this.expectedType = type;
    if (suppressEnumResolution) {
      this.suppressBareEnumResolution = true;
    }
    try {
      return fn();
    } finally {
      this.expectedType = savedType;
      this.suppressBareEnumResolution = savedSuppress;
    }
  }
 
  // ===========================================================================
  // CONVENIENCE LOOKUP METHODS
  // ===========================================================================
 
  /**
   * Check if a type name is a known struct.
   * Also includes bitmaps since they're struct-like (Issue #551).
   */
  static isKnownStruct(name: string): boolean {
    if (this.symbols?.knownStructs.has(name)) return true;
    if (this.symbols?.knownBitmaps.has(name)) return true;
    Iif (this.symbolTable.getStructFields(name)) return true;
    return false;
  }
 
  /**
   * Check if a type name is a known scope.
   */
  static isKnownScope(name: string): boolean {
    return this.symbols?.knownScopes.has(name) ?? false;
  }
 
  /**
   * Check if a type name is a known enum.
   */
  static isKnownEnum(name: string): boolean {
    return this.symbols?.knownEnums.has(name) ?? false;
  }
 
  /**
   * Check if a type name is a known bitmap.
   */
  static isKnownBitmap(name: string): boolean {
    return this.symbols?.knownBitmaps.has(name) ?? false;
  }
 
  /**
   * Check if a type name is a known register.
   */
  static isKnownRegister(name: string): boolean {
    return this.symbols?.knownRegisters.has(name) ?? false;
  }
 
  /**
   * Issue #948: Check if a type name is an opaque (forward-declared) struct type.
   * Opaque types are incomplete types that can only be used as pointers.
   * Example: `typedef struct _widget_t widget_t;` without a body makes `widget_t` opaque.
   */
  static isOpaqueType(typeName: string): boolean {
    return this.symbols?.opaqueTypes.has(typeName) ?? false;
  }
 
  /**
   * Issue #958: Check if a type name is an external typedef struct type.
   * External typedef struct types should use pointer semantics for scope variables.
   * Unlike isOpaqueType, this returns true for both forward-declared and complete structs.
   */
  static isTypedefStructType(typeName: string): boolean {
    return this.symbolTable?.isTypedefStructType(typeName) ?? false;
  }
 
  /**
   * Get type info for a variable.
   * Checks local typeRegistry first, then falls back to SymbolTable
   * for cross-file variables from included .cnx files.
   *
   * Issue #786: This unified lookup ensures cross-file variables
   * (defined in included files) are found even before code generation
   * registers them locally.
   */
  static getVariableTypeInfo(name: string): TTypeInfo | undefined {
    // First check the local type registry (current file's variables)
    const localInfo = this.typeRegistry.get(name);
    if (localInfo) {
      return localInfo;
    }
 
    // ADR-055 Phase 7: Fall back to SymbolTable for cross-file C-Next variables only.
    const symbol = this.symbolTable.getTSymbol(name);
    if (symbol?.kind === "variable" && symbol.type) {
      return this.convertTSymbolToTypeInfo(symbol);
    }
 
    // Issue #978: Fall back to C symbols for external struct globals from .h headers.
    // Only return type info for struct-typed variables — returning info for all
    // C types would cause regressions (e.g., array indexing misread as bit extraction).
    const cSymbol = this.symbolTable.getCSymbol(name);
    if (cSymbol?.kind === "variable" && cSymbol.type) {
      const baseType = CodeGenState.stripTrailingPointers(cSymbol.type);
      if (
        this.symbolTable.isTypedefStructType(baseType) ||
        this.symbolTable.getStructFields(baseType)
      ) {
        return {
          baseType,
          bitWidth: 0,
          isArray: cSymbol.isArray || false,
          isConst: cSymbol.isConst || false,
          isPointer: cSymbol.type.endsWith("*"),
        };
      }
    }
 
    return undefined;
  }
 
  /**
   * Legacy alias for getVariableTypeInfo.
   * @deprecated Use getVariableTypeInfo() instead
   */
  static getTypeInfo(name: string): TTypeInfo | undefined {
    return this.getVariableTypeInfo(name);
  }
 
  /**
   * Check if a variable type is registered (locally or in SymbolTable).
   * ADR-055 Phase 7: Uses getTSymbol for typed symbol lookup.
   */
  static hasVariableTypeInfo(name: string): boolean {
    if (this.typeRegistry.has(name)) {
      return true;
    }
    const symbol = this.symbolTable.getTSymbol(name);
    if (symbol?.kind === "variable" && symbol.type !== undefined) {
      return true;
    }
    // Issue #978: Check C symbols for external struct globals only
    const cSymbol = this.symbolTable.getCSymbol(name);
    if (cSymbol?.kind === "variable" && cSymbol.type) {
      const baseType = CodeGenState.stripTrailingPointers(cSymbol.type);
      return (
        this.symbolTable.isTypedefStructType(baseType) ||
        !!this.symbolTable.getStructFields(baseType)
      );
    }
    return false;
  }
 
  /**
   * Set variable type info in the local registry.
   */
  static setVariableTypeInfo(name: string, info: TTypeInfo): void {
    this.typeRegistry.set(name, info);
  }
 
  /**
   * Delete variable type info from the local registry.
   */
  static deleteVariableTypeInfo(name: string): void {
    this.typeRegistry.delete(name);
  }
 
  /**
   * Get a read-only view of the local type registry.
   * Used for passing to helper functions that need to iterate over types.
   * Note: This only returns locally registered types, not cross-file symbols.
   */
  static getTypeRegistryView(): ReadonlyMap<string, TTypeInfo> {
    return this.typeRegistry;
  }
 
  /**
   * Convert a TSymbol IVariableSymbol to TTypeInfo for unified type lookups.
   * ADR-055 Phase 7: Works with typed TSymbol instead of ISymbol.
   */
  /**
   * Strip trailing pointer stars from a C type string (e.g., "font_t*" → "font_t").
   * Uses string operations instead of regex to avoid SonarCloud ReDoS flag (S5852).
   */
  private static stripTrailingPointers(type: string): string {
    let end = type.length;
    while (end > 0 && type[end - 1] === "*") {
      end--;
    }
    return type.slice(0, end).trim();
  }
 
  private static convertTSymbolToTypeInfo(
    symbol: import("../types/symbols/IVariableSymbol").default,
  ): TTypeInfo {
    const typeName = TypeResolver.getTypeName(symbol.type);
 
    // Parse string capacity using regex
    const stringPattern = /^string<(\d+)>$/;
    const stringMatch = stringPattern.exec(typeName);
    const isString = stringMatch !== null;
    const stringCapacity = stringMatch
      ? Number.parseInt(stringMatch[1], 10)
      : undefined;
    // Use char for string types to match local convention
    const baseType = isString ? "char" : typeName;
 
    const isEnum = this.isKnownEnum(baseType);
 
    return {
      baseType,
      bitWidth: isString ? 8 : TYPE_WIDTH[baseType] || 0,
      isArray: symbol.isArray || false,
      arrayDimensions: symbol.arrayDimensions
        ?.map((d) => (typeof d === "number" ? d : Number.parseInt(d, 10)))
        .filter((n) => !Number.isNaN(n)),
      isConst: symbol.isConst || false,
      isAtomic: symbol.isAtomic || false,
      isEnum,
      enumTypeName: isEnum ? baseType : undefined,
      isString,
      stringCapacity,
    };
  }
 
  /**
   * Check if a parameter in a function is modified.
   */
  static isParameterModified(funcName: string, paramName: string): boolean {
    return this.modifiedParameters.get(funcName)?.has(paramName) ?? false;
  }
 
  /**
   * Compute unmodified parameters for all functions on-demand.
   * Returns a map of function name -> Set of parameter names NOT modified.
   * Computed from functionSignatures and modifiedParameters (no cached state).
   */
  static getUnmodifiedParameters(): Map<string, Set<string>> {
    const result = new Map<string, Set<string>>();
    for (const [funcName, signature] of this.functionSignatures) {
      const modifiedSet = this.modifiedParameters.get(funcName);
      const unmodified = new Set<string>();
      for (const param of signature.parameters) {
        if (!modifiedSet?.has(param.name)) {
          unmodified.add(param.name);
        }
      }
      result.set(funcName, unmodified);
    }
    return result;
  }
 
  /**
   * Check if a parameter should pass by value.
   */
  static isPassByValue(funcName: string, paramName: string): boolean {
    return this.passByValueParams.get(funcName)?.has(paramName) ?? false;
  }
 
  /**
   * Check if a parameter has subscript access.
   */
  static hasSubscriptAccess(funcName: string, paramName: string): boolean {
    return (
      this.subscriptAccessedParameters.get(funcName)?.has(paramName) ?? false
    );
  }
 
  /**
   * Get the function signature for a function.
   */
  static getFunctionSignature(name: string): IFunctionSignature | undefined {
    return this.functionSignatures.get(name);
  }
 
  /**
   * Get callback type info for a function name.
   */
  static getCallbackType(name: string): ICallbackTypeInfo | undefined {
    return this.callbackTypes.get(name);
  }
 
  /**
   * Issue #895: Get the typedef type string for a C typedef by name.
   * Used to look up function pointer typedef signatures for callback-compatible functions.
   *
   * @param typedefName - Name of the typedef (e.g., "flush_cb_t")
   * @returns The type string (e.g., "void (*)(widget_t *, const rect_t *, uint8_t *)") or undefined
   */
  static getTypedefType(typedefName: string): string | undefined {
    const symbol = this.symbolTable.getCSymbol(typedefName);
    Iif (symbol?.kind === "type") {
      return symbol.type;
    }
    return undefined;
  }
 
  /**
   * Check if a type name is a known C-Next function.
   */
  static isCNextFunction(name: string): boolean {
    return this.knownFunctions.has(name);
  }
 
  /**
   * Check if a name is a compile-time const value.
   */
  static isConstValue(name: string): boolean {
    return this.constValues.has(name);
  }
 
  /**
   * Get the compile-time value of a const.
   */
  static getConstValue(name: string): number | undefined {
    return this.constValues.get(name);
  }
 
  /**
   * Get parameter info from current function context.
   */
  static getParameterInfo(name: string): TParameterInfo | undefined {
    return this.currentParameters.get(name);
  }
 
  /**
   * Check if a name is a local variable.
   */
  static isLocalVariable(name: string): boolean {
    return this.localVariables.has(name);
  }
 
  /**
   * Check if a name is a local array.
   */
  static isLocalArray(name: string): boolean {
    return this.localArrays.has(name);
  }
 
  /**
   * Get members of a scope.
   */
  static getScopeMembers(scopeName: string): Set<string> | undefined {
    return this.scopeMembers.get(scopeName);
  }
 
  /**
   * Set members of a scope.
   */
  static setScopeMembers(scopeName: string, members: Set<string>): void {
    this.scopeMembers.set(scopeName, members);
  }
 
  /**
   * Get all scope members (for IGeneratorState).
   */
  static getAllScopeMembers(): ReadonlyMap<string, ReadonlySet<string>> {
    return this.scopeMembers;
  }
 
  /**
   * Check if an identifier is a member of the current scope.
   */
  static isCurrentScopeMember(identifier: string): boolean {
    if (!this.currentScope) return false;
    return this.scopeMembers.get(this.currentScope)?.has(identifier) ?? false;
  }
 
  /**
   * Resolve an identifier to its fully-scoped name.
   * Inside a scope, checks if the identifier is a scope member first.
   */
  static resolveIdentifier(identifier: string): string {
    if (this.currentScope) {
      const members = this.scopeMembers.get(this.currentScope);
      if (members?.has(identifier)) {
        return `${this.currentScope}_${identifier}`;
      }
    }
    return identifier;
  }
 
  /**
   * Get struct field type (simple lookup).
   */
  static getStructFieldType(
    structName: string,
    fieldName: string,
  ): string | undefined {
    return this.symbols?.structFields.get(structName)?.get(fieldName);
  }
 
  /**
   * Get struct field info including dimensions (checks SymbolTable then local symbols).
   */
  static getStructFieldInfo(
    structType: string,
    fieldName: string,
  ): { type: string; dimensions?: (number | string)[] } | null {
    // First check SymbolTable (C header structs)
    const fieldInfo = this.symbolTable.getStructFieldInfo(
      structType,
      fieldName,
    );
    if (fieldInfo) {
      return {
        type: fieldInfo.type,
        dimensions: fieldInfo.arrayDimensions,
      };
    }
 
    // Fall back to local C-Next struct fields
    const localFields = this.symbols?.structFields.get(structType);
    if (localFields) {
      const fieldType = localFields.get(fieldName);
      Eif (fieldType) {
        const fieldDimensions =
          this.symbols?.structFieldDimensions.get(structType);
        const dimensions = fieldDimensions?.get(fieldName);
        return {
          type: fieldType,
          dimensions: dimensions ? [...dimensions] : undefined,
        };
      }
    }
 
    return null;
  }
 
  /**
   * Get member type info for a struct field.
   * Returns full TTypeInfo for the field, or null if not found.
   */
  static getMemberTypeInfo(
    structType: string,
    memberName: string,
  ): TTypeInfo | null {
    const fieldInfo = this.getStructFieldInfo(structType, memberName);
    Iif (!fieldInfo) return null;
 
    const isArray =
      (fieldInfo.dimensions !== undefined && fieldInfo.dimensions.length > 0) ||
      (this.symbols?.structFieldArrays.get(structType)?.has(memberName) ??
        false);
    const dims = fieldInfo.dimensions?.filter(
      (d): d is number => typeof d === "number",
    );
 
    return {
      baseType: fieldInfo.type,
      bitWidth: TYPE_WIDTH[fieldInfo.type] ?? 32,
      isConst: false,
      isArray,
      arrayDimensions: dims && dims.length > 0 ? dims : undefined,
    };
  }
 
  /**
   * Check if a struct field is an array.
   */
  static isStructFieldArray(structName: string, fieldName: string): boolean {
    return (
      this.symbols?.structFieldArrays.get(structName)?.has(fieldName) ?? false
    );
  }
 
  /**
   * Get enum members for an enum.
   */
  static getEnumMembers(
    enumName: string,
  ): ReadonlyMap<string, number> | undefined {
    return this.symbols?.enumMembers.get(enumName);
  }
 
  /**
   * Build external struct fields from the symbol table.
   * Called once per run after all headers are processed.
   * Issue #355: Excludes array fields from init checking.
   */
  static buildExternalStructFields(): void {
    this.externalStructFields.clear();
    const allStructFields = this.symbolTable.getAllStructFields();
 
    for (const [structName, fieldMap] of allStructFields) {
      const nonArrayFields = new Set<string>();
      for (const [fieldName, fieldInfo] of fieldMap) {
        // Only include non-array fields in init checking
        if (
          !fieldInfo.arrayDimensions ||
          fieldInfo.arrayDimensions.length === 0
        ) {
          nonArrayFields.add(fieldName);
        }
      }
      if (nonArrayFields.size > 0) {
        this.externalStructFields.set(structName, nonArrayFields);
      }
    }
  }
 
  /**
   * Get external struct fields for initialization analysis.
   */
  static getExternalStructFields(): Map<string, Set<string>> {
    return this.externalStructFields;
  }
 
  /**
   * Get function return type.
   */
  static getFunctionReturnType(funcName: string): string | undefined {
    return this.symbols?.functionReturnTypes.get(funcName);
  }
 
  // ===========================================================================
  // INCLUDE FLAG HELPERS
  // ===========================================================================
 
  /**
   * Mark that stdint.h is needed.
   */
  static requireStdint(): void {
    this.needsStdint = true;
  }
 
  /**
   * Mark that stdbool.h is needed.
   */
  static requireStdbool(): void {
    this.needsStdbool = true;
  }
 
  /**
   * Mark that string.h is needed.
   */
  static requireString(): void {
    this.needsString = true;
  }
 
  /**
   * Mark that CMSIS headers are needed.
   */
  static requireCMSIS(): void {
    this.needsCMSIS = true;
  }
 
  /**
   * Mark that limits.h is needed.
   */
  static requireLimits(): void {
    this.needsLimits = true;
  }
 
  /**
   * Mark that ISR type is needed.
   */
  static requireISR(): void {
    this.needsISR = true;
  }
 
  // ===========================================================================
  // TYPE REGISTRATION HELPERS
  // ===========================================================================
 
  /**
   * Register a variable type.
   */
  static registerType(name: string, info: TTypeInfo): void {
    this.setVariableTypeInfo(name, info);
  }
 
  /**
   * Register a const value.
   */
  static registerConstValue(name: string, value: number): void {
    this.constValues.set(name, value);
  }
 
  /**
   * Register a local variable.
   */
  static registerLocalVariable(name: string, isArray: boolean = false): void {
    this.localVariables.add(name);
    if (isArray) {
      this.localArrays.add(name);
    }
  }
 
  /**
   * Register a function signature.
   */
  static registerFunctionSignature(
    name: string,
    sig: IFunctionSignature,
  ): void {
    this.functionSignatures.set(name, sig);
    this.knownFunctions.add(name);
  }
 
  /**
   * Register a callback type.
   */
  static registerCallbackType(name: string, info: ICallbackTypeInfo): void {
    this.callbackTypes.set(name, info);
  }
 
  /**
   * Register a callback field type.
   */
  static registerCallbackFieldType(key: string, typeName: string): void {
    this.callbackFieldTypes.set(key, typeName);
  }
 
  /**
   * Mark a clamp operation as used.
   */
  static markClampOpUsed(operation: string, cnxType: string): void {
    this.usedClampOps.add(`${operation}_${cnxType}`);
  }
 
  /**
   * Mark a safe div operation as used.
   */
  static markSafeDivOpUsed(operation: string, cnxType: string): void {
    this.usedSafeDivOps.add(`${operation}_${cnxType}`);
  }
 
  // ===========================================================================
  // FLOAT BIT SHADOW HELPERS
  // ===========================================================================
 
  /**
   * Register a float bit shadow variable.
   */
  static registerFloatBitShadow(name: string): void {
    this.floatBitShadows.add(name);
  }
 
  /**
   * Check if a float bit shadow exists.
   */
  static hasFloatBitShadow(name: string): boolean {
    return this.floatBitShadows.has(name);
  }
 
  /**
   * Mark a float shadow as having current value.
   */
  static markFloatShadowCurrent(name: string): void {
    this.floatShadowCurrent.add(name);
  }
 
  /**
   * Check if a float shadow has current value.
   */
  static isFloatShadowCurrent(name: string): boolean {
    return this.floatShadowCurrent.has(name);
  }
 
  // ===========================================================================
  // OPAQUE SCOPE VARIABLE HELPERS (Issue #948)
  // ===========================================================================
 
  /**
   * Mark a scope variable as having an opaque (forward-declared) struct type.
   * These are generated as pointers with NULL initialization.
   *
   * @param qualifiedName - The fully qualified variable name (e.g., "MyScope_widget")
   */
  static markOpaqueScopeVariable(qualifiedName: string): void {
    this.opaqueScopeVariables.add(qualifiedName);
  }
 
  /**
   * Check if a scope variable has an opaque type (and is thus a pointer).
   * Used during access generation to determine if & prefix is needed.
   *
   * @param qualifiedName - The fully qualified variable name (e.g., "MyScope_widget")
   * @returns true if this is an opaque scope variable (already a pointer)
   */
  static isOpaqueScopeVariable(qualifiedName: string): boolean {
    return this.opaqueScopeVariables.has(qualifiedName);
  }
 
  // ===========================================================================
  // C++ MODE HELPERS
  // ===========================================================================
 
  /**
   * Add a pending temp declaration for C++ mode.
   */
  static addPendingTempDeclaration(decl: string): void {
    this.pendingTempDeclarations.push(decl);
  }
 
  /**
   * Flush and return pending temp declarations.
   */
  static flushPendingTempDeclarations(): string[] {
    const decls = this.pendingTempDeclarations;
    this.pendingTempDeclarations = [];
    return decls;
  }
 
  /**
   * Get a unique temp variable name.
   */
  static getNextTempVarName(): string {
    return `_tmp${this.tempVarCounter++}`;
  }
}