All files / transpiler/logic/symbols CppSymbolCollector.ts

90.06% Statements 281/312
75.44% Branches 169/224
100% Functions 33/33
94.15% Lines 274/291

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                                                              89x             4x                     118x                                                     144x                                   90x 90x   90x 1x     89x 90x 1x     88x 376x     88x       430x     430x 430x 10x 10x       420x 430x 32x 32x       388x 430x   23x       365x 430x 365x         10x 10x   10x 10x     10x 10x       10x         10x   10x                           32x 32x   32x 32x   31x                   31x 31x       32x 32x 29x 54x       31x         365x 365x 347x       365x 365x         365x 365x 17x 17x 17x                                         346x   346x 427x 427x   358x 427x 118x 118x 3x       358x 427x 36x       346x                     118x 118x 118x 118x   118x   115x 115x       3x                       3x   3x 3x   3x 3x 3x                       196x 196x   196x 196x         196x 3x 3x         193x   196x                             347x 347x   346x 346x     346x 347x   194x 196x 196x 196x           115x 115x   115x 115x   115x 115x   115x 115x 115x   115x       115x     115x 73x 73x 73x                   76x 320x               320x     320x 320x 79x 79x       241x 320x   241x     241x 320x   232x 235x                                 79x 79x   79x 79x   64x 79x     79x 79x                                     235x 235x   235x 235x     214x 80x             80x     134x                         80x 80x                                       134x 6x             134x     134x                       134x     134x 134x 134x 134x 134x         134x                       134x       36x 36x   36x 36x   36x 36x       36x                     36x 23x 23x 16x 16x 16x 16x 16x 16x                       16x             746x 746x 746x 746x 746x           746x               1081x 1081x 743x 743x 743x 743x 743x 743x 707x             374x 1081x 335x     39x       410x 410x 410x 410x 203x       207x 410x       207x                                   277x     277x 277x 277x 277x 277x   277x       277x         277x 277x 112x       165x 277x         165x 237x 237x 237x       165x                         237x 237x       237x 237x 237x     237x 237x 42x       237x 237x   237x   226x 61x     237x   9x 9x         237x 70x       237x 237x 226x 226x 223x       237x                       226x 226x   226x 226x 58x     168x 3x     165x               9x 9x 9x 9x 9x                           859x   859x 1089x 1089x 910x 910x 747x 747x 686x           859x          
/**
 * C++ Symbol Collector
 * Extracts symbols from C++ parse trees for the unified symbol table
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
import {
  CPP14Parser,
  ClassSpecifierContext,
} from "../parser/cpp/grammar/CPP14Parser";
import ISymbol from "../../../utils/types/ISymbol";
import ESymbolKind from "../../../utils/types/ESymbolKind";
import ESourceLanguage from "../../../utils/types/ESourceLanguage";
import SymbolTable from "./SymbolTable";
import SymbolUtils from "./SymbolUtils";
import SymbolCollectorContext from "./SymbolCollectorContext";
import ICollectorContext from "./types/ICollectorContext";
 
// Import context types
type TranslationUnitContext = ReturnType<CPP14Parser["translationUnit"]>;
 
/**
 * Collects symbols from a C++ parse tree
 */
class CppSymbolCollector {
  private readonly ctx: ICollectorContext;
 
  private currentNamespace: string | undefined;
 
  constructor(sourceFile: string, symbolTable?: SymbolTable) {
    this.ctx = SymbolCollectorContext.create(sourceFile, symbolTable);
  }
 
  /**
   * Get warnings generated during symbol collection
   */
  getWarnings(): string[] {
    return SymbolCollectorContext.getWarnings(this.ctx);
  }
 
  // ========================================================================
  // Symbol Creation Helpers (Issue #707: Reduce code duplication)
  // ========================================================================
 
  /**
   * Add a class/struct symbol to the symbol table.
   */
  private _addClassSymbol(fullName: string, line: number): void {
    SymbolCollectorContext.addSymbol(this.ctx, {
      name: fullName,
      kind: ESymbolKind.Class,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      parent: this.currentNamespace,
    });
  }
 
  /**
   * Add a member function symbol to the symbol table.
   */
  private _addMemberFunctionSymbol(
    className: string,
    funcName: string,
    returnType: string,
    params: Array<{
      name: string;
      type: string;
      isConst: boolean;
      isArray: boolean;
    }>,
    line: number,
    isDeclaration: boolean,
  ): void {
    SymbolCollectorContext.addSymbol(this.ctx, {
      name: `${className}::${funcName}`,
      kind: ESymbolKind.Function,
      type: returnType,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      isDeclaration: isDeclaration || undefined,
      parent: className,
      parameters: params.length > 0 ? params : undefined,
    });
  }
 
