All files / TRANSPILE/1-Analyze InitializationAnalyzer.ts

96.74% Statements 327/338
90.5% Branches 162/179
100% Functions 63/63
99.35% Lines 310/312

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                                                                                                        552x     552x     552x     552x 552x             610x     610x 610x     610x 610x 109x 137x 137x     137x 137x 137x 51x     137x         610x     610x 610x     651x 651x     651x 651x             599x       599x 203x     396x 396x 396x     396x 396x 396x 112x       396x   396x                           202x     202x 202x 202x   202x         202x       202x 202x 32x 32x       202x                       202x 117x       85x     85x 54x         31x             121x     121x     121x 121x       121x   150x                 150x 150x 99x               1999x     1999x 1848x   628x 628x     628x 628x 241x     387x             1999x                       628x 267x     361x     361x 1x       360x 360x 240x 240x 240x     120x                     361x 361x   361x   359x 359x   1x     1x             57x   57x 57x     57x 57x 57x     57x   57x                       55x               4x   4x     4x     4x 4x 4x       10x   10x                 10x 10x   10x     10x 10x 8x 8x 8x 8x     2x 2x 2x 2x 2x 2x       7x   7x 7x 6x 6x     10x 10x 10x 10x 10x   5x     5x                     554x   554x   554x           554x     554x     554x               488x 488x 322x       166x             218x                     166x 13x     153x 153x 146x   3x 2x         151x                         552x 552x 552x   552x     552x     552x     552x 552x   552x               552x   552x 870x 870x               870x 870x   163x 163x 163x     163x               870x 870x             102x         102x     102x 191x                       102x   102x 191x 191x   121x 121x     121x     102x                     132x 157x                     163x 163x 163x 163x                   163x 163x   51x 51x     51x 163x 51x                       163x 163x 3x 4x         163x 163x 1x       163x 163x 1x       163x 163x 1x                     163x 163x   2x 3x 3x 3x     2x 163x 1x                     163x 163x 6x                       191x 191x   40x 40x 40x 40x       40x 40x 40x     191x 191x             203x               552x 870x 870x 65x 65x   65x 137x 137x     65x                         1814x             1261x                                   639x         639x 639x         639x 639x   639x                   639x               301x 271x 34x   237x   271x               34x   34x   33x 33x   33x 85x   33x 27x               237x   237x   34x 34x 34x                           660x   660x   263x     397x 100x 297x 23x                             100x 86x 86x     14x 2x                             86x 86x   86x 6x                           2x 2x 1x                 361x                     147x                     136x                               5x 7x 7x 1x   7x                               30x 30x                               2x       2002x                               138x 1x     138x 138x       138x                 138x          
/**
 * Initialization Analyzer
 * Detects use of uninitialized variables (Rust-style E0381 errors)
 *
 * Phases:
 * 1. Linear code tracking
 * 2. Control flow (if/else branches)
 * 3. Loop analysis
 * 4. Scope tracking
 * 5. Function parameters (always initialized)
 * 7. Per-field struct tracking
 */
 
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../../PARSE/2-Parse/grammar/CNextListener";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import IInitializationError from "./types/IInitializationError";
import IDeclarationInfo from "./types/IDeclarationInfo";
import ScopeStack from "./ScopeStack";
import ExpressionUtils from "../../utils/ExpressionUtils";
import ParserUtils from "../../utils/ParserUtils";
import analyzePostfixOps from "../../utils/PostfixAnalysisUtils";
import SymbolTable from "../../PARSE/3-Declare/SymbolTable";
import ESourceLanguage from "../../utils/types/ESourceLanguage";
import ScopeUtils from "../../utils/ScopeUtils";
import type IAnalysisContext from "./types/IAnalysisContext";
 
/**
 * Tracks the initialization state of a variable
 */
interface IVariableState {
  /** Where the variable was declared */
  declaration: IDeclarationInfo;
  /** Whether the variable has been initialized */
  initialized: boolean;
  /** Type of the variable (for struct field tracking) */
  typeName: string | null;
  /** For structs: which fields have been initialized */
  initializedFields: Set<string>;
  /** Is this a struct type? */
  isStruct: boolean;
  /** Is this a string type? (string<N> or string) */
  isStringType: boolean;
}
 
/**
 * Listener that walks the parse tree and tracks initialization
 */
class InitializationListener extends CNextListener {
  private readonly analyzer: InitializationAnalyzer;
 
