All files / transpiler/output/codegen TypeValidator.ts

99.44% Statements 359/361
98.56% Branches 274/278
100% Functions 40/40
100% Lines 339/339

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189                                            14x                                                     1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x 1003x                               49x 49x   49x 49x 2x       47x       47x 10x                                                 43x 43x 42x 32x   31x   31x 27x               4x                               43x 43x   43x 5x 1x             32x 32x                         27x   26x 26x 26x 2x                                 4x 7x 7x 2x                                       8x 8x     8x   8x 3x 5x 2x 3x 2x     8x 3x                                         35x 42x 42x 40x 1x     39x   3x                                             6x     6x     1x     5x 5x   5x   1x       4x 1x             3x       1x                     11x 9x   8x 5x 5x 5x 4x 3x 2x     4x                         313x 313x 1x       312x     312x 312x 4x     308x               30x 30x 1x       29x 29x 2x     27x                               10x     10x 1x       9x 1x       8x 8x 1x           7x 1x         6x       1x         5x 1x         4x 1x             3x 3x 1x                                         643x 202x     441x     441x 48x 48x       397x     368x       29x                   48x 48x 43x     5x 5x 1x     4x                       397x 397x 266x       131x       60x       71x                             3x 2x   1x                       21x 22x               22x 7x           15x 1x       14x 2x       12x                 2x 2x 1x       1x 1x                 12x 2x   10x 2x   8x 1x                 4x 2x       2x 2x                             25x 25x 25x     25x 25x 1x           24x 1x           23x 23x 45x 46x 46x 2x       44x         21x 10x                         10x 10x   10x     10x 10x 20x     10x   3x   3x   2x 2x 1x               7x   1x 1x                   5x 5x 3x   2x             55x 12x 12x   24x     43x 11x   32x 26x   26x 26x 26x   6x   3x   3x 3x 3x   3x   1x 1x   2x 1x   1x                         15x     15x 1x     14x 14x 1x         13x 1x     12x 12x 1x         11x 2x     9x 9x 1x         8x 5x       3x                       12x   12x 1x                                 21x 21x     21x 1x         20x 20x     20x 1x     19x 19x 1x           18x 1x     17x 17x 1x           16x 1x     15x 15x 1x           14x 8x       6x 6x 3x       3x                   6x     6x 1x       5x 1x       4x 4x 1x     3x                                 64x 4x 4x                             9x 3x 3x                                                 33x 33x     32x 32x     25x 3x                 22x 8x                         33x     19x     2x     9x     2x   1x                       32x 32x   31x 31x 31x   30x 30x                   39x 39x   39x 39x 28x       11x 11x 9x 9x     2x                   28x 28x   28x 28x   26x 26x 26x                                                 151x 73x       78x 1x     77x     77x 77x 77x   77x   48x     29x            
/**
 * TypeValidator - Handles compile-time validation of types, assignments, and control flow
 * Extracted from CodeGenerator for better separation of concerns
 * Issue #63: Validation logic separated for independent testing
 */
import { existsSync } from "node:fs";
import { dirname, resolve, join } from "node:path";
import * as Parser from "../../logic/parser/grammar/CNextParser";
import ICodeGenSymbols from "../../types/ICodeGenSymbols";
import SymbolTable from "../../logic/symbols/SymbolTable";
import TTypeInfo from "./types/TTypeInfo";
import TParameterInfo from "./types/TParameterInfo";
import ICallbackTypeInfo from "./types/ICallbackTypeInfo";
import ITypeValidatorDeps from "./types/ITypeValidatorDeps";
import TypeResolver from "./TypeResolver";
import ExpressionUtils from "../../../utils/ExpressionUtils";
// SonarCloud S3776: Extracted literal parsing to reduce complexity
import LiteralEvaluator from "./helpers/LiteralEvaluator";
 
/**
 * ADR-010: Implementation file extensions that should NOT be #included
 */
const IMPLEMENTATION_EXTENSIONS = new Set([
  ".c",
  ".cpp",
  ".cc",
  ".cxx",
  ".c++",
]);
 
/**
 * TypeValidator class - validates types, assignments, and control flow at compile time
 */
class TypeValidator {
  private readonly symbols: ICodeGenSymbols | null;
  private readonly symbolTable: SymbolTable | null;
  private readonly typeRegistry: Map<string, TTypeInfo>;
  private readonly typeResolver: TypeResolver;
  private readonly callbackTypes: Map<string, ICallbackTypeInfo>;
  private readonly knownFunctions: Set<string>;
  private readonly knownGlobals: Set<string>;
  private readonly getCurrentScopeFn: () => string | null;
  private readonly getScopeMembersFn: () => Map<string, Set<string>>;
  private readonly getCurrentParametersFn: () => Map<string, TParameterInfo>;
  private readonly getLocalVariablesFn: () => Set<string>;
  private readonly resolveIdentifierFn: (name: string) => string;
  private readonly getExpressionTypeFn: (ctx: unknown) => string | null;
 
