All files / transpiler/logic/symbols/cpp/collectors ClassCollector.ts

84.61% Statements 66/78
60.34% Branches 35/58
100% Functions 7/7
98.5% Lines 66/67

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                                                                                                                  6x 6x   6x 6x   6x 6x   6x 6x 6x   6x   6x 6x 6x         6x 6x 4x               4x     6x                     6x                                       1x 1x   1x 1x 1x   1x               1x   1x                   1x                   5x 8x                     8x     8x 8x 1x             1x       7x 8x   7x     7x 8x   7x 7x                                     1x 1x   1x 1x   1x 1x       1x                 1x                       7x 7x   7x 7x     7x 2x                 2x 2x       5x                         5x             5x     5x 5x                 5x 5x           5x            
/**
 * ClassCollector - Extracts class/struct definitions from C++ parse trees.
 *
 * Handles class members including data fields and member functions.
 * Produces ICppClassSymbol instances with optional field information.
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
import ESourceLanguage from "../../../../../utils/types/ESourceLanguage";
import ICppClassSymbol from "../../../../types/symbols/cpp/ICppClassSymbol";
import ICppFunctionSymbol from "../../../../types/symbols/cpp/ICppFunctionSymbol";
import ICppFieldInfo from "../../../../types/symbols/cpp/ICppFieldInfo";
import SymbolTable from "../../SymbolTable";
import SymbolUtils from "../../SymbolUtils";
import DeclaratorUtils from "../utils/DeclaratorUtils";
import FunctionCollector from "./FunctionCollector";
 
/**
 * Result of collecting a class, including the class symbol and any member function symbols.
 */
interface IClassCollectorResult {
  classSymbol: ICppClassSymbol;
  memberFunctions: ICppFunctionSymbol[];
  warnings: string[];
}
 
/**
 * Internal context for member collection.
 */
interface IMemberCollectionContext {
  readonly className: string;
  readonly sourceFile: string;
  readonly symbolTable: SymbolTable | null;
  readonly fields: Map<string, ICppFieldInfo> | undefined;
  readonly memberFunctions: ICppFunctionSymbol[];
  readonly warnings: string[];
}
 
class ClassCollector {
  /**
   * Collect a class specifier and return an ICppClassSymbol with member functions.
   *
   * @param classSpec The class specifier context
   * @param sourceFile Source file path
   * @param line Line number
   * @param currentNamespace Optional current namespace
   * @param symbolTable Optional symbol table for storing field info
   * @returns The class symbol with member functions, or null if no name
   */
  static collect(
    classSpec: any,
    sourceFile: string,
    line: number,
    currentNamespace?: string,
    symbolTable?: SymbolTable | null,
  ): IClassCollectorResult | null {
    const classHead = classSpec.classHead?.();
    Iif (!classHead) return null;
 
    const classHeadName = classHead.classHeadName?.();
    Iif (!classHeadName) return null;
 
    const className = classHeadName.className?.();
    Iif (!className) return null;
 
    const identifier = className.Identifier?.();
    const name = identifier?.getText();
    Iif (!name) return null;
 
    const fullName = currentNamespace ? `${currentNamespace}::${name}` : name;
 
    const memberFunctions: ICppFunctionSymbol[] = [];
    const warnings: string[] = [];
    const fields: Map<string, ICppFieldInfo> | undefined = symbolTable
      ? new Map()
      : undefined;
 
    // Extract class members
    const memberSpec = classSpec.memberSpecification?.();
    if (memberSpec) {
      const ctx: IMemberCollectionContext = {
        className: fullName,
        sourceFile,
        symbolTable: symbolTable ?? null,
        fields,
        memberFunctions,
        warnings,
      };
      ClassCollector._collectClassMembers(ctx, memberSpec);
    }
 
    const classSymbol: ICppClassSymbol = {
      kind: "class",
      name: fullName,
      sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      parent: currentNamespace,
      fields: fields && fields.size > 0 ? fields : undefined,
    };
 
    return { classSymbol, memberFunctions, warnings };
  }
 
  /**
   * Collect an anonymous class from a typedef.
   *
   * @param classSpec The class specifier context (anonymous)
   * @param typedefName The typedef name to use as the class name
   * @param sourceFile Source file path
   * @param line Line number
   * @param symbolTable Symbol table for storing field info
   * @returns The class symbol result, or null on error
   */
  static collectAnonymousTypedef(
    classSpec: any,
    typedefName: string,
    sourceFile: string,
    line: number,
    symbolTable: SymbolTable,
  ): IClassCollectorResult | null {
    const memberSpec = classSpec.memberSpecification?.();
    Iif (!memberSpec) return null;
 
    const memberFunctions: ICppFunctionSymbol[] = [];
    const warnings: string[] = [];
    const fields = new Map<string, ICppFieldInfo>();
 
    const ctx: IMemberCollectionContext = {
      className: typedefName,
      sourceFile,
      symbolTable,
      fields,
      memberFunctions,
      warnings,
    };
    ClassCollector._collectClassMembers(ctx, memberSpec);
 
    const classSymbol: ICppClassSymbol = {
      kind: "class",
      name: typedefName,
      sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.Cpp,
      isExported: true,
      fields: fields.size > 0 ? fields : undefined,
    };
 
    return { classSymbol, memberFunctions, warnings };
  }
 