  /** Stack of saved states before each if statement */
  private readonly savedStates: Map<string, IVariableState>[] = [];
 
  /** Track when we're inside a function call's argument list */
  private inFunctionCallArgs: number = 0;
 
  /** Track nesting depth inside functions/methods (0 = global level) */
  private functionDepth: number = 0;
 
  constructor(analyzer: InitializationAnalyzer) {
    super();
    this.analyzer = analyzer;
  }
 
  // ========================================================================
  // Scope Entry/Exit
  // ========================================================================
 
  override enterFunctionDeclaration = (
    ctx: Parser.FunctionDeclarationContext,
  ): void => {
    this.functionDepth++;
    this.analyzer.enterScope();
 
    // Declare parameters as initialized
    const paramList = ctx.parameterList();
    if (paramList) {
      for (const param of paramList.parameter()) {
        const name = param.IDENTIFIER().getText();
        const { line, column } = ParserUtils.getPosition(param);
 
        // Get type name for struct tracking
        const typeCtx = param.type();
        let typeName: string | null = null;
        if (typeCtx.userType()) {
          typeName = typeCtx.userType()!.IDENTIFIER().getText();
        }
 
        this.analyzer.declareParameter(name, line, column, typeName);
      }
    }
  };
 
  override exitFunctionDeclaration = (
    _ctx: Parser.FunctionDeclarationContext,
  ): void => {
    this.analyzer.exitScope();
    this.functionDepth--;
  };
 
  override enterBlock = (_ctx: Parser.BlockContext): void => {
    this.analyzer.enterScope();
  };
 
  override exitBlock = (_ctx: Parser.BlockContext): void => {
    this.analyzer.exitScope();
  };
 
  // ========================================================================
  // Variable Declarations
  // ========================================================================
 
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    // Skip global variables - they're already handled by createGlobalScope()
    if (this.functionDepth === 0) {
      return;
    }
 
    const name = ctx.IDENTIFIER().getText();
    const { line, column } = ParserUtils.getPosition(ctx);
    const hasInitializer = ctx.expression() !== null;
 
    // Get type name for struct tracking
    const typeCtx = ctx.type();
    let typeName: string | null = null;
    if (typeCtx.userType()) {
      typeName = typeCtx.userType()!.IDENTIFIER().getText();
    }
 
    // Check if this is a string type (string<N> or string)
    const isStringType = typeCtx.stringType() !== null;
 