  constructor(deps: ITypeValidatorDeps) {
    this.symbols = deps.symbols;
    this.symbolTable = deps.symbolTable;
    this.typeRegistry = deps.typeRegistry;
    this.typeResolver = deps.typeResolver;
    this.callbackTypes = deps.callbackTypes;
    this.knownFunctions = deps.knownFunctions;
    this.knownGlobals = deps.knownGlobals;
    this.getCurrentScopeFn = deps.getCurrentScope;
    this.getScopeMembersFn = deps.getScopeMembers;
    this.getCurrentParametersFn = deps.getCurrentParameters;
    this.getLocalVariablesFn = deps.getLocalVariables;
    this.resolveIdentifierFn = deps.resolveIdentifier;
    this.getExpressionTypeFn = deps.getExpressionType;
  }
 
  // ========================================================================
  // Include Validation (ADR-010)
  // ========================================================================
 
  /**
   * ADR-010: Validate that #include doesn't include implementation files
   */
  validateIncludeNotImplementationFile(
    includeText: string,
    lineNumber: number,
  ): void {
    // Extract the file path from #include directive
    // Match both <file> and "file" forms
    const angleMatch = /#\s*include\s*<([^>]+)>/.exec(includeText);
    const quoteMatch = /#\s*include\s*"([^"]+)"/.exec(includeText);
 
    const includePath = angleMatch?.[1] || quoteMatch?.[1];
    if (!includePath) {
      return; // Malformed include, let other validation handle it
    }
 
    // Get the file extension (lowercase for case-insensitive comparison)
    const ext = includePath
      .substring(includePath.lastIndexOf("."))
      .toLowerCase();
 
    if (IMPLEMENTATION_EXTENSIONS.has(ext)) {
      throw new Error(
        `E0503: Cannot #include implementation file '${includePath}'. ` +
          `Only header files (.h, .hpp) are allowed. Line ${lineNumber}`,
      );
    }
  }
 
  /**
   * E0504: Validate that a .cnx alternative doesn't exist for a .h/.hpp include
   * This helps during codebase migration by alerting developers when they should
   * be using the C-Next version of a file instead of the C header.
   *
   * @param includeText - The full #include directive text
   * @param lineNumber - Line number for error reporting
   * @param sourcePath - Path to the source file (for resolving relative includes)
   * @param includePaths - Array of directories to search for includes
   * @param fileExists - Function to check if a file exists (injectable for testing)
   */
  validateIncludeNoCnxAlternative(
    includeText: string,
    lineNumber: number,
    sourcePath: string | null,
    includePaths: string[],
    fileExists: (path: string) => boolean = existsSync,
  ): void {
    const parsed = this._parseIncludeDirective(includeText);
    if (!parsed) return;
    if (parsed.path.endsWith(".cnx")) return;
    if (!this._isHeaderFile(parsed.path)) return;
 
    const cnxPath = parsed.path.replace(/\.(h|hpp)$/i, ".cnx");
 
    if (parsed.isQuoted) {
      this._checkQuotedIncludeForCnx(
        parsed.path,
        cnxPath,
        sourcePath,
        lineNumber,
        fileExists,
      );
    } else {
      this._checkAngleIncludeForCnx(
        parsed.path,
        cnxPath,
        includePaths,
        lineNumber,
        fileExists,
      );
    }
  }
 
  /**
   * Parse an include directive to extract path and type
   */
  private _parseIncludeDirective(
    includeText: string,
  ): { path: string; isQuoted: boolean } | null {
    const angleMatch = /#\s*include\s*<([^>]+)>/.exec(includeText);
    const quoteMatch = /#\s*include\s*"([^"]+)"/.exec(includeText);
 
    if (quoteMatch) return { path: quoteMatch[1], isQuoted: true };
    if (angleMatch) return { path: angleMatch[1], isQuoted: false };
    return null;
  }
 
  /**
   * Check if a path is a header file (.h or .hpp)
   */
  private _isHeaderFile(path: string): boolean {
    const ext = path.substring(path.lastIndexOf(".")).toLowerCase();
    return ext === ".h" || ext === ".hpp";
  }
 
  /**
   * Check quoted include for .cnx alternative
   */
  private _checkQuotedIncludeForCnx(
    includePath: string,
    cnxPath: string,
    sourcePath: string | null,
    lineNumber: number,
    fileExists: (path: string) => boolean,
  ): void {
    if (!sourcePath) return;
 
    const sourceDir = dirname(sourcePath);
    const fullCnxPath = resolve(sourceDir, cnxPath);
    if (fileExists(fullCnxPath)) {
      throw new Error(
        `E0504: Found #include "${includePath}" but '${cnxPath}' exists at the same location.\n` +
          `       Use #include "${cnxPath}" instead to use the C-Next version. Line ${lineNumber}`,
      );
    }
  }
 
  /**
   * Check angle bracket include for .cnx alternative in search paths
   */
  private _checkAngleIncludeForCnx(
    includePath: string,
    cnxPath: string,
    includePaths: string[],
    lineNumber: number,
    fileExists: (path: string) => boolean,
  ): void {
    for (const searchDir of includePaths) {
      const fullCnxPath = join(searchDir, cnxPath);
      if (fileExists(fullCnxPath)) {
        throw new Error(
          `E0504: Found #include <${includePath}> but '${cnxPath}' exists at the same location.\n` +
            `       Use #include <${cnxPath}> instead to use the C-Next version. Line ${lineNumber}`,
        );
      }
    }
  }
 