  /**
   * Collect all symbols from a C++ translation unit
   */
  collect(tree: TranslationUnitContext): ISymbol[] {
    SymbolCollectorContext.reset(this.ctx);
    this.currentNamespace = undefined;
 
    if (!tree) {
      return SymbolCollectorContext.getSymbols(this.ctx);
    }
 
    const declSeq = tree.declarationseq?.();
    if (!declSeq) {
      return SymbolCollectorContext.getSymbols(this.ctx);
    }
 
    for (const decl of declSeq.declaration()) {
      this.collectDeclaration(decl);
    }
 
    return SymbolCollectorContext.getSymbols(this.ctx);
  }
 
  private collectDeclaration(decl: any): void {
    const line = decl.start?.line ?? 0;
 
    // Function definition
    const funcDef = decl.functionDefinition?.();
    if (funcDef) {
      this.collectFunctionDefinition(funcDef, line);
      return;
    }
 
    // Namespace definition
    const nsDef = decl.namespaceDefinition?.();
    if (nsDef) {
      this.collectNamespaceDefinition(nsDef, line);
      return;
    }
 
    // Template declaration
    const templDecl = decl.templateDeclaration?.();
    if (templDecl) {
      // Skip template declarations for now - complex to handle
      return;
    }
 
    // Block declaration (simpleDeclaration, etc.)
    const blockDecl = decl.blockDeclaration?.();
    if (blockDecl) {
      this.collectBlockDeclaration(blockDecl, line);
    }
  }
 
  private collectFunctionDefinition(funcDef: any, line: number): void {
    const declarator = funcDef.declarator?.();
    Iif (!declarator) return;
 
    const name = this.extractDeclaratorName(declarator);
    Iif (!name) return;
 
    // Get return type
    const declSpecSeq = funcDef.declSpecifierSeq?.();
    const returnType = declSpecSeq
      ? this.extractTypeFromDeclSpecSeq(declSpecSeq)
      : "void";
 
    const fullName = this.currentNamespace
      ? `${this.currentNamespace}::${name}`
      : name;
 
    // Issue #322: Extract function parameters
    const params = this.extractFunctionParameters(declarator);
 
    SymbolCollectorContext.addSymbol(this.ctx, {
      name: fullName,
      kind: ESymbolKind.Function,
      type: returnType,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      parent: this.currentNamespace,
      parameters: params.length > 0 ? params : undefined,
    });
  }
 
  private collectNamespaceDefinition(nsDef: any, line: number): void {
    const identifier = nsDef.Identifier?.();
    const originalNs = nsDef.originalNamespaceName?.();
 
    const name = identifier?.getText() ?? originalNs?.getText();
    if (!name) return;
 
    SymbolCollectorContext.addSymbol(this.ctx, {
      name,
      kind: ESymbolKind.Namespace,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
    });
 
    // Process namespace body
    const savedNamespace = this.currentNamespace;
    this.currentNamespace = this.currentNamespace
      ? `${this.currentNamespace}::${name}`
      : name;
 
    const body = nsDef.declarationseq?.();
    if (body) {
      for (const decl of body.declaration()) {
        this.collectDeclaration(decl);
      }
    }
 
    this.currentNamespace = savedNamespace;
  }
 
  private collectBlockDeclaration(blockDecl: any, line: number): void {
    // Simple declaration (variables, typedefs, class declarations)
    const simpleDecl = blockDecl.simpleDeclaration?.();
    if (simpleDecl) {
      this.collectSimpleDeclaration(simpleDecl, line);
    }
 
    // Using declaration
    const usingDecl = blockDecl.usingDeclaration?.();
    Iif (usingDecl) {
      // Skip using declarations for now
    }
 
    // Alias declaration (using X = Y)
    const aliasDecl = blockDecl.aliasDeclaration?.();
    if (aliasDecl) {
      const identifier = aliasDecl.Identifier?.();
      Eif (identifier) {
        SymbolCollectorContext.addSymbol(this.ctx, {
          name: identifier.getText(),
          kind: ESymbolKind.Type,
          sourceFile: this.ctx.sourceFile,
          sourceLine: line,
          sourceLanguage: ESourceLanguage.Cpp,
          isExported: true,
          parent: this.currentNamespace,
        });
      }
    }
  }
 