    this.analyzer.declareVariable(
      name,
      line,
      column,
      hasInitializer,
      typeName,
      isStringType,
    );
  };
 
  // ========================================================================
  // Assignments
  // ========================================================================
 
  override enterAssignmentStatement = (
    ctx: Parser.AssignmentStatementContext,
  ): void => {
    const targetCtx = ctx.assignmentTarget();
    const baseId = targetCtx.IDENTIFIER()?.getText();
    const postfixOps = targetCtx.postfixTargetOp();
 
    Iif (!baseId) {
      return;
    }
 
    // Resolve the assignment target ONCE (single source of truth)
    const target = this._resolveAssignmentTarget(baseId, postfixOps);
 
    // Issue #1012: Compound assignment reads the LHS before writing.
    // Check if the assignment operator is a compound operator (not simple `<-`).
    const isCompoundAssignment = ctx.assignmentOperator().ASSIGN() === null;
    if (isCompoundAssignment) {
      const { line, column } = ParserUtils.getPosition(ctx);
      this.analyzer.checkRead(target.varName, line, column, target.fieldName);
    }
 
    // Record the assignment to the resolved target
    this.analyzer.recordAssignment(target.varName, target.fieldName);
  };
 
  /**
   * Resolve an assignment target to its variable name and optional field name.
   * Single classification path used by both read checks and assignment recording.
   */
  private _resolveAssignmentTarget(
    baseId: string,
    postfixOps: Parser.PostfixTargetOpContext[],
  ): { varName: string; fieldName?: string } {
    // Simple variable: x <- value (no postfix ops)
    if (postfixOps.length === 0) {
      return { varName: baseId };
    }
 
    // Analyze postfix operations
    const { identifiers, hasSubscript } = analyzePostfixOps(baseId, postfixOps);
 
    // Member access: p.x <- value (struct field)
    if (identifiers.length >= 2 && !hasSubscript) {
      return { varName: identifiers[0], fieldName: identifiers[1] };
    }
 
    // Array access or mixed: arr[i] <- value or arr[i].field <- value
    // Consider the array/base as a whole
    return { varName: baseId };
  }
 
  // ========================================================================
  // Function Call Arguments (ADR-006: pass-by-reference may initialize)
  // ========================================================================
 
  override enterArgumentList = (_ctx: Parser.ArgumentListContext): void => {
    // When inside function call arguments, variables passed may be output params
    // We don't error on uninitialized reads, and we mark them as initialized after
    this.inFunctionCallArgs++;
  };
 
  override exitArgumentList = (ctx: Parser.ArgumentListContext): void => {
    this.inFunctionCallArgs--;
 
    // Mark any simple identifiers passed as arguments as initialized
    // (they might be output parameters that the function writes to)
    for (const expr of ctx.expression()) {
      // Walk down to find simple identifiers
      this.markArgumentsAsInitialized(expr);
    }
  };
 
  /**
   * Mark simple identifier arguments as initialized.
   * Only marks truly simple identifiers (not complex expressions like `a + b`).
   */
  private markArgumentsAsInitialized(expr: Parser.ExpressionContext): void {
    const identifier = ExpressionUtils.extractIdentifier(expr);
    if (identifier) {
      this.analyzer.recordAssignment(identifier);
    }
  }
 
  // ========================================================================
  // Variable Reads (in expressions)
  // ========================================================================
 
  override enterPrimaryExpression = (
    ctx: Parser.PrimaryExpressionContext,
  ): void => {
    if (this._shouldSkipReadCheck()) return;
    if (!ctx.IDENTIFIER()) return;
 
    const name = ctx.IDENTIFIER()!.getText();
    const { line, column } = ParserUtils.getPosition(ctx);
 
    // Check if this is part of a postfixExpression with member access
    const parent = ctx.parent as Parser.PostfixExpressionContext | undefined;
    if (this._handlePostfixExpression(parent, name, line, column)) {
      return;
    }
 
    this.analyzer.checkRead(name, line, column);
  };
 
  /**
   * Check if we should skip read checking in current context
   */
  private _shouldSkipReadCheck(): boolean {
    return this.analyzer.isInWriteContext() || this.inFunctionCallArgs > 0;
  }
 
  /**
   * Handle postfix expression member access. Returns true if handled.
   */
  private _handlePostfixExpression(
    parent: Parser.PostfixExpressionContext | undefined,
    name: string,
    line: number,
    column: number,
  ): boolean {
    if (!parent?.postfixOp || parent.postfixOp().length === 0) {
      return false;
    }
 
    const ops = parent.postfixOp();
 
    // Check if we should skip for .length on non-string types
    if (this._shouldSkipLengthCheck(name, ops)) {
      return true;
    }
 
    // If the first postfixOp is a member access, check the field
    const firstOpText = ops[0].getText();
    if (firstOpText.startsWith(".")) {
      const fieldName = firstOpText.slice(1);
      this.analyzer.checkRead(name, line, column, fieldName);
      return true;
    }
 
    return false;
  }
 
  /**
   * Issue #196 Bug 2: Check if we should skip init check for .length
   * on non-string types (compile-time property)
   */
  private _shouldSkipLengthCheck(
    name: string,
    ops: Parser.PostfixOpContext[],
  ): boolean {
    const varState = this.analyzer.lookupVariableState(name);
    const isStringType = varState?.isStringType ?? false;
 
    if (isStringType) return false;
 
    const lastOp = ops.at(-1)!.getText();
    if (lastOp !== ".length") return false;
 
    const firstOpText = ops[0].getText();
    // Skip if: direct .length or array element .length
    // Don't skip for struct member access (.field.length)
    return ops.length === 1 || firstOpText.startsWith("[");
  }
 
  // ========================================================================
  // Control Flow: If Statements
  // ========================================================================
 
  override enterIfStatement = (_ctx: Parser.IfStatementContext): void => {
    // Save current state before entering if
    const stateBefore = this.analyzer.cloneScopeState();
    this.savedStates.push(stateBefore);
  };
 
  override exitIfStatement = (ctx: Parser.IfStatementContext): void => {
    const stateBefore = this.savedStates.pop();
    Iif (!stateBefore) return;
 
    // Check if there's an else clause
    const hasElse = ctx.ELSE() !== null;
 
    if (hasElse) {
      // With else: the tree walker processes both branches in order.
      // If a variable is initialized in both branches, it ends up initialized.
      // If only one branch initializes it, it may or may not be initialized
      // depending on which branch ran last in the traversal.
      // For now, we'll trust the final state - this is optimistic but
      // often correct for the common pattern where both branches initialize.
      // (A more precise analysis would track both branches separately)
      // Don't restore - keep whatever state the branches produced.
    } else {
      // No else: the if might not execute, so restore to state before if
      // Any initializations inside the if are not guaranteed
      this.analyzer.restoreFromState(stateBefore);
    }
  };
 
  // ========================================================================
  // Control Flow: Loops
  // ========================================================================
 
  override enterWhileStatement = (_ctx: Parser.WhileStatementContext): void => {
    // Save state before loop - we'll restore after because loop might not run
    this.savedStates.push(this.analyzer.cloneScopeState());
  };
 
  override exitWhileStatement = (_ctx: Parser.WhileStatementContext): void => {
    // Loops are conservative: we assume they might not run at all
    // So we restore state to before the loop
    const stateBeforeLoop = this.savedStates.pop();
    Eif (stateBeforeLoop) {
      this.analyzer.restoreFromState(stateBeforeLoop);
    }
  };
 
  override enterForStatement = (_ctx: Parser.ForStatementContext): void => {
    // Save state before loop
    this.savedStates.push(this.analyzer.cloneScopeState());
  };
 
  /**
   * Check if a for-loop is deterministic (will definitely run at least once)
   * A loop is deterministic if it has the form: for (var <- 0; var < CONSTANT; ...)
   * where CONSTANT > 0
   */
  private isDeterministicForLoop(ctx: Parser.ForStatementContext): boolean {
    const init = ctx.forInit();
    const cond = ctx.expression();
 
    Iif (!init || !cond) return false;
 
    // Check if init is a variable declaration starting at 0
    const forVarDecl = init.forVarDecl();
    if (forVarDecl) {
      const initExpr = forVarDecl.expression();
      Iif (!initExpr) return false;
      const initText = initExpr.getText();
      if (initText !== "0") return false;
    } else {
      // forAssignment case: check if assigning 0
      const forAssign = init.forAssignment();
      Iif (!forAssign) return false;
      const assignExpr = forAssign.expression();
      Iif (!assignExpr) return false;
      const assignText = assignExpr.getText();
      if (assignText !== "0") return false;
    }
 
    // Check if condition is var < POSITIVE_CONSTANT
    const condText = cond.getText();
    // Match patterns like "i<4" or "ti<3" (no spaces in AST getText())
    const match = /^\w+<(\d+)$/.exec(condText);
    if (!match) return false;
    const bound = Number.parseInt(match[1], 10);
    return bound > 0;
  }
 
  override exitForStatement = (ctx: Parser.ForStatementContext): void => {
    const stateBeforeLoop = this.savedStates.pop();
    Eif (stateBeforeLoop) {
      const isDeterministic = this.isDeterministicForLoop(ctx);
      if (isDeterministic) {
        // Deterministic loop - preserve initialization (loop WILL run)
        this.analyzer.mergeInitializationState(stateBeforeLoop);
      } else {
        // Non-deterministic loop - conservative restore (loop might not run)
        this.analyzer.restoreFromState(stateBeforeLoop);
      }
    }
  };
}
 