  // ========================================================================
  // Bitmap Field Validation (ADR-034)
  // ========================================================================
 
  /**
   * ADR-034: Validate that a literal value fits in a bitmap field
   */
  validateBitmapFieldLiteral(
    expr: Parser.ExpressionContext,
    width: number,
    fieldName: string,
  ): void {
    const text = expr.getText().trim();
    const maxValue = (1 << width) - 1;
 
    // Check for integer literals
    let value: number | null = null;
 
    if (/^\d+$/.exec(text)) {
      value = Number.parseInt(text, 10);
    } else if (/^0[xX][0-9a-fA-F]+$/.exec(text)) {
      value = Number.parseInt(text, 16);
    } else if (/^0[bB][01]+$/.exec(text)) {
      value = Number.parseInt(text.substring(2), 2);
    }
 
    if (value !== null && value > maxValue) {
      throw new Error(
        `Error: Value ${value} exceeds ${width}-bit field '${fieldName}' maximum of ${maxValue}`,
      );
    }
  }
 
  // ========================================================================
  // Array Bounds Validation (ADR-036)
  // ========================================================================
 
  /**
   * ADR-036: Check array bounds at compile time for constant indices.
   * Throws an error if the constant index is out of bounds.
   */
  checkArrayBounds(
    arrayName: string,
    dimensions: number[],
    indexExprs: Parser.ExpressionContext[],
    line: number,
    tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined,
  ): void {
    for (let i = 0; i < indexExprs.length && i < dimensions.length; i++) {
      const constValue = tryEvaluateConstant(indexExprs[i]);
      if (constValue !== undefined) {
        if (constValue < 0) {
          throw new Error(
            `Array index out of bounds: ${constValue} is negative for '${arrayName}' dimension ${i + 1} (line ${line})`,
          );
        } else if (dimensions[i] > 0 && constValue >= dimensions[i]) {
          // Issue #547: Skip upper bound check for unsized dimensions (size 0)
          throw new Error(
            `Array index out of bounds: ${constValue} >= ${dimensions[i]} for '${arrayName}' dimension ${i + 1} (line ${line})`,
          );
        }
      }
    }
  }
 
  // ========================================================================
  // Callback Assignment Validation (ADR-029)
  // ========================================================================
 
  /**
   * ADR-029: Validate callback assignment with nominal typing
   * - If value IS a callback type used as a field type: must match exactly (nominal typing)
   * - If value is just a function (not used as a type): signature must match
   */
  validateCallbackAssignment(
    expectedType: string,
    valueExpr: Parser.ExpressionContext,
    fieldName: string,
    isCallbackTypeUsedAsFieldType: (funcName: string) => boolean,
  ): void {
    const valueText = valueExpr.getText();
 
    // Check if the value is a known function
    if (!this.knownFunctions.has(valueText)) {
      // Not a function name - could be a variable holding a callback
      // Skip validation for now (C compiler will catch type mismatches)
      return;
    }
 
    const expectedInfo = this.callbackTypes.get(expectedType);
    const valueInfo = this.callbackTypes.get(valueText);
 
    if (!expectedInfo || !valueInfo) {
      // Shouldn't happen, but guard against it
      return;
    }
 
    // First check if signatures match
    if (!this.callbackSignaturesMatch(expectedInfo, valueInfo)) {
      throw new Error(
        `Error: Function '${valueText}' signature does not match callback type '${expectedType}'`,
      );
    }
 
    // Nominal typing: if the value function is used as a field type somewhere,
    // it can only be assigned to fields of that same type
    if (
      isCallbackTypeUsedAsFieldType(valueText) &&
      valueText !== expectedType
    ) {
      throw new Error(
        `Error: Cannot assign '${valueText}' to callback field '${fieldName}' ` +
          `(expected ${expectedType} type, got ${valueText} type - nominal typing)`,
      );
    }
  }
 
  /**
   * ADR-029: Check if two callback signatures match
   */
  callbackSignaturesMatch(a: ICallbackTypeInfo, b: ICallbackTypeInfo): boolean {
    if (a.returnType !== b.returnType) return false;
    if (a.parameters.length !== b.parameters.length) return false;
 
    for (let i = 0; i < a.parameters.length; i++) {
      const pa = a.parameters[i];
      const pb = b.parameters[i];
      if (pa.type !== pb.type) return false;
      if (pa.isConst !== pb.isConst) return false;
      if (pa.isPointer !== pb.isPointer) return false;
      if (pa.isArray !== pb.isArray) return false;
    }
 
    return true;
  }
 
  // ========================================================================
  // Const Assignment Validation (ADR-013)
  // ========================================================================
 
  /**
   * ADR-013: Check if assigning to an identifier would violate const rules.
   * Returns error message if const, null if mutable.
   */
  checkConstAssignment(identifier: string): string | null {
    // Check if it's a const parameter
    const paramInfo = this.getCurrentParametersFn().get(identifier);
    if (paramInfo?.isConst) {
      return `cannot assign to const parameter '${identifier}'`;
    }
 
    // Resolve identifier to scoped name for proper lookup
    const scopedName = this.resolveIdentifierFn(identifier);
 
    // Check if it's a const variable
    const typeInfo = this.typeRegistry.get(scopedName);
    if (typeInfo?.isConst) {
      return `cannot assign to const variable '${identifier}'`;
    }
 
    return null; // Mutable, assignment OK
  }
 