  /**
   * Process type specifiers in a declaration, collecting classes and enums.
   * Returns anonymous class specifier if found (for typedef handling).
   */
  private processTypeSpecifiers(
    declSpecSeq: any,
    line: number,
  ): ClassSpecifierContext | null {
    let anonymousClassSpec: ClassSpecifierContext | null = null;
 
    for (const spec of declSpecSeq.declSpecifier?.() ?? []) {
      const typeSpec = spec.typeSpecifier?.();
      if (!typeSpec) continue;
 
      const classSpec = typeSpec.classSpecifier?.();
      if (classSpec) {
        const result = this.handleClassSpecInDecl(classSpec, line);
        if (result) {
          anonymousClassSpec = result;
        }
      }
 
      const enumSpec = typeSpec.enumSpecifier?.();
      if (enumSpec) {
        this.collectEnumSpecifier(enumSpec, line);
      }
    }
 
    return anonymousClassSpec;
  }
 
  /**
   * Handle a class specifier in a declaration.
   * Returns the class spec if it's anonymous (for typedef handling).
   */
  private handleClassSpecInDecl(
    classSpec: any,
    line: number,
  ): ClassSpecifierContext | null {
    const classHead = classSpec.classHead?.();
    const classHeadName = classHead?.classHeadName?.();
    const className = classHeadName?.className?.();
    const identifier = className?.Identifier?.();
 
    if (identifier?.getText()) {
      // Named struct - collect normally
      this.collectClassSpecifier(classSpec, line);
      return null;
    }
 
    // Issue #342: Anonymous struct - return for typedef handling
    return classSpec;
  }
 
  /**
   * Issue #342: Handle typedef of anonymous struct.
   * Returns true if handled (caller should skip normal processing).
   */
  private tryCollectAnonymousTypedef(
    anonymousClassSpec: ClassSpecifierContext,
    fullName: string,
    line: number,
  ): boolean {
    Iif (!this.ctx.symbolTable) return false;
 
    const memberSpec = anonymousClassSpec.memberSpecification?.();
    Iif (!memberSpec) return false;
 
    this._addClassSymbol(fullName, line);
    this.collectClassMembers(fullName, memberSpec);
    return true;
  }
 
  /**
   * Process a single declarator (variable or function).
   */
  private collectDeclarator(
    declarator: any,
    baseType: string,
    line: number,
    anonymousClassSpec: ClassSpecifierContext | null,
  ): void {
    const name = this.extractDeclaratorName(declarator);
    Iif (!name) return;
 
    const isFunction = this.declaratorIsFunction(declarator);
    const fullName = this.currentNamespace
      ? `${this.currentNamespace}::${name}`
      : name;
 
    // Issue #342: Handle anonymous struct typedef
    if (anonymousClassSpec) {
      Eif (this.tryCollectAnonymousTypedef(anonymousClassSpec, fullName, line)) {
        return;
      }
    }
 
    // Issue #322: Extract parameters for function declarations
    const params = isFunction ? this.extractFunctionParameters(declarator) : [];
 
    SymbolCollectorContext.addSymbol(this.ctx, {
      name: fullName,
      kind: isFunction ? ESymbolKind.Function : ESymbolKind.Variable,
      type: baseType,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      isDeclaration: isFunction,
      parent: this.currentNamespace,
      parameters: params.length > 0 ? params : undefined,
    });
  }
 
  private collectSimpleDeclaration(simpleDecl: any, line: number): void {
    const declSpecSeq = simpleDecl.declSpecifierSeq?.();
    if (!declSpecSeq) return;
 
    const baseType = this.extractTypeFromDeclSpecSeq(declSpecSeq);
    const anonymousClassSpec = this.processTypeSpecifiers(declSpecSeq, line);
 
    // Collect declarators (variables, function prototypes)
    const initDeclList = simpleDecl.initDeclaratorList?.();
    if (!initDeclList) return;
 
    for (const initDecl of initDeclList.initDeclarator()) {
      const declarator = initDecl.declarator?.();
      Eif (declarator) {
        this.collectDeclarator(declarator, baseType, line, anonymousClassSpec);
      }
    }
  }
 