/**
 * Analyzes C-Next AST for use-before-initialization errors
 */
class InitializationAnalyzer {
  /** #1456: handed in rather than read off shared state. */
  constructor(private readonly context: IAnalysisContext) {}
 
  private errors: IInitializationError[] = [];
 
  private scopeStack: ScopeStack<IVariableState> = new ScopeStack();
 
  /**
   * C-Next struct fields from current file (collected at analysis time).
   * External struct fields from C/C++ headers are accessed via CodeGenState.
   */
  private cnextStructFields: Map<string, Set<string>> = new Map();
 
  /** Track if we're processing a write target (left side of assignment) */
  private inWriteContext: boolean = false;
 
  /** Symbol table for checking C++ types (Issue #503) */
  private symbolTable: SymbolTable | null = null;
 
  /**
   * Get struct fields for a given struct type.
   * Checks C-Next structs first, then falls back to CodeGenState for external structs.
   */
  private getStructFields(structName: string): ReadonlySet<string> | undefined {
    // Check C-Next structs from current file first
    const cnextFields = this.cnextStructFields.get(structName);
    if (cnextFields) {
      return cnextFields;
    }
 
    // Check external structs from CodeGenState
    return this.context.program.externalStructFields().get(structName);
  }
 
  /**
   * Check if a type name is a known struct.
   */
  private isKnownStruct(typeName: string): boolean {
    return this.getStructFields(typeName) !== undefined;
  }
 
