All files / transpiler/logic/analysis NullCheckAnalyzer.ts

99.22% Statements 257/259
90.6% Branches 135/149
100% Functions 46/46
99.59% Lines 246/247

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                                                                  14x                                                                                                                                                                                                                                   14x                           14x   14x   14x                                                                                 227x     227x     227x     227x     227x             227x             227x     227x     227x           227x     227x     227x 227x                     258x             258x             258x 258x 258x   258x             36x 36x 36x 36x 4x   4x             45x 45x 45x 45x 45x 45x                           60x 58x                       258x       258x     258x       258x             46x   46x 46x     46x       46x 34x 34x 34x     34x             34x   24x       12x               46x 46x 46x       46x   7x 7x 6x       46x               422x 422x 422x               422x 369x     53x 53x 2x     51x 51x 24x                 422x 406x     16x 16x 2x     14x 14x 5x             35x       35x 8x               7x   7x 7x     7x   7x 5x     5x           5x     2x             7x 7x 7x             720x         720x     720x 768x 768x 48x 48x 48x   48x 48x                     48x   48x 48x 96x   96x 46x     48x     720x       720x 720x 720x 768x 768x 48x 48x       720x     48x 48x 48x 48x               802x     802x 802x   352x 352x     352x 194x 194x     352x   157x     157x 6x 6x       151x 95x   3x 92x         26x         151x                       151x   148x 159x 159x     135x 135x 230x   230x 36x 36x 8x 8x 8x                               431x 431x     431x 45x   45x   44x 40x       1x               44x     1x                 215x     215x 215x 215x 215x 215x 215x     215x 60x     215x   175x     175x   56x     56x 4x                 56x       119x 1x 1x       118x   7x 7x 5x           215x   215x     57x       57x 57x 57x 57x 57x   57x   11x   10x   10x 10x     1x       57x   57x                     232x     232x 2708x 67x         165x 657x 1x       164x               227x     227x               227x 227x     227x     227x 227x   227x             227x 33x 33x 33x 33x                 3x                     26x                                   7x                           1x                                     1x                                       4x                                     5x                                   1x                                     8x                                   448x                 15x   14x   11x 9x                 2x             8x             7x                 2x          
/**
 * Null Check Analyzer
 * Enforces NULL safety for C library interop (ADR-046)
 *
 * C-Next eliminates null bugs by design. This analyzer provides a controlled
 * exception for C interop: Variables storing nullable C pointer returns must
 * use the c_ prefix to indicate they hold C interop values.
 *
 * Rules:
 * - C functions returning nullable pointers require c_ prefix for storage
 * - NULL keyword only valid in equality comparison context (= or !=)
 * - Dynamic allocation functions (malloc, etc.) remain forbidden (ADR-003)
 */
 
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../parser/grammar/CNextListener";
import * as Parser from "../parser/grammar/CNextParser";
import INullCheckError from "./types/INullCheckError";
import ParserUtils from "../../../utils/ParserUtils";
 
/**
 * Metadata for C library functions that can return NULL
 */
interface ICLibraryFunction {
  header: string;
  nullMeaning: string;
  docsUrl: string;
}
 
/**
 * C library functions that return nullable pointers
 * These require the c_ prefix when stored in variables (ADR-046)
 */