  /**
   * ADR-013: Check if an argument is const (variable or parameter)
   */
  isConstValue(identifier: string): boolean {
    // Check if it's a const parameter
    const paramInfo = this.getCurrentParametersFn().get(identifier);
    if (paramInfo?.isConst) {
      return true;
    }
 
    // Check if it's a const variable
    const typeInfo = this.typeRegistry.get(identifier);
    if (typeInfo?.isConst) {
      return true;
    }
 
    return false;
  }
 
  // ========================================================================
  // Scope Identifier Validation (ADR-016)
  // ========================================================================
 
  /**
   * ADR-016: Validate that bare identifiers inside scopes are only used for local variables.
   * Throws an error if a bare identifier references a scope member or global.
   */
  validateBareIdentifierInScope(
    identifier: string,
    isLocalVariable: boolean,
    isKnownStruct: (name: string) => boolean,
  ): void {
    const currentScope = this.getCurrentScopeFn();
 
    // Only enforce inside scopes
    if (!currentScope) {
      return;
    }
 
    // Local variables and parameters are allowed as bare identifiers
    if (isLocalVariable) {
      return;
    }
 
    // Check if this identifier is a scope member
    const scopeMembers = this.getScopeMembersFn().get(currentScope);
    if (scopeMembers?.has(identifier)) {
      throw new Error(
        `Error: Use 'this.${identifier}' to access scope member '${identifier}' inside scope '${currentScope}'`,
      );
    }
 
    // Check if this is a known global (register, function, enum, struct)
    if (this.symbols!.knownRegisters.has(identifier)) {
      throw new Error(
        `Error: Use 'global.${identifier}' to access register '${identifier}' inside scope '${currentScope}'`,
      );
    }
 
    if (
      this.knownFunctions.has(identifier) &&
      !identifier.startsWith(currentScope + "_")
    ) {
      throw new Error(
        `Error: Use 'global.${identifier}' to access global function '${identifier}' inside scope '${currentScope}'`,
      );
    }
 
    if (this.symbols!.knownEnums.has(identifier)) {
      throw new Error(
        `Error: Use 'global.${identifier}' to access global enum '${identifier}' inside scope '${currentScope}'`,
      );
    }
 
    if (isKnownStruct(identifier)) {
      throw new Error(
        `Error: Use 'global.${identifier}' to access global struct '${identifier}' inside scope '${currentScope}'`,
      );
    }
 
    // Check if this identifier exists as a global variable in the type registry
    // (but not a scoped variable - those would have Scope_ prefix)
    const typeInfo = this.typeRegistry.get(identifier);
    if (typeInfo && !identifier.includes("_")) {
      throw new Error(
        `Error: Use 'global.${identifier}' to access global variable '${identifier}' inside scope '${currentScope}'`,
      );
    }
  }
 
  /**
   * Resolve a bare identifier to its qualified name using priority:
   * 1. Local variables/parameters (return null - no transformation needed)
   * 2. Scope members (return Scope_identifier)
   * 3. Global variables/functions (return identifier)
   *
   * Returns null if no transformation needed, the resolved name otherwise.
   * Used by implicit scope resolution feature.
   */
  resolveBareIdentifier(
    identifier: string,
    isLocalVariable: boolean,
    isKnownStruct: (name: string) => boolean,
  ): string | null {
    // Priority 1: Local variables and parameters - no transformation
    if (isLocalVariable) {
      return null;
    }
 
    const currentScope = this.getCurrentScopeFn();
 
    // Priority 2: If inside a scope, check scope members
    if (currentScope) {
      const scopeResolved = this._resolveScopeMember(identifier, currentScope);
      if (scopeResolved) return scopeResolved;
    }
 
    // Priority 3: Global resolution
    if (
      this._isKnownGlobalIdentifier(identifier, currentScope, isKnownStruct)
    ) {
      return currentScope ? identifier : null;
    }
 
    // Not found anywhere - let it pass through (may be enum member or error later)
    return null;
  }
 
  /**
   * Try to resolve identifier as a scope member or scope function
   */
  private _resolveScopeMember(
    identifier: string,
    currentScope: string,
  ): string | null {
    const scopeMembers = this.getScopeMembersFn().get(currentScope);
    if (scopeMembers?.has(identifier)) {
      return `${currentScope}_${identifier}`;
    }
 
    const scopedFuncName = `${currentScope}_${identifier}`;
    if (this.knownFunctions.has(scopedFuncName)) {
      return scopedFuncName;
    }
 
    return null;
  }
 
  /**
   * Check if identifier is a known global (variable, function, enum, struct, register)
   */
  private _isKnownGlobalIdentifier(
    identifier: string,
    currentScope: string | null,
    isKnownStruct: (name: string) => boolean,
  ): boolean {
    // Global variable in type registry
    const typeInfo = this.typeRegistry.get(identifier);
    if (typeInfo && !identifier.includes("_")) {
      return true;
    }
 
    // Global function (not prefixed with current scope)
    if (
      this.knownFunctions.has(identifier) &&
      !identifier.startsWith(currentScope + "_")
    ) {
      return true;
    }
 
    // Known types: enums, structs, registers
    return (
      this.symbols!.knownEnums.has(identifier) ||
      isKnownStruct(identifier) ||
      this.symbols!.knownRegisters.has(identifier)
    );
  }
 