  /**
   * Issue #503: Check if a type name is a C++ class/struct
   * C++ classes with default constructors are automatically initialized.
   *
   * @param typeName The type name to check
   * @returns true if the type is from C++ (has constructor-based init)
   */
  private isCppClass(typeName: string): boolean {
    if (!this.symbolTable) {
      return false;
    }
 
    const symbols = this.symbolTable.getOverloads(typeName);
    for (const sym of symbols) {
      if (sym.sourceLanguage === ESourceLanguage.Cpp) {
        // C++ classes and structs have default constructors
        if (sym.kind === "struct" || sym.kind === "class") {
          return true;
        }
      }
    }
 
    return false;
  }
 
  /**
   * Analyze a parsed program for initialization errors
   * @param tree The parsed program AST
   * @param symbolTable Optional symbol table for C++ type detection
   * @returns Array of initialization errors
   */
  public analyze(
    tree: Parser.ProgramContext,
    symbolTable?: SymbolTable,
  ): IInitializationError[] {
    this.errors = [];
    this.scopeStack = new ScopeStack();
    this.symbolTable = symbolTable ?? null;
    // Clear C-Next struct fields from previous analysis (external fields come from CodeGenState)
    this.cnextStructFields = new Map();
 
    // First pass: collect struct definitions from current file
    this.collectStructDefinitions(tree);
 
    // Create global scope with all global/namespace variable declarations
    this.createGlobalScope(tree);
 
    // Second pass: analyze initialization
    const listener = new InitializationListener(this);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
 
    return this.errors;
  }
 
  /**
   * Create the global scope with all top-level variable declarations
   * Global variables are considered "initialized" (zero-init by ADR-015)
   */
  private createGlobalScope(tree: Parser.ProgramContext): void {
    this.enterScope(); // Create global scope
 
    for (const decl of tree.declaration()) {
      this._processGlobalVariable(decl);
      this._processScopeMembers(decl);
    }
  }
 
  /**
   * Process a global variable declaration
   */
  private _processGlobalVariable(decl: Parser.DeclarationContext): void {
    const varDecl = decl.variableDeclaration();
    if (!varDecl) return;
 
    const name = varDecl.IDENTIFIER().getText();
    const { line, column } = ParserUtils.getPosition(varDecl);
    const typeName = this._extractUserTypeName(varDecl.type());
 
    // Globals are always initialized (zero-init or explicit)
    this.declareVariable(name, line, column, true, typeName);
  }
 
  /**
   * Process scope member variable declarations (ADR-016)
   * Issue #1019: Scope members require explicit initialization like locals
   */
  private _processScopeMembers(decl: Parser.DeclarationContext): void {
    const scopeDecl = decl.scopeDeclaration();
    if (!scopeDecl) return;
 
    // #1298: the whole scope PATH, not its leaf name, so a nested scope keeps
    // its outer components when its members are qualified.
    // No `??` fallback: `IProgram.scopePathOf` returns `string` and already
    // answers the bare name on a miss, so a second fallback here is a guard
    // that cannot fire and reads as if the method could answer null.
    const scopePath = this.context.program.scopePathOf(
      scopeDecl.IDENTIFIER().getText(),
    );
 
    // Phase 1: Find all members assigned in any scope function
    const assignedMembers = this._findAssignedScopeMembers(scopeDecl);
 
    // Phase 2: Process each member with assignment info
    for (const member of scopeDecl.scopeMember()) {
      this._processScopeMemberVariable(member, scopePath, assignedMembers);
    }
  }
 
  /**
   * Scan all functions in a scope to find which members are assigned.
   * Issue #1019: A member assigned in ANY function is considered initialized
   * for reads in other functions within the same scope.
   */
  private _findAssignedScopeMembers(
    scopeDecl: Parser.ScopeDeclarationContext,
  ): Set<string> {
    const assigned = new Set<string>();
 
    for (const member of scopeDecl.scopeMember()) {
      const funcDecl = member.functionDeclaration();
      if (!funcDecl) continue;
 
      const body = funcDecl.block();
      Iif (!body) continue;
 
      // Scan the function body for assignments to scope members
      this._collectAssignmentsInBlock(body, assigned);
    }
 
    return assigned;
  }
 