const NULLABLE_C_FUNCTIONS: Map<string, ICLibraryFunction> = new Map([
  // Stream I/O
  [
    "fgets",
    {
      header: "stdio.h",
      nullMeaning: "EOF or error",
      docsUrl: "https://en.cppreference.com/w/c/io/fgets",
    },
  ],
  [
    "fputs",
    {
      header: "stdio.h",
      nullMeaning: "Write error (EOF)",
      docsUrl: "https://en.cppreference.com/w/c/io/fputs",
    },
  ],
  [
    "fgetc",
    {
      header: "stdio.h",
      nullMeaning: "EOF or error",
      docsUrl: "https://en.cppreference.com/w/c/io/fgetc",
    },
  ],
  [
    "fputc",
    {
      header: "stdio.h",
      nullMeaning: "Write error (EOF)",
      docsUrl: "https://en.cppreference.com/w/c/io/fputc",
    },
  ],
  [
    "gets",
    {
      header: "stdio.h",
      nullMeaning: "EOF or error (DEPRECATED)",
      docsUrl: "https://en.cppreference.com/w/c/io/gets",
    },
  ],
  // File handling (now allowed with c_ prefix)
  [
    "fopen",
    {
      header: "stdio.h",
      nullMeaning: "Failed to open file",
      docsUrl: "https://en.cppreference.com/w/c/io/fopen",
    },
  ],
  [
    "freopen",
    {
      header: "stdio.h",
      nullMeaning: "Failed to reopen",
      docsUrl: "https://en.cppreference.com/w/c/io/freopen",
    },
  ],
  [
    "tmpfile",
    {
      header: "stdio.h",
      nullMeaning: "Failed to create temp file",
      docsUrl: "https://en.cppreference.com/w/c/io/tmpfile",
    },
  ],
  // String functions
  [
    "strstr",
    {
      header: "string.h",
      nullMeaning: "Substring not found",
      docsUrl: "https://en.cppreference.com/w/c/string/byte/strstr",
    },
  ],
  [
    "strchr",
    {
      header: "string.h",
      nullMeaning: "Character not found",
      docsUrl: "https://en.cppreference.com/w/c/string/byte/strchr",
    },
  ],
  [
    "strrchr",
    {
      header: "string.h",
      nullMeaning: "Character not found",
      docsUrl: "https://en.cppreference.com/w/c/string/byte/strrchr",
    },
  ],
  [
    "memchr",
    {
      header: "string.h",
      nullMeaning: "Byte not found",
      docsUrl: "https://en.cppreference.com/w/c/string/byte/memchr",
    },
  ],
  // Environment
  [
    "getenv",
    {
      header: "stdlib.h",
      nullMeaning: "Variable not found",
      docsUrl: "https://en.cppreference.com/w/c/program/getenv",
    },
  ],
]);
 
/**
 * Functions that remain forbidden (dynamic allocation - ADR-003)
 */
const FORBIDDEN_FUNCTIONS: Set<string> = new Set([
  "malloc",
  "calloc",
  "realloc",
  "free",
]);
 
// ============================================================================
// Flow Analysis Data Structures (E0908)
// ============================================================================
 
/**
 * State of a nullable variable with respect to NULL checking
 */
enum NullCheckState {
  /** Variable has not been checked for NULL */
  Unchecked = "unchecked",
  /** Variable has been verified as not NULL */
  CheckedNotNull = "checked_not_null",
}
 
/**
 * Tracks the NULL check state of a single nullable variable
 */
interface INullableVariableState {
  /** Variable name (with c_ prefix) */
  name: string;
  /** Line where the variable was declared */
  declarationLine: number;
  /** Type name (e.g., FILE, cstring) */
  typeName: string;
  /** Current NULL check state */
  state: NullCheckState;
}
 
/**
 * A scope for tracking nullable variable states.
 * Scopes form a stack: function body -> if body -> nested if body, etc.
 */
interface INullCheckScope {
  /** Map of variable name to state within this scope */
  variables: Map<string, INullableVariableState>;
  /** Parent scope (null for function-level scope) */
  parent: INullCheckScope | null;
  /** If this scope is from an if-statement, tracks if it's a guard clause */
  isGuardClause: boolean;
  /** Variable being checked in the if condition (for guard clause detection) */
  guardVariable: string | null;
  /** Whether the condition was == NULL (true) or != NULL (false) */
  isNullEqualityCheck: boolean;
}
 
/**
 * Listener that walks the parse tree and checks NULL usage
 */
class NullCheckListener extends CNextListener {
  private readonly analyzer: NullCheckAnalyzer;
 
  /** Whether we're currently inside an equality comparison (= or !=) */
  private inEqualityComparison = false;
 
  /** Track the function name in the current equality comparison (if any) */
  private equalityComparisonFuncName: string | null = null;
 
  /** Track if the current equality comparison contains NULL */
  private equalityComparisonHasNull = false;
 