  /**
   * Resolve an identifier that appears before a '.' (member access).
   * Prioritizes scope names for Scope.member() calls.
   *
   * Returns the resolved name or null if not a scope.
   */
  resolveForMemberAccess(identifier: string): string | null {
    // For member access, check if it's a scope name first
    if (this.symbols!.knownScopes.has(identifier)) {
      return identifier;
    }
    return null;
  }
 
  // ========================================================================
  // Critical Section Validation (ADR-050)
  // ========================================================================
 
  /**
   * ADR-050: Validate no early exits inside critical block
   * return, break, continue would leave interrupts disabled
   */
  validateNoEarlyExits(ctx: Parser.BlockContext): void {
    for (const stmt of ctx.statement()) {
      this._validateStatementForEarlyExit(stmt);
    }
  }
 
  /**
   * Validate a single statement for early exits in critical sections
   */
  private _validateStatementForEarlyExit(stmt: Parser.StatementContext): void {
    if (stmt.returnStatement()) {
      throw new Error(
        `E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
      );
    }
 
    // Recursively check nested blocks
    if (stmt.block()) {
      this.validateNoEarlyExits(stmt.block()!);
    }
 
    // Check inside if statements
    if (stmt.ifStatement()) {
      this._validateIfStatementForEarlyExit(stmt.ifStatement()!);
    }
 
    // Check inside loops
    this._validateLoopForEarlyExit(stmt);
  }
 
  /**
   * Validate if statement branches for early exits
   */
  private _validateIfStatementForEarlyExit(
    ifStmt: Parser.IfStatementContext,
  ): void {
    for (const innerStmt of ifStmt.statement()) {
      if (innerStmt.returnStatement()) {
        throw new Error(
          `E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
        );
      }
      Eif (innerStmt.block()) {
        this.validateNoEarlyExits(innerStmt.block()!);
      }
    }
  }
 
  /**
   * Validate loop statements for early exits
   */
  private _validateLoopForEarlyExit(stmt: Parser.StatementContext): void {
    if (stmt.whileStatement()) {
      this._checkLoopBodyForReturn(stmt.whileStatement()!.statement());
    }
    if (stmt.forStatement()) {
      this._checkLoopBodyForReturn(stmt.forStatement()!.statement());
    }
    if (stmt.doWhileStatement()) {
      this.validateNoEarlyExits(stmt.doWhileStatement()!.block());
    }
  }
 
  /**
   * Issue #707: Check a loop body statement for early return.
   * Shared between while and for loop validation in critical sections.
   */
  private _checkLoopBodyForReturn(loopStmt: Parser.StatementContext): void {
    if (loopStmt.returnStatement()) {
      throw new Error(
        `E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
      );
    }
    Eif (loopStmt.block()) {
      this.validateNoEarlyExits(loopStmt.block()!);
    }
  }
 
  // ========================================================================
  // Switch Statement Validation (ADR-025)
  // ========================================================================
 
  /**
   * ADR-025: Validate switch statement for MISRA compliance
   */
  validateSwitchStatement(
    ctx: Parser.SwitchStatementContext,
    switchExpr: Parser.ExpressionContext,
  ): void {
    const cases = ctx.switchCase();
    const defaultCase = ctx.defaultCase();
    const totalClauses = cases.length + (defaultCase ? 1 : 0);
 
    // MISRA 16.7: No boolean switches (use if/else instead)
    const exprType = this.getExpressionTypeFn(switchExpr);
    if (exprType === "bool") {
      throw new Error(
        "Error: Cannot switch on boolean type (MISRA 16.7). Use if/else instead.",
      );
    }
 
    // MISRA 16.6: Minimum 2 clauses required
    if (totalClauses < 2) {
      throw new Error(
        "Error: Switch requires at least 2 clauses (MISRA 16.6). Use if statement for single case.",
      );
    }
 
    // Check for duplicate case values
    const seenValues = new Set<string>();
    for (const caseCtx of cases) {
      for (const labelCtx of caseCtx.caseLabel()) {
        const labelValue = this.getCaseLabelValue(labelCtx);
        if (seenValues.has(labelValue)) {
          throw new Error(
            `Error: Duplicate case value '${labelValue}' in switch statement.`,
          );
        }
        seenValues.add(labelValue);
      }
    }
 
    // ADR-025: Enum exhaustiveness checking
    if (exprType && this.symbols!.knownEnums.has(exprType)) {
      this.validateEnumExhaustiveness(ctx, exprType, cases, defaultCase);
    }
  }
 
  /**
   * ADR-025: Validate enum switch exhaustiveness with default(n) counting
   */
  validateEnumExhaustiveness(
    ctx: Parser.SwitchStatementContext,
    enumTypeName: string,
    cases: Parser.SwitchCaseContext[],
    defaultCase: Parser.DefaultCaseContext | null,
  ): void {
    const enumVariants = this.symbols!.enumMembers.get(enumTypeName);
    Iif (!enumVariants) return; // Shouldn't happen if knownEnums has it
 
    const totalVariants = enumVariants.size;
 
    // Count explicit cases (each || alternative counts as 1)
    let explicitCaseCount = 0;
    for (const caseCtx of cases) {
      explicitCaseCount += caseCtx.caseLabel().length;
    }
 
    if (defaultCase) {
      // Check for default(n) syntax
      const defaultCount = this.getDefaultCount(defaultCase);
 
      if (defaultCount !== null) {
        // default(n) mode: explicit + n must equal total variants
        const covered = explicitCaseCount + defaultCount;
        if (covered !== totalVariants) {
          throw new Error(
            `Error: switch covers ${covered} of ${totalVariants} ${enumTypeName} variants ` +
              `(${explicitCaseCount} explicit + default(${defaultCount})). ` +
              `Expected ${totalVariants}.`,
          );
        }
      }
      // Plain default: no exhaustiveness check needed
    } else if (explicitCaseCount !== totalVariants) {
      // No default: must cover all variants explicitly
      const missing = totalVariants - explicitCaseCount;
      throw new Error(
        `Error: Non-exhaustive switch on ${enumTypeName}: covers ${explicitCaseCount} of ${totalVariants} variants, missing ${missing}.`,
      );
    }
  }
 
  /**
   * Get the count from default(n) syntax, or null for plain default
   */
  getDefaultCount(ctx: Parser.DefaultCaseContext): number | null {
    const intLiteral = ctx.INTEGER_LITERAL();
    if (intLiteral) {
      return Number.parseInt(intLiteral.getText(), 10);
    }
    return null;
  }
 
  /**
   * Get the string representation of a case label for duplicate checking
   */
  getCaseLabelValue(ctx: Parser.CaseLabelContext): string {
    if (ctx.qualifiedType()) {
      const qt = ctx.qualifiedType()!;
      return qt
        .IDENTIFIER()
        .map((id) => id.getText())
        .join(".");
    }
    if (ctx.IDENTIFIER()) {
      return ctx.IDENTIFIER()!.getText();
    }
    if (ctx.INTEGER_LITERAL()) {
      const num = ctx.INTEGER_LITERAL()!.getText();
      // Check if minus token exists (first child would be '-')
      const hasNeg = ctx.children && ctx.children[0]?.getText() === "-";
      const value = BigInt(num);
      return String(hasNeg ? -value : value);
    }
    if (ctx.HEX_LITERAL()) {
      // Normalize hex to decimal for comparison
      const hex = ctx.HEX_LITERAL()!.getText();
      // Check if minus token exists (first child would be '-')
      const hasNeg = ctx.children && ctx.children[0]?.getText() === "-";
      const value = BigInt(hex); // BigInt handles 0x prefix natively
      return String(hasNeg ? -value : value);
    }
    if (ctx.BINARY_LITERAL()) {
      // Normalize binary to decimal for comparison
      const bin = ctx.BINARY_LITERAL()!.getText();
      return String(BigInt(bin)); // BigInt handles 0b prefix natively
    }
    if (ctx.CHAR_LITERAL()) {
      return ctx.CHAR_LITERAL()!.getText();
    }
    return "";
  }
 
  // ========================================================================
  // Ternary Validation (ADR-022)
  // ========================================================================
 
  /**
   * ADR-022: Validate that ternary condition is a boolean expression
   * Must be a comparison or logical operation, not just a value
   */
  validateTernaryCondition(ctx: Parser.OrExpressionContext): void {
    // Check if the condition contains a comparison or logical operator
    const text = ctx.getText();
 
    // If it has && or ||, it's a logical expression (valid)
    if (ctx.andExpression().length > 1) {
      return; // Has || operator - valid
    }
 
    const andExpr = ctx.andExpression(0);
    if (!andExpr) {
      throw new Error(
        `Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
      );
    }
 
    if (andExpr.equalityExpression().length > 1) {
      return; // Has && operator - valid
    }
 
    const equalityExpr = andExpr.equalityExpression(0);
    if (!equalityExpr) {
      throw new Error(
        `Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
      );
    }
 
    if (equalityExpr.relationalExpression().length > 1) {
      return; // Has = or != operator - valid
    }
 
    const relationalExpr = equalityExpr.relationalExpression(0);
    if (!relationalExpr) {
      throw new Error(
        `Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
      );
    }
 
    if (relationalExpr.bitwiseOrExpression().length > 1) {
      return; // Has <, >, <=, >= operator - valid
    }
 
    // No comparison or logical operators found - just a value
    throw new Error(
      `Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
    );
  }
 
  /**
   * ADR-022: Validate that expression does not contain a nested ternary
   */
  validateNoNestedTernary(
    ctx: Parser.OrExpressionContext,
    branchName: string,
  ): void {
    const text = ctx.getText();
    // Check for ternary pattern: something ? something : something
    if (text.includes("?") && text.includes(":")) {
      throw new Error(
        `Error: Nested ternary not allowed in ${branchName}. Use if/else instead.`,
      );
    }
  }
 
  // ========================================================================
  // Do-While Validation (ADR-027)
  // ========================================================================
 
  /**
   * ADR-027: Validate that do-while condition is a boolean expression (E0701)
   * Must be a comparison, logical operation, or boolean variable - not just a value.
   * This enforces MISRA C:2012 Rule 14.4.
   */
  validateDoWhileCondition(ctx: Parser.ExpressionContext): void {
    // Unwrap: ExpressionContext -> TernaryExpressionContext -> OrExpressionContext
    const ternaryExpr = ctx.ternaryExpression();
    const orExprs = ternaryExpr.orExpression();
 
    // For do-while, we expect a non-ternary expression (single orExpression)
    if (orExprs.length !== 1) {
      throw new Error(
        `Error E0701: do-while condition must be a boolean expression, not a ternary (MISRA C:2012 Rule 14.4)`,
      );
    }
 
    const orExpr = orExprs[0];
    const text = orExpr.getText();
 
    // If it has || operator, it's valid (logical expression)
    if (orExpr.andExpression().length > 1) {
      return;
    }
 
    const andExpr = orExpr.andExpression(0);
    if (!andExpr) {
      throw new Error(
        `Error E0701: do-while condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
      );
    }
 
    // If it has && operator, it's valid
    if (andExpr.equalityExpression().length > 1) {
      return;
    }
 
    const equalityExpr = andExpr.equalityExpression(0);
    if (!equalityExpr) {
      throw new Error(
        `Error E0701: do-while condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
      );
    }
 
    // If it has = or != operator, it's valid
    if (equalityExpr.relationalExpression().length > 1) {
      return;
    }
 
    const relationalExpr = equalityExpr.relationalExpression(0);
    if (!relationalExpr) {
      throw new Error(
        `Error E0701: do-while condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
      );
    }
 
    // If it has <, >, <=, >= operator, it's valid
    if (relationalExpr.bitwiseOrExpression().length > 1) {
      return;
    }
 
    // Check if it's a unary ! (negation) expression - that's valid on booleans
    const bitwiseOrExpr = relationalExpr.bitwiseOrExpression(0);
    if (bitwiseOrExpr && this.isBooleanExpression(bitwiseOrExpr)) {
      return;
    }
 
    // No comparison or logical operators found - just a value
    throw new Error(
      `Error E0701: do-while condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)\n  help: use explicit comparison: ${text} > 0 or ${text} != 0`,
    );
  }
 
  /**
   * Check if an expression resolves to a boolean type.
   * This includes: boolean literals, boolean variables, negation of booleans, function calls returning bool.
   */
  private isBooleanExpression(ctx: Parser.BitwiseOrExpressionContext): boolean {
    const text = ctx.getText();
 
    // Check for boolean literals
    if (text === "true" || text === "false") {
      return true;
    }
 
    // Check for negation (! operator) - valid for boolean expressions
    if (text.startsWith("!")) {
      return true;
    }
 
    // Check if it's a known boolean variable
    const typeInfo = this.typeRegistry.get(text);
    if (typeInfo?.baseType === "bool") {
      return true;
    }
 
    return false;
  }
 
  // ========================================================================
  // Function Call in Condition Validation (Issue #254)
  // ========================================================================
 
  /**
   * Issue #254: Validate that condition does not contain function calls (E0702)
   * MISRA C:2012 Rule 13.5 forbids function calls in conditions because:
   * - Short-circuit evaluation may skip the function call
   * - Side effects become unpredictable
   */
  validateConditionNoFunctionCall(
    ctx: Parser.ExpressionContext,
    conditionType: string,
  ): void {
    if (ExpressionUtils.hasFunctionCall(ctx)) {
      const text = ctx.getText();
      throw new Error(
        `Error E0702: Function call in '${conditionType}' condition is not allowed (MISRA C:2012 Rule 13.5)\n` +
          `  expression: ${text}\n` +
          `  help: store the function result in a variable first`,
      );
    }
  }
 
  /**
   * Issue #254: Validate that ternary condition does not contain function calls (E0702)
   * Used for ternary expressions where condition is OrExpressionContext
   */
  validateTernaryConditionNoFunctionCall(
    ctx: Parser.OrExpressionContext,
  ): void {
    if (ExpressionUtils.hasFunctionCallInOr(ctx)) {
      const text = ctx.getText();
      throw new Error(
        `Error E0702: Function call in 'ternary' condition is not allowed (MISRA C:2012 Rule 13.5)\n` +
          `  expression: ${text}\n` +
          `  help: store the function result in a variable first`,
      );
    }
  }
 
  // Function call detection delegated to ExpressionUtils (Issue #254, #366)
 
  // ========================================================================
  // Shift Amount Validation (MISRA C:2012 Rule 12.2)
  // ========================================================================
 
  /**
   * Validate shift amount doesn't exceed type width (MISRA C:2012 Rule 12.2).
   * Shifting by an amount >= type width is undefined behavior.
   */
  validateShiftAmount(
    leftType: string,
    rightExpr: Parser.AdditiveExpressionContext,
    op: string,
    ctx: Parser.ShiftExpressionContext,
  ): void {
    // Get type width in bits
    const typeWidth = this.getTypeWidth(leftType);
    if (!typeWidth) return; // Unknown type, skip validation
 
    // Try to evaluate shift amount if it's a constant
    const shiftAmount = this.evaluateShiftAmount(rightExpr);
    if (shiftAmount === null) return; // Not a constant, skip validation
 
    // Check for negative shift (undefined behavior)
    if (shiftAmount < 0) {
      throw new Error(
        `Error: Negative shift amount (${shiftAmount}) is undefined behavior\n` +
          `  Type: ${leftType}\n` +
          `  Expression: ${ctx.getText()}\n` +
          `  Shift amounts must be non-negative`,
      );
    }
 
    // Check if shift amount >= type width (undefined behavior)
    if (shiftAmount >= typeWidth) {
      throw new Error(
        `Error: Shift amount (${shiftAmount}) exceeds type width (${typeWidth} bits) for type '${leftType}'\n` +
          `  Expression: ${ctx.getText()}\n` +
          `  Shift amount must be < ${typeWidth} for ${typeWidth}-bit types\n` +
          `  This violates MISRA C:2012 Rule 12.2 and causes undefined behavior`,
      );
    }
  }
 
  /**
   * Get the bit width of a primitive type.
   */
  private getTypeWidth(type: string): number | null {
    switch (type) {
      case "u8":
      case "i8":
        return 8;
      case "u16":
      case "i16":
        return 16;
      case "u32":
      case "i32":
        return 32;
      case "u64":
      case "i64":
        return 64;
      default:
        return null; // Unknown type
    }
  }
 
  /**
   * Try to evaluate a shift amount expression to get its numeric value.
   * Returns null if not a constant or cannot be evaluated.
   */
  private evaluateShiftAmount(
    ctx: Parser.AdditiveExpressionContext,
  ): number | null {
    // For now, handle simple literals only
    const multExprs = ctx.multiplicativeExpression();
    if (multExprs.length !== 1) return null; // Not a simple literal
 
    const multExpr = multExprs[0];
    const unaryExprs = multExpr.unaryExpression();
    if (unaryExprs.length !== 1) return null;
 
    const unaryExpr = unaryExprs[0];
    return this.evaluateUnaryExpression(unaryExpr);
  }
 
  /**
   * Helper to evaluate a unary expression recursively.
   * SonarCloud S3776: Uses LiteralEvaluator for literal parsing.
   */
  private evaluateUnaryExpression(
    ctx: Parser.UnaryExpressionContext,
  ): number | null {
    const unaryText = ctx.getText();
    const isNegative = unaryText.startsWith("-");
 
    const postfixExpr = ctx.postfixExpression();
    if (postfixExpr) {
      return this.evaluateLiteralFromPostfix(postfixExpr, isNegative);
    }
 
    // Recursive unary
    const nestedUnary = ctx.unaryExpression();
    if (nestedUnary) {
      const nestedValue = this.evaluateUnaryExpression(nestedUnary);
      return LiteralEvaluator.applySign(nestedValue, isNegative);
    }
 
    return null;
  }
 
  /**
   * Extract and evaluate a literal from a postfix expression.
   */
  private evaluateLiteralFromPostfix(
    postfixExpr: Parser.PostfixExpressionContext,
    isNegative: boolean,
  ): number | null {
    const primaryExpr = postfixExpr.primaryExpression();
    Iif (!primaryExpr) return null;
 
    const literal = primaryExpr.literal();
    if (!literal) return null;
 
    const text = literal.getText();
    const value = LiteralEvaluator.parseLiteral(text);
    return LiteralEvaluator.applySign(value, isNegative);
  }
 
  // ========================================================================
  // Integer Assignment Validation (ADR-024)
  // ========================================================================
 
  /**
   * ADR-024: Validate integer type conversions for assignments.
   * - For literals: validates the value fits in the target type
   * - For expressions: validates no narrowing or sign-changing conversions
   *
   * @param targetType - The target type (e.g., "u8", "i32")
   * @param expressionText - The expression text (for literal detection)
   * @param sourceType - The source type (for non-literal expressions), or null
   * @param isCompound - Whether this is a compound assignment (skip validation)
   */
  validateIntegerAssignment(
    targetType: string,
    expressionText: string,
    sourceType: string | null,
    isCompound: boolean,
  ): void {
    // Skip validation for compound assignments (+<-, -<-, etc.)
    // since the operand doesn't need to fit directly in the target type
    if (isCompound) {
      return;
    }
 
    // Only validate integer types
    if (!this.typeResolver.isIntegerType(targetType)) {
      return;
    }
 
    const trimmed = expressionText.trim();
 
    // Check if it's a direct literal (decimal, hex, or binary)
    const isDecimalLiteral = /^-?\d+$/.exec(trimmed);
    const isHexLiteral = /^0[xX][0-9a-fA-F]+$/.exec(trimmed);
    const isBinaryLiteral = /^0[bB][01]+$/.exec(trimmed);
 
    if (isDecimalLiteral || isHexLiteral || isBinaryLiteral) {
      // Validate literal fits in target type
      this.typeResolver.validateLiteralFitsType(trimmed, targetType);
    } else {
      // Not a literal - check for narrowing/sign conversions
      this.typeResolver.validateTypeConversion(targetType, sourceType);
    }
  }
}
 
export default TypeValidator;