All files / transpiler/logic/symbols/c index.ts

90.98% Statements 111/122
80.76% Branches 63/78
100% Functions 13/13
99.04% Lines 104/105

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                                                                                                                      97x 97x   97x 97x 5x     92x   120x 120x 10x       10x 10x   10x       110x 110x 100x                   92x                         100x 100x   100x     100x 100x     100x                 100x 100x 44x                     100x 100x 9x               100x 100x 32x 32x     68x                                           44x             44x       44x                       44x 43x                       19x 19x 1x 1x   18x                 19x 19x   1x                         9x 9x   8x 8x 21x                       32x 34x 34x   34x 34x     34x   34x     3x     3x     31x 24x                     7x                                               68x   68x   68x     35x                     35x   35x 27x                 8x                                       68x   68x 141x 141x 141x 36x 36x       68x                     8x 8x   8x 8x   8x                   35x 35x 73x 73x 39x     35x                       3x 3x         3x     3x     2x 3x   2x 3x   2x               2x 2x   2x 2x   2x          
/**
 * CResolver - Orchestrates C symbol collection using composable collectors.
 *
 * This resolver collects symbols from C header parse trees and returns
 * typed TCSymbol[] discriminated unions.
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
import type {
  CompilationUnitContext,
  DeclarationContext,
  DeclarationSpecifiersContext,
  DeclarationSpecifierContext,
} from "../../parser/c/grammar/CParser";
import type TCSymbol from "../../../types/symbols/c/TCSymbol";
import SymbolTable from "../SymbolTable";
import DeclaratorUtils from "./utils/DeclaratorUtils";
import StructCollector from "./collectors/StructCollector";
import EnumCollector from "./collectors/EnumCollector";
import FunctionCollector from "./collectors/FunctionCollector";
import TypedefCollector from "./collectors/TypedefCollector";
import VariableCollector from "./collectors/VariableCollector";
 
/**
 * Result of resolving C symbols.
 */
interface ICResolverResult {
  /** Collected symbols */
  readonly symbols: TCSymbol[];
 
  /** Warnings generated during collection */
  readonly warnings: string[];
}
 
/**
 * Internal context for declaration processing.
 */
interface IDeclarationContext {
  readonly sourceFile: string;
  readonly line: number;
  readonly isTypedef: boolean;
  readonly isExtern: boolean;
  readonly symbols: TCSymbol[];
}
 
class CResolver {
  /**
   * Resolve all symbols from a C compilation unit.
   *
   * @param tree The parsed compilation unit context
   * @param sourceFile Source file path
   * @param symbolTable Optional symbol table for field tracking
   */
  static resolve(
    tree: CompilationUnitContext,
    sourceFile: string,
    symbolTable?: SymbolTable | null,
  ): ICResolverResult {
    const symbols: TCSymbol[] = [];
    const warnings: string[] = [];
 
    const translationUnit = tree.translationUnit();
    if (!translationUnit) {
      return { symbols, warnings };
    }
 
    for (const extDecl of translationUnit.externalDeclaration()) {
      // Function definition
      const funcDef = extDecl.functionDefinition();
      if (funcDef) {
        const funcSymbol = FunctionCollector.collectFromDefinition(
          funcDef,
          sourceFile,
        );
        Eif (funcSymbol) {
          symbols.push(funcSymbol);
        }
        continue;
      }
 
      // Declaration (typedef, struct, variable, function prototype)
      const decl = extDecl.declaration();
      if (decl) {
        CResolver.collectDeclaration(
          decl,
          sourceFile,
          symbolTable ?? null,
          symbols,
          warnings,
        );
      }
    }
 
    return { symbols, warnings };
  }
 
  /**
   * Collect symbols from a declaration.
   */
  private static collectDeclaration(
    decl: DeclarationContext,
    sourceFile: string,
    symbolTable: SymbolTable | null,
    symbols: TCSymbol[],
    warnings: string[],
  ): void {
    const declSpecs = decl.declarationSpecifiers();
    Iif (!declSpecs) return;
 
    const line = decl.start?.line ?? 0;
 
    // Check for storage class specifiers
    const isTypedef = DeclaratorUtils.hasStorageClass(declSpecs, "typedef");
    const isExtern = DeclaratorUtils.hasStorageClass(declSpecs, "extern");
 
    // Build context early for reuse across helper methods
    const ctx: IDeclarationContext = {
      sourceFile,
      line,
      isTypedef,
      isExtern,
      symbols,
    };
 
    // Check for struct/union
    const structSpec = DeclaratorUtils.findStructOrUnionSpecifier(declSpecs);
    if (structSpec) {
      CResolver.collectStructSymbol(
        structSpec,
        decl,
        declSpecs,
        ctx,
        symbolTable,
        warnings,
      );
    }
 
    // Check for enum
    const enumSpec = DeclaratorUtils.findEnumSpecifier(declSpecs);
    if (enumSpec) {
      CResolver.collectEnumSymbols(
        enumSpec,
        ctx.sourceFile,
        ctx.line,
        ctx.symbols,
      );
    }
 
    const initDeclList = decl.initDeclaratorList();
    if (initDeclList) {
      const baseType = DeclaratorUtils.extractTypeFromDeclSpecs(declSpecs);
      CResolver.collectInitDeclaratorList(initDeclList, baseType, ctx);
    } else {
      // Handle case where identifier is parsed as typedefName in declarationSpecifiers
      CResolver.collectFromDeclSpecsTypedefName(
        declSpecs,
        structSpec,
        enumSpec,
        ctx,
      );
    }
  }
 