  /** Track variable names in the current equality comparison */
  private equalityComparisonVarNames: string[] = [];
 
  /** Whether we're currently inside a variable declaration (with c_ prefix handling) */
  private inVariableDeclarationWithNullable = false;
 
  // ========================================================================
  // Flow Analysis State (E0908)
  // ========================================================================
 
  /** Current scope for tracking nullable variable states */
  private currentScope: INullCheckScope | null = null;
 
  /** Stack of if-statement info for tracking nested conditions */
  private readonly ifStack: Array<{
    varName: string | null;
    isNullCheck: boolean;
    hasReturn: boolean;
  }> = [];
 
  /** Track if we're in the body of an if statement (first statement) */
  private readonly inIfBody = false;
 
  /** Track the current if-statement context for body detection */
  private currentIfCtx: Parser.IfStatementContext | null = null;
 
  /** Stack of while-statement info for tracking nested while conditions */
  private readonly whileStack: Array<{
    varName: string | null;
    isNotNullCheck: boolean;
  }> = [];
 
  /** Track the current while-statement context for body detection */
  private currentWhileCtx: Parser.WhileStatementContext | null = null;
 
  constructor(analyzer: NullCheckAnalyzer) {
    super();
    this.analyzer = analyzer;
  }
 
  // ========================================================================
  // Scope Management (E0908)
  // ========================================================================
 
  /**
   * Create a new scope (e.g., entering a function or if-body)
   */
  private pushScope(): void {
    const newScope: INullCheckScope = {
      variables: new Map(),
      parent: this.currentScope,
      isGuardClause: false,
      guardVariable: null,
      isNullEqualityCheck: false,
    };
    this.currentScope = newScope;
  }
 
  /**
   * Exit the current scope and return to parent
   */
  private popScope(): INullCheckScope | null {
    const oldScope = this.currentScope;
    Eif (this.currentScope) {
      this.currentScope = this.currentScope.parent;
    }
    return oldScope;
  }
 
  /**
   * Look up a variable's state in the current scope chain
   */
  private lookupVariable(name: string): INullableVariableState | null {
    let scope = this.currentScope;
    while (scope) {
      const state = scope.variables.get(name);
      if (state) return state;
      scope = scope.parent;
    }
    return null;
  }
 
  /**
   * Update a variable's state in the scope where it's defined
   */
  private updateVariableState(name: string, newState: NullCheckState): void {
    let scope = this.currentScope;
    while (scope) {
      Eif (scope.variables.has(name)) {
        const varState = scope.variables.get(name)!;
        varState.state = newState;
        return;
      }
      scope = scope.parent;
    }
  }
 
  /**
   * Register a c_ prefixed variable in the current scope
   */
  private registerNullableVariable(
    name: string,
    typeName: string,
    line: number,
  ): void {
    if (!this.currentScope) return;
    this.currentScope.variables.set(name, {
      name,
      declarationLine: line,
      typeName,
      state: NullCheckState.Unchecked,
    });
  }
 
  // ========================================================================
  // Function Scope Management (E0908)
  // ========================================================================
 
  override enterFunctionDeclaration = (
    _ctx: Parser.FunctionDeclarationContext,
  ): void => {
    // Create a new scope for the function body
    this.pushScope();
  };
 
  override exitFunctionDeclaration = (
    _ctx: Parser.FunctionDeclarationContext,
  ): void => {
    // Exit the function scope
    this.popScope();
  };
 
  // ========================================================================
  // If-Statement Flow Analysis (E0908)
  // ========================================================================
 
  override enterIfStatement = (ctx: Parser.IfStatementContext): void => {
    // Parse the condition to detect NULL checks
    const condition = ctx.expression();
    const conditionText = condition?.getText() ?? "";
 
    // Check for patterns like "c_var != NULL" or "c_var = NULL"
    const nullCheckMatch = /^(c_[a-zA-Z_]\w*)\s*(!?=)\s*NULL$/.exec(
      conditionText,
    );
 
    if (nullCheckMatch) {
      const varName = nullCheckMatch[1];
      const operator = nullCheckMatch[2];
      const isNotNullCheck = operator === "!=";
 
      // Push info onto the if-stack for tracking
      this.ifStack.push({
        varName,
        isNullCheck: !isNotNullCheck, // true if checking == NULL
        hasReturn: false,
      });
 
      // For != NULL check, mark the variable as checked in the if-body
      if (isNotNullCheck) {
        // We'll set state to CheckedNotNull when entering the if-body
        this.currentIfCtx = ctx;
      }
    } else {
      // Not a null check, just track for nesting
      this.ifStack.push({
        varName: null,
        isNullCheck: false,
        hasReturn: false,
      });
    }
  };
 