  private collectClassSpecifier(classSpec: any, line: number): void {
    const classHead = classSpec.classHead?.();
    Iif (!classHead) return;
 
    const classHeadName = classHead.classHeadName?.();
    Iif (!classHeadName) return;
 
    const className = classHeadName.className?.();
    Iif (!className) return;
 
    const identifier = className.Identifier?.();
    const name = identifier?.getText();
    Iif (!name) return;
 
    const fullName = this.currentNamespace
      ? `${this.currentNamespace}::${name}`
      : name;
 
    this._addClassSymbol(fullName, line);
 
    // Extract struct/class field information if SymbolTable is available
    if (this.ctx.symbolTable) {
      const memberSpec = classSpec.memberSpecification?.();
      Eif (memberSpec) {
        this.collectClassMembers(fullName, memberSpec);
      }
    }
  }
 
  /**
   * Collect class/struct member fields
   */
  private collectClassMembers(className: string, memberSpec: any): void {
    // Iterate through member declarations
    for (const memberDecl of memberSpec.memberdeclaration?.() ?? []) {
      this.collectMemberDeclaration(className, memberDecl);
    }
  }
 
  /**
   * Collect a single member declaration
   */
  private collectMemberDeclaration(className: string, memberDecl: any): void {
    const line = memberDecl.start?.line ?? 0;
 
    // Issue #322: Check for inline function definition within the class
    const funcDef = memberDecl.functionDefinition?.();
    if (funcDef) {
      this._collectInlineFunctionDef(className, funcDef, line);
      return;
    }
 
    // Get member declaration list (for data members and function declarations)
    const declSpecSeq = memberDecl.declSpecifierSeq?.();
    Iif (!declSpecSeq) return;
 
    const fieldType = this.extractTypeFromDeclSpecSeq(declSpecSeq);
 
    // Get declarator list
    const memberDeclList = memberDecl.memberDeclaratorList?.();
    if (!memberDeclList) return;
 
    for (const memberDeclarator of memberDeclList.memberDeclarator?.() ?? []) {
      this._collectMemberDeclarator(
        className,
        memberDeclarator,
        fieldType,
        line,
      );
    }
  }
 
  /**
   * Collect an inline function definition within a class
   */
  private _collectInlineFunctionDef(
    className: string,
    funcDef: any,
    line: number,
  ): void {
    const declarator = funcDef.declarator?.();
    Iif (!declarator) return;
 
    const funcName = this.extractDeclaratorName(declarator);
    if (!funcName) return;
 
    const declSpecSeq = funcDef.declSpecifierSeq?.();
    const returnType = declSpecSeq
      ? this.extractTypeFromDeclSpecSeq(declSpecSeq)
      : "void";
    const params = this.extractFunctionParameters(declarator);
    this._addMemberFunctionSymbol(
      className,
      funcName,
      returnType,
      params,
      line,
      false,
    );
  }
 
  /**
   * Collect a single member declarator (function or data field)
   */
  private _collectMemberDeclarator(
    className: string,
    memberDeclarator: any,
    fieldType: string,
    line: number,
  ): void {
    const declarator = memberDeclarator.declarator?.();
    Iif (!declarator) return;
 
    const fieldName = this.extractDeclaratorName(declarator);
    if (!fieldName) return;
 
    // Issue #322: Collect member functions with their parameters
    if (this.declaratorIsFunction(declarator)) {
      this._collectMemberFunction(
        className,
        fieldName,
        declarator,
        fieldType,
        line,
      );
      return;
    }
 
    this._collectDataField(className, fieldName, declarator, fieldType);
  }
 
  /**
   * Collect a member function declaration
   */
  private _collectMemberFunction(
    className: string,
    funcName: string,
    declarator: any,
    returnType: string,
    line: number,
  ): void {
    const params = this.extractFunctionParameters(declarator);
    this._addMemberFunctionSymbol(
      className,
      funcName,
      returnType,
      params,
      line,
      true,
    );
  }
 
  /**
   * Collect a data field declaration
   */
  private _collectDataField(
    className: string,
    fieldName: string,
    declarator: any,
    fieldType: string,
  ): void {
    // Warn if field name conflicts with C-Next reserved property names
    if (SymbolUtils.isReservedFieldName(fieldName)) {
      SymbolCollectorContext.addWarning(
        this.ctx,
        SymbolUtils.getReservedFieldWarning("C++", className, fieldName),
      );
    }
 
    // Extract array dimensions if any
    const arrayDimensions = this.extractArrayDimensions(declarator);
 
    // Add to SymbolTable
    this.ctx.symbolTable!.addStructField(
      className,
      fieldName,
      fieldType,
      arrayDimensions.length > 0 ? arrayDimensions : undefined,
    );
  }
 