  /**
   * Collect struct symbol from a struct specifier.
   * Extracted to reduce cognitive complexity of collectDeclaration().
   */
  private static collectStructSymbol(
    structSpec: any,
    decl: DeclarationContext,
    declSpecs: DeclarationSpecifiersContext,
    ctx: IDeclarationContext,
    symbolTable: SymbolTable | null,
    warnings: string[],
  ): void {
    // For typedef struct, extract the typedef name
    const typedefName = ctx.isTypedef
      ? CResolver.extractTypedefName(decl, declSpecs)
      : undefined;
 
    // Issue #957: Check if the typedef's declarator has a pointer prefix.
    // For "typedef struct X *Y", Y is already a pointer type, NOT an opaque struct.
    // Don't mark pointer typedefs as opaque.
    const isPointerTypedef = ctx.isTypedef
      ? CResolver.isPointerTypedef(decl)
      : false;
 
    const structSymbol = StructCollector.collect(
      structSpec,
      ctx.sourceFile,
      ctx.line,
      symbolTable,
      {
        typedefName,
        isTypedef: ctx.isTypedef,
        warnings,
        isPointerTypedef,
      },
    );
    if (structSymbol) {
      ctx.symbols.push(structSymbol);
    }
  }
 
  /**
   * Extract typedef name from declaration.
   * First try from init-declarator-list, then fall back to specifiers.
   */
  private static extractTypedefName(
    decl: DeclarationContext,
    declSpecs: DeclarationSpecifiersContext,
  ): string | undefined {
    const initDeclList = decl.initDeclaratorList();
    if (initDeclList) {
      const name = DeclaratorUtils.extractFirstDeclaratorName(initDeclList);
      Eif (name) return name;
    }
    return DeclaratorUtils.extractTypedefNameFromSpecs(declSpecs);
  }
 
  /**
   * Check if a typedef declaration has a pointer declarator.
   * For "typedef struct X *Y", the declarator is "*Y" which has a pointer.
   * Used for Issue #957 to distinguish pointer typedefs from opaque struct typedefs.
   */
  private static isPointerTypedef(decl: DeclarationContext): boolean {
    const initDeclList = decl.initDeclaratorList();
    if (!initDeclList) return false;
 
    return DeclaratorUtils.firstDeclaratorHasPointer(initDeclList);
  }
 
  /**
   * Collect enum symbols from an enum specifier.
   * Extracted to reduce cognitive complexity of collectDeclaration().
   */
  private static collectEnumSymbols(
    enumSpec: any,
    sourceFile: string,
    line: number,
    symbols: TCSymbol[],
  ): void {
    const enumResult = EnumCollector.collect(enumSpec, sourceFile, line);
    if (!enumResult) return;
 
    symbols.push(enumResult.enum);
    for (const member of enumResult.members) {
      symbols.push(member);
    }
  }
 
  /**
   * Collect symbols from init declarator list.
   */
  private static collectInitDeclaratorList(
    initDeclList: any,
    baseType: string,
    ctx: IDeclarationContext,
  ): void {
    for (const initDecl of initDeclList.initDeclarator()) {
      const declarator = initDecl.declarator();
      Iif (!declarator) continue;
 
      const name = DeclaratorUtils.extractDeclaratorName(declarator);
      Iif (!name) continue;
 
      // Check if this is a function declaration (has parameter list)
      const isFunction = DeclaratorUtils.declaratorIsFunction(declarator);
 
      if (ctx.isTypedef) {
        // For function pointer typedefs like `typedef void (*Callback)(int)`,
        // reconstruct the full type including (*) so consumers can detect it
        const typedefType = CResolver.isFunctionPointerDeclarator(declarator)
          ? `${baseType} (*)(${CResolver.extractParamText(declarator)})`
          : baseType;
        ctx.symbols.push(
          TypedefCollector.collect(name, typedefType, ctx.sourceFile, ctx.line),
        );
      } else if (isFunction) {
        ctx.symbols.push(
          FunctionCollector.collectFromDeclaration(
            name,
            baseType,
            declarator,
            ctx.sourceFile,
            ctx.line,
            ctx.isExtern,
          ),
        );
      } else {
        ctx.symbols.push(
          VariableCollector.collect(
            name,
            baseType,
            declarator,
            ctx.sourceFile,
            ctx.line,
            ctx.isExtern,
          ),
        );
      }
    }
  }
 