  override exitIfStatement = (ctx: Parser.IfStatementContext): void => {
    const ifInfo = this.ifStack.pop();
    Iif (!ifInfo) return;
 
    // Handle guard clause pattern: if (c_var == NULL) { return; }
    // After such a guard, the variable is known to be not null
    if (ifInfo.varName && ifInfo.isNullCheck && ifInfo.hasReturn) {
      // This was a guard clause - the variable is checked after the if
      const hasElse = ctx.ELSE() !== null;
      if (!hasElse) {
        this.updateVariableState(ifInfo.varName, NullCheckState.CheckedNotNull);
      }
    }
 
    this.currentIfCtx = null;
  };
 
  /**
   * Detect when we enter the body of an if or while statement
   * For "if (c_var != NULL)" or "while (c_var != NULL)" the body has the variable checked
   * SonarCloud S3776: Refactored to use helper methods.
   */
  override enterStatement = (ctx: Parser.StatementContext): void => {
    this.handleIfBranchNullCheck(ctx);
    this.handleWhileBodyNullCheck(ctx);
  };
 
  /**
   * Handle null-check for if statement "then" branch.
   * SonarCloud S3776: Extracted from enterStatement().
   */
  private handleIfBranchNullCheck(ctx: Parser.StatementContext): void {
    if (!this.currentIfCtx || this.ifStack.length === 0) {
      return;
    }
 
    const ifInfo = this.ifStack.at(-1)!;
    if (ifInfo.isNullCheck || !ifInfo.varName) {
      return;
    }
 
    const statements = this.currentIfCtx.statement();
    if (statements.length > 0 && ctx === statements[0]) {
      this.updateVariableState(ifInfo.varName, NullCheckState.CheckedNotNull);
    }
  }
 
  /**
   * Handle null-check for while statement body.
   * SonarCloud S3776: Extracted from enterStatement().
   */
  private handleWhileBodyNullCheck(ctx: Parser.StatementContext): void {
    if (!this.currentWhileCtx || this.whileStack.length === 0) {
      return;
    }
 
    const whileInfo = this.whileStack.at(-1)!;
    if (!whileInfo.varName || !whileInfo.isNotNullCheck) {
      return;
    }
 
    const whileBody = this.currentWhileCtx.statement();
    if (whileBody === ctx) {
      this.updateVariableState(
        whileInfo.varName,
        NullCheckState.CheckedNotNull,
      );
    }
  }
 
  override enterReturnStatement = (
    _ctx: Parser.ReturnStatementContext,
  ): void => {
    // Mark current if-statement (if any) as having a return
    if (this.ifStack.length > 0) {
      this.ifStack.at(-1)!.hasReturn = true;
    }
  };
 
  // ========================================================================
  // While-Statement Flow Analysis (E0908)
  // ========================================================================
 
  override enterWhileStatement = (ctx: Parser.WhileStatementContext): void => {
    // Parse the condition to detect NULL checks
    const condition = ctx.expression();
    const conditionText = condition?.getText() ?? "";
 
    // Check for patterns like "c_var != NULL"
    const nullCheckMatch = /^(c_[a-zA-Z_]\w*)\s*!=\s*NULL$/.exec(conditionText);
 
    if (nullCheckMatch) {
      const varName = nullCheckMatch[1];
 
      // Push info onto the while-stack for tracking
      this.whileStack.push({
        varName,
        isNotNullCheck: true,
      });
 
      // For != NULL check, mark the variable as checked in the while-body
      this.currentWhileCtx = ctx;
    } else {
      // Not a null check, just track for nesting
      this.whileStack.push({
        varName: null,
        isNotNullCheck: false,
      });
    }
  };
 