  /**
   * Recursively collect variable names that are assigned in a block.
   * Looks for assignment statements targeting bare identifiers or this.member.
   */
  private _collectAssignmentsInBlock(
    block: Parser.BlockContext,
    assigned: Set<string>,
  ): void {
    for (const stmt of block.statement()) {
      this._collectAssignmentsInStatement(stmt, assigned);
    }
  }
 
  /**
   * Collect assignments from a single statement, recursing into nested blocks.
   */
  private _collectAssignmentsInStatement(
    stmt: Parser.StatementContext,
    assigned: Set<string>,
  ): void {
    this._collectDirectAssignment(stmt, assigned);
    this._collectFromControlFlow(stmt, assigned);
    this._collectFromSwitch(stmt, assigned);
    this._collectFromBlock(stmt, assigned);
  }
 
  /**
   * Collect assignment from the statement itself (if it's an assignment).
   */
  private _collectDirectAssignment(
    stmt: Parser.StatementContext,
    assigned: Set<string>,
  ): void {
    const assignStmt = stmt.assignmentStatement();
    if (!assignStmt) return;
 
    const target = assignStmt.assignmentTarget();
    Iif (!target) return;
 
    // Both bare identifier and this.member use the same IDENTIFIER token
    const id = target.IDENTIFIER()?.getText();
    if (id) {
      assigned.add(id);
    }
  }
 
  /**
   * Recurse into control flow statements (if, while, do-while, for).
   */
  private _collectFromControlFlow(
    stmt: Parser.StatementContext,
    assigned: Set<string>,
  ): void {
    // if statement
    const ifStmt = stmt.ifStatement();
    if (ifStmt) {
      for (const childStmt of ifStmt.statement()) {
        this._collectAssignmentsInStatement(childStmt, assigned);
      }
    }
 
    // while statement
    const whileBody = stmt.whileStatement()?.statement();
    if (whileBody) {
      this._collectAssignmentsInStatement(whileBody, assigned);
    }
 
    // do-while statement (Issue #1019 review feedback)
    const doWhileBody = stmt.doWhileStatement()?.block();
    if (doWhileBody) {
      this._collectAssignmentsInBlock(doWhileBody, assigned);
    }
 
    // for statement
    const forBody = stmt.forStatement()?.statement();
    if (forBody) {
      this._collectAssignmentsInStatement(forBody, assigned);
    }
  }
 
  /**
   * Recurse into switch statement cases.
   */
  private _collectFromSwitch(
    stmt: Parser.StatementContext,
    assigned: Set<string>,
  ): void {
    const switchStmt = stmt.switchStatement();
    if (!switchStmt) return;
 
    for (const switchCase of switchStmt.switchCase()) {
      const caseBlock = switchCase.block();
      Eif (caseBlock) {
        this._collectAssignmentsInBlock(caseBlock, assigned);
      }
    }
    const defaultBlock = switchStmt.defaultCase()?.block();
    if (defaultBlock) {
      this._collectAssignmentsInBlock(defaultBlock, assigned);
    }
  }
 
  /**
   * Recurse into standalone block statement.
   */
  private _collectFromBlock(
    stmt: Parser.StatementContext,
    assigned: Set<string>,
  ): void {
    const block = stmt.block();
    if (block) {
      this._collectAssignmentsInBlock(block, assigned);
    }
  }
 
  /**
   * Process a single scope member variable
   */
  private _processScopeMemberVariable(
    member: Parser.ScopeMemberContext,
    scopePath: string,
    assignedMembers: Set<string>,
  ): void {
    const memberVar = member.variableDeclaration();
    if (!memberVar) return;
 
    const varName = memberVar.IDENTIFIER().getText();
    const fullName = ScopeUtils.qualifyInScope(varName, scopePath); // Transpiled C name
    const { line, column } = ParserUtils.getPosition(memberVar);
    const typeName = this._extractUserTypeName(memberVar.type());
 
    // Issue #1019: Scope members are initialized if they have an inline
    // initializer OR are assigned in any function within the scope
    const hasInlineInit = memberVar.expression() !== null;
    const isAssignedInScope = assignedMembers.has(varName);
    const hasInitializer = hasInlineInit || isAssignedInScope;
 
    // Register with both raw name and transpiled C name for scope resolution
    this.declareVariable(varName, line, column, hasInitializer, typeName);
    this.declareVariable(fullName, line, column, hasInitializer, typeName);
  }
 