  /**
   * Collect symbols when identifier appears as typedefName in declarationSpecifiers.
   * This handles the C grammar ambiguity where variable names can be parsed as typedef names.
   */
  private static collectFromDeclSpecsTypedefName(
    declSpecs: DeclarationSpecifiersContext,
    structSpec: any,
    enumSpec: any,
    ctx: IDeclarationContext,
  ): void {
    const specs = declSpecs.declarationSpecifier();
    const { name: lastTypedefName, index: lastTypedefIndex } =
      CResolver.findLastTypedefName(specs);
 
    if (!lastTypedefName || lastTypedefIndex < 0) return;
 
    // Skip duplicates for non-typedef declarations
    Iif (
      !ctx.isTypedef &&
      CResolver.shouldSkipDuplicateTypedefName(
        lastTypedefName,
        structSpec,
        enumSpec,
      )
    ) {
      return;
    }
 
    const baseType = CResolver.buildBaseTypeFromSpecs(specs, lastTypedefIndex);
 
    if (ctx.isTypedef) {
      ctx.symbols.push(
        TypedefCollector.collect(
          lastTypedefName,
          baseType,
          ctx.sourceFile,
          ctx.line,
        ),
      );
    } else {
      ctx.symbols.push(
        VariableCollector.collectFromDeclSpecs(
          lastTypedefName,
          baseType,
          ctx.sourceFile,
          ctx.line,
          ctx.isExtern,
        ),
      );
    }
  }
 
  /**
   * Find the last typedefName in declaration specifiers.
   */
  private static findLastTypedefName(specs: DeclarationSpecifierContext[]): {
    name: string | undefined;
    index: number;
  } {
    let name: string | undefined;
    let index = -1;
 
    for (let i = 0; i < specs.length; i++) {
      const typeSpec = specs[i].typeSpecifier();
      const typedefName = typeSpec?.typedefName?.();
      if (typedefName) {
        name = typedefName.getText();
        index = i;
      }
    }
 
    return { name, index };
  }
 
  /**
   * Check if typedef name should be skipped to avoid duplicates.
   */
  private static shouldSkipDuplicateTypedefName(
    typedefName: string,
    structSpec: any,
    enumSpec: any,
  ): boolean {
    const structName = structSpec?.Identifier?.()?.getText();
    Iif (structName === typedefName) return true;
 
    const enumName = enumSpec?.Identifier?.()?.getText();
    Iif (enumName === typedefName) return true;
 
    return false;
  }
 
  /**
   * Build base type string from specifiers before the typedef name.
   */
  private static buildBaseTypeFromSpecs(
    specs: DeclarationSpecifierContext[],
    endIndex: number,
  ): string {
    const typeParts: string[] = [];
    for (let i = 0; i < endIndex; i++) {
      const typeSpec = specs[i].typeSpecifier();
      if (typeSpec) {
        typeParts.push(typeSpec.getText());
      }
    }
    return typeParts.join(" ") || "int";
  }
 
  /**
   * Check if a declarator represents a function pointer.
   * For `(*PointCallback)(Point p)`, the C grammar parses as:
   *   declarator -> directDeclarator
   *   directDeclarator -> directDeclarator '(' parameterTypeList ')'
   *   inner directDeclarator -> '(' declarator ')'
   *   inner declarator -> pointer directDeclarator -> * PointCallback
   */
  static isFunctionPointerDeclarator(declarator: any): boolean {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return false;
 
    // The outer directDeclarator has: directDeclarator '(' params ')'
    // Check for parameter list at the outer level
    const hasParams =
      directDecl.parameterTypeList?.() !== null ||
      Boolean(directDecl.LeftParen?.());
 
    if (!hasParams) return false;
 
    // The inner directDeclarator should be '(' declarator ')' with a pointer
    const innerDirectDecl = directDecl.directDeclarator?.();
    Iif (!innerDirectDecl) return false;
 
    const nestedDecl = innerDirectDecl.declarator?.();
    Iif (!nestedDecl) return false;
 
    return Boolean(nestedDecl.pointer?.());
  }
 
  /**
   * Extract parameter text from a function pointer declarator.
   * Returns the text of the parameters from a function pointer like "(*Callback)(Point p)".
   */
  static extractParamText(declarator: any): string {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return "";
 
    const paramTypeList = directDecl.parameterTypeList?.();
    Iif (!paramTypeList) return "";
 
    return paramTypeList.getText();
  }
}
 
export default CResolver;