  /**
   * Extract array dimensions from a declarator
   */
  private extractArrayDimensions(declarator: any): number[] {
    const dimensions: number[] = [];
 
    // For C++, we need to check both pointer and no-pointer declarators
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      const noPtr = ptrDecl.noPointerDeclarator?.();
      Eif (noPtr) {
        return this.extractArrayDimensionsFromNoPtr(noPtr);
      }
    }
 
    const noPtr = declarator.noPointerDeclarator?.();
    Iif (noPtr) {
      return this.extractArrayDimensionsFromNoPtr(noPtr);
    }
 
    return dimensions;
  }
 
  /**
   * Extract array dimensions from a noPointerDeclarator
   */
  private extractArrayDimensionsFromNoPtr(noPtr: any): number[] {
    // Use shared utility for regex-based extraction
    return SymbolUtils.parseArrayDimensions(noPtr.getText());
  }
 
  private collectEnumSpecifier(enumSpec: any, line: number): void {
    const enumHead = enumSpec.enumHead?.();
    Iif (!enumHead) return;
 
    const identifier = enumHead.Identifier?.();
    Iif (!identifier) return;
 
    const name = identifier.getText();
    const fullName = this.currentNamespace
      ? `${this.currentNamespace}::${name}`
      : name;
 
    SymbolCollectorContext.addSymbol(this.ctx, {
      name: fullName,
      kind: ESymbolKind.Enum,
      sourceFile: this.ctx.sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      parent: this.currentNamespace,
    });
 
    // Issue #208: Extract enum backing type for typed enums (e.g., enum EPressureType : uint8_t)
    if (this.ctx.symbolTable) {
      const enumbase = enumHead.enumbase?.();
      if (enumbase) {
        const typeSpecSeq = enumbase.typeSpecifierSeq?.();
        Eif (typeSpecSeq) {
          const typeName = typeSpecSeq.getText();
          const bitWidth = this.getTypeWidth(typeName);
          Eif (bitWidth > 0) {
            this.ctx.symbolTable.addEnumBitWidth(fullName, bitWidth);
          }
        }
      }
    }
  }
 
  /**
   * Issue #208: Map C/C++ type names to their bit widths
   * Delegates to shared utility for consistent type width mapping
   */
  private getTypeWidth(typeName: string): number {
    return SymbolUtils.getTypeWidth(typeName);
  }
 
  // Helper methods
 
  private extractDeclaratorName(declarator: any): string | null {
    // Pointer declarator -> noPointerDeclarator
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      const noPtr = ptrDecl.noPointerDeclarator?.();
      Eif (noPtr) {
        return this.extractNoPointerDeclaratorName(noPtr);
      }
    }
 
    // No pointer declarator
    const noPtr = declarator.noPointerDeclarator?.();
    Iif (noPtr) {
      return this.extractNoPointerDeclaratorName(noPtr);
    }
 
    return null;
  }
 
  private extractNoPointerDeclaratorName(noPtr: any): string | null {
    const declId = noPtr.declaratorid?.();
    if (declId) {
      const idExpr = declId.idExpression?.();
      Eif (idExpr) {
        const unqualId = idExpr.unqualifiedId?.();
        Eif (unqualId) {
          const identifier = unqualId.Identifier?.();
          if (identifier) {
            return identifier.getText();
          }
        }
      }
    }
 
    // Recursive case
    const innerNoPtr = noPtr.noPointerDeclarator?.();
    if (innerNoPtr) {
      return this.extractNoPointerDeclaratorName(innerNoPtr);
    }
 
    return null;
  }
 
  private declaratorIsFunction(declarator: any): boolean {
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      const noPtr = ptrDecl.noPointerDeclarator?.();
      if (noPtr?.parametersAndQualifiers?.()) {
        return true;
      }
    }
 
    const noPtr = declarator.noPointerDeclarator?.();
    Iif (noPtr?.parametersAndQualifiers?.()) {
      return true;
    }
 
    return false;
  }
 
  /**
   * Issue #322: Extract function parameters from a declarator.
   * Returns an array of parameter info objects with name, type, and pointer flag.
   */
  private extractFunctionParameters(declarator: any): Array<{
    name: string;
    type: string;
    isConst: boolean;
    isArray: boolean;
  }> {
    const params: Array<{
      name: string;
      type: string;
      isConst: boolean;
      isArray: boolean;
    }> = [];
 
    // Find parametersAndQualifiers from the declarator
    let paramsAndQuals: any = null;
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      const noPtr = ptrDecl.noPointerDeclarator?.();
      paramsAndQuals = noPtr?.parametersAndQualifiers?.();
    }
    Iif (!paramsAndQuals) {
      const noPtr = declarator.noPointerDeclarator?.();
      paramsAndQuals = noPtr?.parametersAndQualifiers?.();
    }
    Iif (!paramsAndQuals) {
      return params;
    }
 
    // Get parameterDeclarationClause
    const paramClause = paramsAndQuals.parameterDeclarationClause?.();
    if (!paramClause) {
      return params;
    }
 
    // Get parameterDeclarationList
    const paramList = paramClause.parameterDeclarationList?.();
    Iif (!paramList) {
      return params;
    }
 
    // Iterate over parameterDeclaration entries
    for (const paramDecl of paramList.parameterDeclaration?.() ?? []) {
      const paramInfo = this.extractParameterInfo(paramDecl);
      Eif (paramInfo) {
        params.push(paramInfo);
      }
    }
 
    return params;
  }
 
  /**
   * Issue #322: Extract type and name info from a single parameter declaration.
   */
  private extractParameterInfo(paramDecl: any): {
    name: string;
    type: string;
    isConst: boolean;
    isArray: boolean;
  } | null {
    // Get the type from declSpecifierSeq
    const declSpecSeq = paramDecl.declSpecifierSeq?.();
    Iif (!declSpecSeq) {
      return null;
    }
 
    let baseType = this.extractTypeFromDeclSpecSeq(declSpecSeq);
    let isConst = false;
    let isPointer = false;
 
    // Check for const qualifier
    const declText = declSpecSeq.getText();
    if (declText.includes("const")) {
      isConst = true;
    }
 
    // Check for pointer in declarator or abstractDeclarator
    const declarator = paramDecl.declarator?.();
    const abstractDecl = paramDecl.abstractDeclarator?.();
 
    if (declarator) {
      // Check if declarator has pointer operator
      if (this.declaratorHasPointer(declarator)) {
        isPointer = true;
      }
    }
    if (abstractDecl) {
      // Abstract declarator (no name) - check for pointer
      Eif (this.abstractDeclaratorHasPointer(abstractDecl)) {
        isPointer = true;
      }
    }
 
    // If pointer, append * to the type
    if (isPointer) {
      baseType = baseType + "*";
    }
 
    // Get parameter name (may be empty for abstract declarators)
    let paramName = "";
    if (declarator) {
      const name = this.extractDeclaratorName(declarator);
      if (name) {
        paramName = name;
      }
    }
 
    return {
      name: paramName,
      type: baseType,
      isConst,
      isArray: false, // Could be enhanced to detect arrays
    };
  }
 
  /**
   * Issue #322: Check if a declarator contains a pointer operator.
   */
  private declaratorHasPointer(declarator: any): boolean {
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      // Check for pointerOperator children
      const ptrOps = ptrDecl.pointerOperator?.();
      if (ptrOps && ptrOps.length > 0) {
        return true;
      }
      // Also check getText for *
      if (ptrDecl.getText().includes("*")) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Issue #322: Check if an abstract declarator (pointer without name) contains a pointer.
   */
  private abstractDeclaratorHasPointer(abstractDecl: any): boolean {
    // Check for pointerAbstractDeclarator
    const ptrAbstract = abstractDecl.pointerAbstractDeclarator?.();
    Eif (ptrAbstract) {
      const ptrOps = ptrAbstract.pointerOperator?.();
      Eif (ptrOps && ptrOps.length > 0) {
        return true;
      }
      if (ptrAbstract.getText().includes("*")) {
        return true;
      }
    }
    // Simple check for * in the text
    if (abstractDecl.getText().includes("*")) {
      return true;
    }
    return false;
  }
 
  private extractTypeFromDeclSpecSeq(declSpecSeq: any): string {
    const parts: string[] = [];
 
    for (const spec of declSpecSeq.declSpecifier?.() ?? []) {
      const typeSpec = spec.typeSpecifier?.();
      if (typeSpec) {
        const trailingType = typeSpec.trailingTypeSpecifier?.();
        if (trailingType) {
          const simpleType = trailingType.simpleTypeSpecifier?.();
          if (simpleType) {
            parts.push(simpleType.getText());
          }
        }
      }
    }
 
    return parts.join(" ") || "int";
  }
}
 
export default CppSymbolCollector;