  /**
   * Extract user type name from a type context
   */
  private _extractUserTypeName(typeCtx: Parser.TypeContext): string | null {
    return typeCtx.userType()?.IDENTIFIER().getText() ?? null;
  }
 
  /**
   * Collect struct definitions from current file to know their fields.
   * This supplements the external struct fields from CodeGenState.
   */
  private collectStructDefinitions(tree: Parser.ProgramContext): void {
    for (const decl of tree.declaration()) {
      const structDecl = decl.structDeclaration();
      if (structDecl) {
        const structName = structDecl.IDENTIFIER().getText();
        const fields = new Set<string>();
 
        for (const member of structDecl.structMember()) {
          const fieldName = member.IDENTIFIER().getText();
          fields.add(fieldName);
        }
 
        this.cnextStructFields.set(structName, fields);
      }
    }
  }
 
  // ========================================================================
  // Scope Management (delegated to ScopeStack)
  // ========================================================================
 
  /**
   * Enter a new scope (function, block, etc.)
   */
  public enterScope(): void {
    this.scopeStack.enterScope();
  }
 
  /**
   * Exit the current scope
   */
  public exitScope(): void {
    this.scopeStack.exitScope();
  }
 
  // ========================================================================
  // Variable Tracking
  // ========================================================================
 
  /**
   * Declare a variable (may or may not be initialized)
   */
  public declareVariable(
    name: string,
    line: number,
    column: number,
    hasInitializer: boolean,
    typeName: string | null,
    isStringType: boolean = false,
  ): void {
    Iif (!this.scopeStack.hasActiveScope()) {
      // Global scope - create implicit scope
      this.enterScope();
    }
 
    const isStruct = typeName !== null && this.isKnownStruct(typeName);
    const fields = isStruct
      ? this.getStructFields(typeName)!
      : new Set<string>();
 
    // Issue #503: C++ classes with default constructors are automatically initialized
    const isCppClassType = typeName !== null && this.isCppClass(typeName);
    const isInitialized = hasInitializer || isCppClassType;
 
    const state: IVariableState = {
      declaration: { name, line, column },
      initialized: isInitialized,
      typeName,
      isStruct,
      isStringType,
      // If initialized with full struct initializer or C++ class, all fields are initialized
      initializedFields: isInitialized ? new Set(fields) : new Set(),
    };
 
    this.scopeStack.declare(name, state);
  }
 
  /**
   * Record that a variable (or field) has been assigned
   * SonarCloud S3776: Refactored to use helper methods.
   */
  public recordAssignment(name: string, field?: string): void {
    this.scopeStack.update(name, (state) => {
      if (field) {
        this.recordFieldAssignment(state, field);
      } else {
        this.recordWholeAssignment(state);
      }
      return state;
    });
  }
 
  /**
   * Handle field-level assignment.
   */
  private recordFieldAssignment(state: IVariableState, field: string): void {
    state.initializedFields.add(field);
    // Check if all fields are now initialized
    if (!state.isStruct || !state.typeName) return;
 
    const allFields = this.getStructFields(state.typeName);
    Iif (!allFields) return;
 
    const allInitialized = [...allFields].every((f) =>
      state.initializedFields.has(f),
    );
    if (allInitialized) {
      state.initialized = true;
    }
  }
 
  /**
   * Handle whole-variable assignment.
   */
  private recordWholeAssignment(state: IVariableState): void {
    state.initialized = true;
    // Mark all fields as initialized too
    if (!state.isStruct || !state.typeName) return;
 
    const fields = this.getStructFields(state.typeName);
    Eif (fields) {
      state.initializedFields = new Set(fields);
    }
  }
 
  /**
   * Check if a variable (or field) is used before initialization
   * SonarCloud S3776: Refactored to use helper methods.
   */
  public checkRead(
    name: string,
    line: number,
    column: number,
    field?: string,
  ): void {
    const state = this.scopeStack.lookup(name);
 
    if (!state) {
      // Variable not found - let undefined variable handling deal with it
      return;
    }
 
    if (field) {
      this.checkFieldRead(name, line, column, field, state);
    } else if (!state.initialized) {
      this.addError(name, line, column, state.declaration, false);
    }
  }
 