  override exitWhileStatement = (_ctx: Parser.WhileStatementContext): void => {
    this.whileStack.pop();
    this.currentWhileCtx = null;
  };
 
  // ========================================================================
  // Equality Comparison Context
  // ========================================================================
 
  override enterEqualityExpression = (
    ctx: Parser.EqualityExpressionContext,
  ): void => {
    // Check if this is actually a comparison (has = or !=)
    // The grammar has equalityExpression : relationalExpression (('=' | '!=') relationalExpression)*
    const children = ctx.children ?? [];
 
    // Look for comparison operators
    for (const child of children) {
      const text = child.getText();
      if (text === "=" || text === "!=") {
        this.inEqualityComparison = true;
        this.equalityComparisonFuncName = null;
        this.equalityComparisonHasNull = false;
        // Extract variable names from the comparison
        this.equalityComparisonVarNames = this.extractVariableNames(ctx);
        return;
      }
    }
  };
 
  /**
   * Extract simple variable names from an equality expression
   */
  private extractVariableNames(
    ctx: Parser.EqualityExpressionContext,
  ): string[] {
    const names: string[] = [];
    // Get relational expressions (left and right sides of comparison)
    const children = ctx.relationalExpression();
    for (const child of children) {
      const text = child.getText();
      // Simple check: if it's a simple identifier and not NULL, add it
      if (/^[a-zA-Z_]\w*$/.test(text) && text !== "NULL") {
        names.push(text);
      }
    }
    return names;
  }
 
  override exitEqualityExpression = (
    ctx: Parser.EqualityExpressionContext,
  ): void => {
    // Check if this was a comparison (has = or !=)
    const children = ctx.children ?? [];
    let isComparison = false;
    for (const child of children) {
      const text = child.getText();
      if (text === "=" || text === "!=") {
        isComparison = true;
        break;
      }
    }
 
    if (isComparison) {
      // If we had a stream function in this comparison, it's OK
      // (the function was used correctly in a NULL check)
      this.inEqualityComparison = false;
      this.equalityComparisonFuncName = null;
      this.equalityComparisonHasNull = false;
      this.equalityComparisonVarNames = [];
    }
  };
 
  // ========================================================================
  // Function Calls
  // ========================================================================
 
  override enterPostfixExpression = (
    ctx: Parser.PostfixExpressionContext,
  ): void => {
    const primary = ctx.primaryExpression();
    if (!primary?.IDENTIFIER()) return;
 
    const funcName = primary.IDENTIFIER()!.getText();
    const ops = ctx.postfixOp();
 
    // Check if it's a function call (has argument list or parens)
    const isCall = ops.some((op) => {
      const text = op.getText();
      return text.startsWith("(");
    });
 
    if (!isCall) return;
 
    const { line, column } = ParserUtils.getPosition(ctx);
 
    // Check forbidden functions (always an error)
    if (FORBIDDEN_FUNCTIONS.has(funcName)) {
      this.analyzer.reportForbiddenFunction(funcName, line, column);
      return;
    }
 
    // Check nullable C functions
    if (NULLABLE_C_FUNCTIONS.has(funcName)) {
      if (this.inEqualityComparison) {
        // Track that we found a stream function in this comparison
        this.equalityComparisonFuncName = funcName;
      } else if (this.inVariableDeclarationWithNullable) {
        // Inside a variable declaration - E0905 or valid c_ prefix already handled
        // Don't also report E0901
      } else {
        // Stream function used outside of NULL comparison - error
        this.analyzer.reportMissingNullCheck(funcName, line, column);
      }
    }
 
    // E0908: Check for unchecked c_ variables passed as function arguments
    this.checkFunctionArgumentsForUncheckedVariables(ctx, ops, line);
  };
 