  /**
   * Collect class members (data fields and member functions).
   */
  private static _collectClassMembers(
    ctx: IMemberCollectionContext,
    memberSpec: any,
  ): void {
    for (const memberDecl of memberSpec.memberdeclaration?.() ?? []) {
      ClassCollector._collectMemberDeclaration(memberDecl, ctx);
    }
  }
 
  /**
   * Collect a single member declaration.
   */
  private static _collectMemberDeclaration(
    memberDecl: any,
    ctx: IMemberCollectionContext,
  ): void {
    const line = memberDecl.start?.line ?? 0;
 
    // Check for inline function definition within the class
    const funcDef = memberDecl.functionDefinition?.();
    if (funcDef) {
      ClassCollector._collectInlineFunctionDef(
        ctx.className,
        funcDef,
        ctx.sourceFile,
        line,
        ctx.memberFunctions,
      );
      return;
    }
 
    // Get member declaration list (for data members and function declarations)
    const declSpecSeq = memberDecl.declSpecifierSeq?.();
    Iif (!declSpecSeq) return;
 
    const fieldType = DeclaratorUtils.extractTypeFromDeclSpecSeq(declSpecSeq);
 
    // Get declarator list
    const memberDeclList = memberDecl.memberDeclaratorList?.();
    Iif (!memberDeclList) return;
 
    for (const memberDeclarator of memberDeclList.memberDeclarator?.() ?? []) {
      ClassCollector._collectMemberDeclarator(
        memberDeclarator,
        fieldType,
        line,
        ctx,
      );
    }
  }
 
  /**
   * Collect an inline function definition within a class.
   */
  private static _collectInlineFunctionDef(
    className: string,
    funcDef: any,
    sourceFile: string,
    line: number,
    memberFunctions: ICppFunctionSymbol[],
  ): void {
    const declarator = funcDef.declarator?.();
    Iif (!declarator) return;
 
    const funcName = DeclaratorUtils.extractDeclaratorName(declarator);
    Iif (!funcName) return;
 
    const declSpecSeq = funcDef.declSpecifierSeq?.();
    const returnType = declSpecSeq
      ? DeclaratorUtils.extractTypeFromDeclSpecSeq(declSpecSeq)
      : "void";
 
    const symbol = FunctionCollector.collectMemberFunction(
      className,
      funcName,
      declarator,
      returnType,
      sourceFile,
      line,
      false, // not a declaration, it's a definition
    );
    memberFunctions.push(symbol);
  }
 
  /**
   * Collect a single member declarator (function or data field).
   */
  private static _collectMemberDeclarator(
    memberDeclarator: any,
    fieldType: string,
    line: number,
    ctx: IMemberCollectionContext,
  ): void {
    const declarator = memberDeclarator.declarator?.();
    Iif (!declarator) return;
 
    const fieldName = DeclaratorUtils.extractDeclaratorName(declarator);
    Iif (!fieldName) return;
 
    // Check if this is a member function
    if (DeclaratorUtils.declaratorIsFunction(declarator)) {
      const symbol = FunctionCollector.collectMemberFunction(
        ctx.className,
        fieldName,
        declarator,
        fieldType,
        ctx.sourceFile,
        line,
        true, // declaration
      );
      ctx.memberFunctions.push(symbol);
      return;
    }
 
    // Data field
    ClassCollector._collectDataField(fieldName, declarator, fieldType, ctx);
  }
 
  /**
   * Collect a data field declaration.
   */
  private static _collectDataField(
    fieldName: string,
    declarator: any,
    fieldType: string,
    ctx: IMemberCollectionContext,
  ): void {
    // Warn if field name conflicts with C-Next reserved property names
    Iif (SymbolUtils.isReservedFieldName(fieldName)) {
      ctx.warnings.push(
        SymbolUtils.getReservedFieldWarning("C++", ctx.className, fieldName),
      );
    }
 
    // Extract array dimensions if any
    const arrayDimensions = DeclaratorUtils.extractArrayDimensions(declarator);
 
    // Add to SymbolTable if provided
    Eif (ctx.symbolTable) {
      ctx.symbolTable.addStructField(
        ctx.className,
        fieldName,
        fieldType,
        arrayDimensions.length > 0 ? arrayDimensions : undefined,
      );
    }
 
    // Add to fields map if provided
    Eif (ctx.fields) {
      const fieldInfo: ICppFieldInfo = {
        name: fieldName,
        type: fieldType,
        arrayDimensions:
          arrayDimensions.length > 0 ? arrayDimensions : undefined,
      };
      ctx.fields.set(fieldName, fieldInfo);
    }
  }
}
 
export default ClassCollector;