  /**
   * Check field read for uninitialized access.
   * SonarCloud S3776: Extracted from checkRead().
   */
  private checkFieldRead(
    name: string,
    line: number,
    column: number,
    field: string,
    state: IVariableState,
  ): void {
    if (state.isStruct && state.typeName) {
      this.checkStructFieldRead(name, line, column, field, state);
      return;
    }
 
    if (state.isStringType) {
      this.checkStringPropertyRead(name, line, column, field, state);
    }
    // Other types: .field is a compile-time property, no check needed
  }
 
  /**
   * Check struct field read for initialization.
   */
  private checkStructFieldRead(
    name: string,
    line: number,
    column: number,
    field: string,
    state: IVariableState,
  ): void {
    const structFieldSet = this.getStructFields(state.typeName!);
    Iif (!structFieldSet?.has(field)) return;
 
    if (!state.initializedFields.has(field)) {
      this.addError(`${name}.${field}`, line, column, state.declaration, false);
    }
  }
 
  /**
   * Check string property read for initialization.
   */
  private checkStringPropertyRead(
    name: string,
    line: number,
    column: number,
    field: string,
    state: IVariableState,
  ): void {
    const runtimeProperties = ["length", "capacity", "size"];
    if (runtimeProperties.includes(field) && !state.initialized) {
      this.addError(name, line, column, state.declaration, false);
    }
  }
 
  /**
   * Public method to look up variable state
   * Issue #196 Bug 2: Used by visitor to check if variable is string type
   */
  public lookupVariableState(name: string): IVariableState | null {
    return this.scopeStack.lookup(name);
  }
 
  // ========================================================================
  // Control Flow (using ScopeStack's clone/restore)
  // ========================================================================
 
  /**
   * Clone the current scope state for branch analysis
   */
  public cloneScopeState(): Map<string, IVariableState> {
    return this.scopeStack.cloneState((state) => ({
      ...state,
      initializedFields: new Set(state.initializedFields),
    }));
  }
 
  /**
   * Restore initialization state from a saved snapshot
   * Used for control flow analysis to "undo" branch changes
   */
  public restoreFromState(savedState: Map<string, IVariableState>): void {
    this.scopeStack.restoreState(savedState, (_current, saved) => ({
      ...saved,
      initializedFields: new Set(saved.initializedFields),
    }));
  }
 
  /**
   * Merge initialization state from a saved snapshot
   * Used for deterministic loops where initialization inside the loop
   * should be preserved (the loop WILL run at least once)
   */
  public mergeInitializationState(
    beforeState: Map<string, IVariableState>,
  ): void {
    // For each variable, keep current init state but merge in any fields
    // that were initialized before the loop
    for (const [name, beforeVar] of beforeState) {
      this.scopeStack.update(name, (currentState) => {
        for (const field of beforeVar.initializedFields) {
          currentState.initializedFields.add(field);
        }
        return currentState;
      });
    }
  }
 
  // ========================================================================
  // Error Reporting
  // ========================================================================
 
  private addError(
    variable: string,
    line: number,
    column: number,
    declaration: IDeclarationInfo,
    mayBeUninitialized: boolean,
  ): void {
    const certainty = mayBeUninitialized ? "possibly " : "";
    this.errors.push({
      code: "E0381",
      variable,
      line,
      column,
      declaration,
      mayBeUninitialized,
      message: `use of ${certainty}uninitialized variable '${variable}'`,
    });
  }
 
  // ========================================================================
  // Write Context Tracking
  // ========================================================================
 
  public setWriteContext(inWrite: boolean): void {
    this.inWriteContext = inWrite;
  }
 
  public isInWriteContext(): boolean {
    return this.inWriteContext;
  }
 
  // ========================================================================
  // Function Parameters
  // ========================================================================
 
  /**
   * Declare function parameters (always initialized by caller)
   */
  public declareParameter(
    name: string,
    line: number,
    column: number,
    typeName: string | null,
  ): void {
    if (!this.scopeStack.hasActiveScope()) {
      this.enterScope();
    }
 
    const isStruct = typeName !== null && this.isKnownStruct(typeName);
    const fields = isStruct
      ? this.getStructFields(typeName)!
      : new Set<string>();
 
    const state: IVariableState = {
      declaration: { name, line, column },
      initialized: true, // Parameters are always initialized by caller
      typeName,
      isStruct,
      isStringType: false, // Not tracked for parameters since they're always initialized
      initializedFields: new Set(fields), // All fields initialized
    };
 
    this.scopeStack.declare(name, state);
  }
}
 
export default InitializationAnalyzer;