  /**
   * Check if any c_ prefixed variables in function arguments are unchecked (E0908)
   */
  private checkFunctionArgumentsForUncheckedVariables(
    ctx: Parser.PostfixExpressionContext,
    ops: Parser.PostfixOpContext[],
    line: number,
  ): void {
    // Skip if we're in a NULL comparison context (the check itself)
    if (this.inEqualityComparison) return;
 
    for (const op of ops) {
      const argList = op.argumentList();
      if (!argList) continue;
 
      // Get all expressions in the argument list
      const args = argList.expression();
      for (const arg of args) {
        const argText = arg.getText();
        // Check if argument is a simple c_ prefixed variable
        if (/^c_[a-zA-Z_]\w*$/.test(argText)) {
          const varState = this.lookupVariable(argText);
          if (varState?.state === NullCheckState.Unchecked) {
            const argLine = arg.start?.line ?? line;
            const argColumn = arg.start?.column ?? 0;
            this.analyzer.reportMissingNullCheckBeforeUse(
              argText,
              varState.typeName,
              argLine,
              argColumn,
            );
          }
        }
      }
    }
  }
 
  // ========================================================================
  // NULL Literal
  // ========================================================================
 
  override enterLiteral = (ctx: Parser.LiteralContext): void => {
    const text = ctx.getText();
 
    // Check for uppercase NULL (C library NULL)
    if (text === "NULL") {
      const { line, column } = ParserUtils.getPosition(ctx);
 
      if (this.inEqualityComparison) {
        // Check if any compared variable lacks c_ prefix and is not a nullable C function
        for (const varName of this.equalityComparisonVarNames) {
          if (
            !NullCheckAnalyzer.hasNullablePrefix(varName) &&
            !NULLABLE_C_FUNCTIONS.has(varName)
          ) {
            this.analyzer.reportNullComparisonOnNonNullable(
              varName,
              line,
              column,
            );
          }
        }
        // NULL in comparison context - OK (for c_ prefixed variables or functions)
        this.equalityComparisonHasNull = true;
      } else {
        // NULL outside comparison - error
        this.analyzer.reportInvalidNullUsage(line, column);
      }
    }
  };
 
  // ========================================================================
  // Variable Assignment (check for storing stream function result)
  // ========================================================================
 
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    const expr = ctx.expression();
    const varName = ctx.IDENTIFIER().getText();
    const typeName = ctx.type()?.getText() ?? "unknown";
    const identifierToken = ctx.IDENTIFIER().symbol;
    const line = identifierToken.line;
    const column = (identifierToken.column ?? 0) + 1; // 1-indexed column
 
    // E0908: Register c_ prefixed variables for flow tracking
    if (NullCheckAnalyzer.hasNullablePrefix(varName)) {
      this.registerNullableVariable(varName, typeName, line);
    }
 
    if (!expr) return;
 
    const funcName = this.extractFunctionCallName(expr);
 
    // Check if assigning from a nullable C function
    if (funcName && NULLABLE_C_FUNCTIONS.has(funcName)) {
      // Set flag to suppress E0901 for the function call inside this declaration
      this.inVariableDeclarationWithNullable = true;
 
      // Must have c_ prefix
      if (!NullCheckAnalyzer.hasNullablePrefix(varName)) {
        this.analyzer.reportMissingCPrefix(
          varName,
          typeName,
          funcName,
          line,
          column,
        );
      }
      // If has c_ prefix, storage is allowed (don't report E0904 or E0901)
      return;
    }
 
    // Check forbidden functions (malloc, etc.) - always error
    if (funcName && FORBIDDEN_FUNCTIONS.has(funcName)) {
      this.analyzer.reportForbiddenFunction(funcName, line, column);
      return;
    }
 
    // Check for invalid c_ prefix on non-nullable types (E0906)
    if (NullCheckAnalyzer.hasNullablePrefix(varName)) {
      // If NOT assigning from nullable function AND type is NOT nullable, c_ prefix is invalid
      Eif (!funcName || !NULLABLE_C_FUNCTIONS.has(funcName)) {
        if (!NullCheckAnalyzer.isNullableCType(typeName)) {
          this.analyzer.reportInvalidCPrefix(varName, typeName, line, column);
        }
      }
    }
  };
 
  override exitVariableDeclaration = (): void => {
    // Clear the flag when leaving variable declaration
    this.inVariableDeclarationWithNullable = false;
  };
 
  override enterAssignmentStatement = (
    ctx: Parser.AssignmentStatementContext,
  ): void => {
    // Check if RHS contains a stream function call
    const expr = ctx.expression();
    const funcName = this.extractFunctionCallName(expr);
    const target = ctx.assignmentTarget();
    const varName = target.getText();
    const { line, column } = ParserUtils.getPosition(ctx);
 
    if (funcName && NULLABLE_C_FUNCTIONS.has(funcName)) {
      // ADR-046: Allow reassignment to c_ prefixed variables (e.g., in while loops)
      if (NullCheckAnalyzer.hasNullablePrefix(varName)) {
        // Set flag to suppress E0901 for the function call inside this assignment
        this.inVariableDeclarationWithNullable = true;
        // E0908: Reset state to Unchecked on reassignment from nullable function
        this.updateVariableState(varName, NullCheckState.Unchecked);
        return;
      }
 
      this.analyzer.reportInvalidStorage(varName, funcName, line, column);
    }
  };
 
  override exitAssignmentStatement = (): void => {
    // Clear the flag when leaving assignment statement
    this.inVariableDeclarationWithNullable = false;
  };
 
  /**
   * Extract function call name from an expression (if it's a simple call)
   */
  private extractFunctionCallName(
    ctx: Parser.ExpressionContext,
  ): string | null {
    // Simple heuristic: look for identifier followed by parens in text
    // This could be improved with deeper AST analysis
    const text = ctx.getText();
 
    // Check nullable C functions
    for (const funcName of NULLABLE_C_FUNCTIONS.keys()) {
      if (text.includes(`${funcName}(`)) {
        return funcName;
      }
    }
 
    // Check forbidden functions
    for (const funcName of FORBIDDEN_FUNCTIONS) {
      if (text.includes(`${funcName}(`)) {
        return funcName;
      }
    }
 
    return null;
  }
}
 
/**
 * Analyzes C-Next AST for NULL safety violations
 */
class NullCheckAnalyzer {
  private errors: INullCheckError[] = [];
 
  /** Included headers (for context) */
  private includedHeaders: Set<string> = new Set();
 
  /**
   * Analyze a parsed program for NULL safety errors
   * @param tree The parsed program AST
   * @returns Array of NULL check errors
   */
  public analyze(tree: Parser.ProgramContext): INullCheckError[] {
    this.errors = [];
    this.includedHeaders = new Set();
 
    // Collect included headers
    this.collectIncludes(tree);
 
    // Walk tree and check NULL usage
    const listener = new NullCheckListener(this);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
 
    return this.errors;
  }
 
  /**
   * Collect included headers for context
   */
  private collectIncludes(tree: Parser.ProgramContext): void {
    for (const include of tree.includeDirective()) {
      const text = include.getText();
      const match = /#include\s*[<"]([^>"]+)[>"]/.exec(text);
      Eif (match) {
        this.includedHeaders.add(match[1]);
      }
    }
  }
 
  /**
   * Check if stdio.h is included (required for stream functions)
   */
  public hasStdioIncluded(): boolean {
    return this.includedHeaders.has("stdio.h");
  }
 
  /**
   * Report error: stream function used without NULL check
   */
  public reportMissingNullCheck(
    funcName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0901",
      functionName: funcName,
      line,
      column,
      message: `C library function '${funcName}' can return NULL - must check result`,
      helpText: `Use: if (${funcName}(...) != NULL) { ... }`,
    });
  }
 
  /**
   * Report error: forbidden function (dynamic allocation - ADR-003)
   */
  public reportForbiddenFunction(
    funcName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0902",
      functionName: funcName,
      line,
      column,
      message: `Dynamic allocation function '${funcName}' is forbidden`,
      helpText: "Dynamic allocation is forbidden by ADR-003",
    });
  }
 
  /**
   * Report error: NULL used outside comparison context
   */
  public reportInvalidNullUsage(line: number, column: number): void {
    this.errors.push({
      code: "E0903",
      functionName: "NULL",
      line,
      column,
      message: "NULL can only be used in comparison context",
      helpText: "Use: if (func(...) != NULL) or if (func(...) = NULL)",
    });
  }
 
  /**
   * Report error: trying to store stream function result in variable
   */
  public reportInvalidStorage(
    varName: string,
    funcName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0904",
      functionName: funcName,
      line,
      column,
      message: `Cannot store '${funcName}' return value in variable '${varName}'`,
      helpText: `C library pointer returns cannot be stored. Use direct comparison: if (${funcName}(...) != NULL)`,
    });
  }
 
  /**
   * Report error: missing c_ prefix for nullable C type (E0905)
   */
  public reportMissingCPrefix(
    varName: string,
    typeName: string,
    funcName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0905",
      functionName: funcName,
      line,
      column,
      message: `Missing 'c_' prefix for nullable C type '${typeName}'`,
      helpText: `Variable '${varName}' stores nullable pointer from '${funcName}'. Use: ${typeName} c_${varName} <- ${funcName}(...)`,
    });
  }
 
  /**
   * Report error: c_ prefix on non-nullable type (E0906)
   */
  public reportInvalidCPrefix(
    varName: string,
    typeName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0906",
      functionName: varName,
      line,
      column,
      message: `Invalid 'c_' prefix on non-nullable type '${typeName}'`,
      helpText: `The 'c_' prefix is only for nullable C pointer types. Use: ${typeName} ${varName.substring(2)} <- ...`,
    });
  }
 
  /**
   * Report error: NULL comparison on non-nullable variable (E0907)
   */
  public reportNullComparisonOnNonNullable(
    varName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0907",
      functionName: varName,
      line,
      column,
      message: `NULL comparison on non-nullable variable '${varName}'`,
      helpText: `Only variables with 'c_' prefix can be compared to NULL. C-Next variables are never null.`,
    });
  }
 
  /**
   * Report error: c_ variable used without prior NULL check (E0908)
   */
  public reportMissingNullCheckBeforeUse(
    varName: string,
    typeName: string,
    line: number,
    column: number,
  ): void {
    this.errors.push({
      code: "E0908",
      functionName: varName,
      line,
      column,
      message: `Nullable variable '${varName}' used without NULL check`,
      helpText: `Check for NULL before use: if (${varName} != NULL) { ... }`,
    });
  }
 
  // ========================================================================
  // c_ Prefix Validation Helpers (ADR-046)
  // ========================================================================
 
  /**
   * Check if variable name has required c_ prefix for nullable C types
   */
  public static hasNullablePrefix(varName: string): boolean {
    return varName.startsWith("c_");
  }
 
  /**
   * Check if a type is a nullable C pointer type
   * Currently checks for FILE and pointer returns from NULLABLE_C_FUNCTIONS
   */
  public static isNullableCType(typeName: string): boolean {
    // FILE is always nullable
    if (typeName === "FILE") return true;
    // cstring (char*) from C functions is nullable
    if (typeName === "cstring") return true;
    // Pointer types from C headers
    if (typeName.endsWith("*")) return true;
    return false;
  }
 
  /**
   * Get metadata for a nullable C function (for VS Code tooltips)
   */
  public static getNullableFunctionInfo(
    funcName: string,
  ): ICLibraryFunction | null {
    return NULLABLE_C_FUNCTIONS.get(funcName) ?? null;
  }
 
  /**
   * Check if a function is a nullable C function
   */
  public static isNullableFunction(funcName: string): boolean {
    return NULLABLE_C_FUNCTIONS.has(funcName);
  }
 
  /**
   * Check if a function is forbidden (dynamic allocation - ADR-003)
   */
  public static isForbiddenFunction(funcName: string): boolean {
    return FORBIDDEN_FUNCTIONS.has(funcName);
  }
 
  /**
   * Get nullable C functions that return struct pointers (FILE*, etc.)
   * These need asterisk added to the type in code generation.
   * Excludes char*-returning functions (fgets, strstr, etc.) which use cstring type.
   */
  public static getStructPointerFunctions(): Set<string> {
    return new Set(["fopen", "freopen", "tmpfile"]);
  }
}
 
export default NullCheckAnalyzer;