All files / PARSE/3-Declare/c/utils DeclaratorUtils.ts

91.01% Statements 152/167
78.57% Branches 88/112
100% Functions 25/25
96.71% Lines 147/152

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                                                          344x 344x   344x                   483x 483x 338x       145x 483x 6x         139x 483x 139x                   136x 136x       136x     31x   22x             121x 121x   121x 121x   104x 121x   104x                   109x 109x   38x 38x     38x 109x   109x 38x 38x 38x 38x       38x                                                 275x 275x               113x 113x     113x                 182x   182x 224x 224x 183x       182x                             614x 614x 79x 79x       535x 535x 3x 3x       532x                                   105x 5x         100x                           105x     105x   105x     5x 105x               5x                   354x   830x                   708x 1198x 1198x 197x     511x                 354x 765x 765x 553x 553x 103x       251x                 354x 832x 832x 620x 620x 14x       340x                 155x     155x 155x 163x 163x 162x     163x 163x 1x     163x     155x                     45x 45x   45x 45x       45x 45x                 45x   45x 56x 56x 56x       45x                 56x 56x     56x   56x 56x         56x 56x 56x 56x 56x       56x       56x                 56x 56x 56x   56x 56x 54x     56x 2x 2x     54x                   68x 204x 204x 136x 136x 68x                             4x 4x   4x 4x   4x                     4x 4x   4x 4x   4x          
/**
 * DeclaratorUtils - Shared utilities for extracting information from C declarators.
 *
 * Provides methods for extracting names, types, parameters, and array dimensions
 * from C parse tree declarator contexts.
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
import type {
  DeclarationSpecifiersContext,
  DeclaratorContext,
  StructOrUnionSpecifierContext,
  EnumSpecifierContext,
  StructDeclarationListContext,
  StructDeclarationContext,
  StructDeclaratorContext,
  InitDeclaratorListContext,
  TypeSpecifierContext,
} from "../../../2-Parse/c/grammar/CParser";
import SymbolUtils from "../../SymbolUtils";
import IExtractedParameter from "../../shared/IExtractedParameter";
import ParameterExtractorUtils from "../../shared/ParameterExtractorUtils";
 
class DeclaratorUtils {
  /**
   * Extract name from a declarator context.
   */
  static extractDeclaratorName(declarator: any): string | null {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return null;
 
    return DeclaratorUtils.extractDirectDeclaratorName(directDecl);
  }
 
  /**
   * Extract identifier from directDeclarator, handling arrays and function pointers.
   * The C grammar has recursive directDeclarator for arrays: `directDeclarator '[' ... ']'`
   * so `buf[8]` is parsed as directDeclarator('[', directDeclarator('buf'), ']')
   */
  static extractDirectDeclaratorName(directDecl: any): string | null {
    // Check for identifier (base case)
    const identifier = directDecl.Identifier?.();
    if (identifier) {
      return identifier.getText();
    }
 
    // Nested declarator in parentheses: '(' declarator ')'
    const nestedDecl = directDecl.declarator?.();
    if (nestedDecl) {
      return DeclaratorUtils.extractDeclaratorName(nestedDecl);
    }
 
    // Nested directDeclarator for arrays/functions
    // Grammar: directDeclarator '[' ... ']' or directDeclarator '(' ... ')'
    const nestedDirectDecl = directDecl.directDeclarator?.();
    if (nestedDirectDecl) {
      return DeclaratorUtils.extractDirectDeclaratorName(nestedDirectDecl);
    }
 
    return null;
  }
 
  /**
   * Check if a declarator represents a function.
   */
  static declaratorIsFunction(declarator: any): boolean {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return false;
 
    // Check for parameter type list (function with params) or empty parens
    // The C grammar: directDeclarator '(' parameterTypeList ')' | directDeclarator '(' identifierList? ')'
    if (directDecl.parameterTypeList?.() !== null) return true;
 
    // Check for LeftParen token - indicates function declarator even with empty params
    if (directDecl.LeftParen?.()) return true;
 
    return false;
  }
 
  /**
   * Extract function parameters from a declarator.
   */
  static extractFunctionParameters(declarator: any): IExtractedParameter[] {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return [];
 
    const paramTypeList = directDecl.parameterTypeList?.();
    if (!paramTypeList) return [];
 
    const paramList = paramTypeList.parameterList?.();
    Iif (!paramList) return [];
 
    return ParameterExtractorUtils.processParameterList(
      paramList,
      DeclaratorUtils.extractParameterInfo,
    );
  }
 
  /**
   * Extract parameter info from a single parameter declaration.
   */
  static extractParameterInfo(paramDecl: any): IExtractedParameter | null {
    const declSpecs = paramDecl.declarationSpecifiers?.();
    if (!declSpecs) return null;
 
    const baseType = DeclaratorUtils.extractTypeFromDeclSpecs(declSpecs);
    const isConst = declSpecs.getText().includes("const");
 
    // Check for array in declarator
    const declarator = paramDecl.declarator?.();
    let isArray = false;
 
    if (declarator) {
      const directDecl = declarator.directDeclarator?.();
      Eif (directDecl) {
        const text = directDecl.getText();
        isArray = text.includes("[") && text.includes("]");
      }
    }
 
    return ParameterExtractorUtils.buildParameterInfo(
      declarator,
      DeclaratorUtils.pointerType(baseType, declarator),
      isConst,
      isArray,
      DeclaratorUtils.extractDeclaratorName,
    );
  }
 
  /**
   * The C type a declarator gives its base type: `Dev` under `**out` is
   * `Dev**`.
   *
   * The grammar's `pointer` holds EVERY level -- `**out` is one context with
   * two `*` -- so asking only whether it is present says "at least one". A
   * parameter, a variable and a return type each asked exactly that, and a
   * `Dev**` out-parameter was recorded as `Dev*`: codegen could not see that
   * it takes the ADDRESS of a handle, and passed the handle itself. A typedef
   * alone kept the depth (`typedef struct Sample **Grid`), by a count of its
   * own. They all read it here now.
   */
  static pointerType(
    baseType: string,
    declarator: DeclaratorContext | null | undefined,
  ): string {
    const pointerText = declarator?.pointer()?.getText() ?? "";
    return baseType + "*".repeat(pointerText.split("*").length - 1);
  }
 
  /**
   * Extract array dimensions from a declarator.
   * Issue #981: Returns (number | string)[] to support macro-sized arrays.
   */
  static extractArrayDimensions(declarator: any): (number | string)[] {
    const directDecl = declarator.directDeclarator?.();
    Iif (!directDecl) return [];
 
    // Use shared utility for regex-based extraction
    return SymbolUtils.parseArrayDimensions(directDecl.getText());
  }
 
  /**
   * Extract type string from declaration specifiers.
   */
  static extractTypeFromDeclSpecs(
    declSpecs: DeclarationSpecifiersContext,
  ): string {
    const parts: string[] = [];
 
    for (const spec of declSpecs.declarationSpecifier()) {
      const typeSpec = spec.typeSpecifier();
      if (typeSpec) {
        parts.push(DeclaratorUtils.typeSpecifierText(typeSpec));
      }
    }
 
    return parts.join(" ") || "int";
  }
 
  /**
   * How one type specifier is spelled in a recorded C type -- the one
   * decision for declarations, typedefs and struct fields (#1668).
   *
   * `getText()` concatenates tokens, so `struct foo` and `enum tag_e` were
   * recorded with the keyword and the tag run together, which no lookup
   * matches.
   * A struct or union is spelled by its tag, the name its fields are keyed
   * by (an anonymous one is reconstructed); an enum as `enum tag`, or
   * `enum {...}` when anonymous, so its kind is still readable.
   */
  static typeSpecifierText(typeSpec: TypeSpecifierContext): string {
    const structSpec = typeSpec.structOrUnionSpecifier();
    if (structSpec) {
      const identifier = structSpec.Identifier();
      return identifier
        ? identifier.getText()
        : DeclaratorUtils.reconstructAnonymousStruct(structSpec);
    }
    const enumSpec = typeSpec.enumSpecifier();
    if (enumSpec) {
      const identifier = enumSpec.Identifier();
      return identifier
        ? `enum ${identifier.getText()}`
        : `enum ${enumSpec.getText().replace(/^enum/, "")}`;
    }
    return typeSpec.getText();
  }
 
  /**
   * The type a declarator records: the base type with any indirection the
   * declarator carries -- a pointer's depth, or a function pointer's
   * `T (*)(params)`. The one rule for a typedef and a struct field (#1760
   * review: a field recorded its specifiers alone, so `float (*readLevel)(void)`
   * was a `float` and `uint8_t *buf` a `uint8_t`).
   *
   * Declaration specifiers give the base type; the `*` of a pointer typedef
   * lives in the *declarator* (`typedef struct Sample *SampleHandle`). Issue
   * #1178: only function-pointer typedefs used to reconstruct their
   * indirection, so a plain pointer typedef was recorded as though it were the
   * struct itself -- and a consumer asking "can the callee write through this
   * parameter?" was told no.
   */
  static declaredType(baseType: string, declarator: DeclaratorContext): string {
    if (DeclaratorUtils.isFunctionPointerDeclarator(declarator)) {
      return `${baseType} (*)(${DeclaratorUtils.extractParamText(declarator)})`;
    }
    // Keep the declarator's pointer depth, not merely its presence: the symbol
    // model is shared, and a consumer that wants the pointer probably wants the
    // right number of them (`typedef struct Sample **Grid`).
    return DeclaratorUtils.pointerType(baseType, declarator);
  }
 
  /**
   * 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
   */
  private static isFunctionPointerDeclarator(
    declarator: DeclaratorContext,
  ): boolean {
    const directDecl = declarator.directDeclarator();
    // The outer directDeclarator has: directDeclarator '(' params ')'
    const hasParams =
      directDecl.parameterTypeList() !== null ||
      directDecl.LeftParen() !== null;
    if (!hasParams) return false;
 
    // The inner directDeclarator should be '(' declarator ')' with a pointer
    const nestedDecl = directDecl.directDeclarator()?.declarator();
    return (nestedDecl?.pointer() ?? null) !== null;
  }
 
  /**
   * Extract parameter text from a function pointer declarator.
   * Returns the text of the parameters from a function pointer like "(*Callback)(Point p)".
   */
  private static extractParamText(declarator: DeclaratorContext): string {
    return declarator.directDeclarator().parameterTypeList()?.getText() ?? "";
  }
 
  /**
   * Whether a declaration is `volatile` (#1760 review). The specifier list is
   * read for its type specifiers alone, so a `volatile float` global was
   * recorded as `float`, and the typer could not know that reading it has a
   * side effect. A struct field's spelling keeps its qualifiers already.
   */
  static isVolatile(declSpecs: DeclarationSpecifiersContext): boolean {
    return declSpecs
      .declarationSpecifier()
      .some((spec) => spec.typeQualifier()?.getText() === "volatile");
  }
 
  /**
   * Check if declaration specifiers contain a specific storage class.
   */
  static hasStorageClass(
    declSpecs: DeclarationSpecifiersContext,
    storage: string,
  ): boolean {
    for (const spec of declSpecs.declarationSpecifier()) {
      const storageSpec = spec.storageClassSpecifier();
      if (storageSpec?.getText() === storage) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Find struct or union specifier in declaration specifiers.
   */
  static findStructOrUnionSpecifier(
    declSpecs: DeclarationSpecifiersContext,
  ): StructOrUnionSpecifierContext | null {
    for (const spec of declSpecs.declarationSpecifier()) {
      const typeSpec = spec.typeSpecifier();
      if (typeSpec) {
        const structSpec = typeSpec.structOrUnionSpecifier?.();
        if (structSpec) {
          return structSpec;
        }
      }
    }
    return null;
  }
 
  /**
   * Find enum specifier in declaration specifiers.
   */
  static findEnumSpecifier(
    declSpecs: DeclarationSpecifiersContext,
  ): EnumSpecifierContext | null {
    for (const spec of declSpecs.declarationSpecifier()) {
      const typeSpec = spec.typeSpecifier();
      if (typeSpec) {
        const enumSpec = typeSpec.enumSpecifier?.();
        if (enumSpec) {
          return enumSpec;
        }
      }
    }
    return null;
  }
 
  /**
   * Extract type from specifierQualifierList (for struct fields).
   * For struct/union field types, extract just the identifier (e.g., "InnerConfig")
   * not the concatenated text ("structInnerConfig").
   */
  static extractTypeFromSpecQualList(specQualList: any): string {
    const parts: string[] = [];
 
    // Traverse the specifierQualifierList
    let current = specQualList;
    while (current) {
      const typeSpec = current.typeSpecifier?.();
      if (typeSpec) {
        parts.push(DeclaratorUtils.typeSpecifierText(typeSpec));
      }
 
      const typeQual = current.typeQualifier?.();
      if (typeQual) {
        parts.push(typeQual.getText());
      }
 
      current = current.specifierQualifierList?.();
    }
 
    return parts.join(" ") || "int";
  }
 
  /**
   * Reconstruct an anonymous struct/union type with proper spacing.
   * For `struct { unsigned int flag_a: 1; }`, returns the properly formatted string
   * instead of the concatenated tokens from getText().
   */
  private static reconstructAnonymousStruct(
    structSpec: StructOrUnionSpecifierContext,
  ): string {
    const structOrUnion = structSpec.structOrUnion();
    const keyword = structOrUnion.Struct() ? "struct" : "union";
 
    const declList = structSpec.structDeclarationList();
    Iif (!declList) {
      return `${keyword} { }`;
    }
 
    const fields = DeclaratorUtils.reconstructStructFields(declList);
    return `${keyword} { ${fields} }`;
  }
 
  /**
   * Reconstruct struct fields with proper spacing.
   */
  private static reconstructStructFields(
    declList: StructDeclarationListContext,
  ): string {
    const fieldStrings: string[] = [];
 
    for (const decl of declList.structDeclaration()) {
      const fieldStr = DeclaratorUtils.reconstructStructField(decl);
      Eif (fieldStr) {
        fieldStrings.push(fieldStr);
      }
    }
 
    return fieldStrings.join(" ");
  }
 
  /**
   * Reconstruct a single struct field declaration.
   */
  private static reconstructStructField(
    decl: StructDeclarationContext,
  ): string | null {
    const specQualList = decl.specifierQualifierList();
    Iif (!specQualList) return null;
 
    // Get the base type with proper spacing
    const baseType = DeclaratorUtils.extractTypeFromSpecQualList(specQualList);
 
    const declaratorList = decl.structDeclaratorList();
    Iif (!declaratorList) {
      return `${baseType};`;
    }
 
    // Process each declarator in the list
    const declarators: string[] = [];
    for (const structDecl of declaratorList.structDeclarator()) {
      const declStr = DeclaratorUtils.reconstructStructDeclarator(structDecl);
      Eif (declStr) {
        declarators.push(declStr);
      }
    }
 
    Iif (declarators.length === 0) {
      return `${baseType};`;
    }
 
    return `${baseType} ${declarators.join(", ")};`;
  }
 
  /**
   * Reconstruct a struct declarator (field name with optional bitfield width).
   */
  private static reconstructStructDeclarator(
    structDecl: StructDeclaratorContext,
  ): string | null {
    const declarator = structDecl.declarator();
    const hasColon = structDecl.Colon() !== null;
    const constExpr = structDecl.constantExpression();
 
    let name = "";
    if (declarator) {
      name = DeclaratorUtils.extractDeclaratorName(declarator) || "";
    }
 
    if (hasColon && constExpr) {
      const width = constExpr.getText();
      return `${name}: ${width}`;
    }
 
    return name || null;
  }
 
  /**
   * Extract typedef name from declaration specifiers.
   * For "typedef struct { ... } AppConfig;", this returns "AppConfig".
   */
  static extractTypedefNameFromSpecs(
    declSpecs: DeclarationSpecifiersContext,
  ): string | undefined {
    for (const spec of declSpecs.declarationSpecifier()) {
      const typeSpec = spec.typeSpecifier();
      if (typeSpec) {
        const typeName = typeSpec.typedefName?.();
        if (typeName) {
          return typeName.getText();
        }
      }
    }
    return undefined;
  }
 
  /**
   * Extract the first declarator name from an init-declarator-list.
   * For "typedef struct _widget_t widget_t;", this returns "widget_t".
   * Used for Issue #948 opaque type detection.
   */
  static extractFirstDeclaratorName(
    initDeclList: InitDeclaratorListContext,
  ): string | undefined {
    const initDeclarators = initDeclList.initDeclarator?.();
    Iif (!initDeclarators || initDeclarators.length === 0) return undefined;
 
    const firstDeclarator = initDeclarators[0].declarator?.();
    Iif (!firstDeclarator) return undefined;
 
    return DeclaratorUtils.extractDeclaratorName(firstDeclarator) ?? undefined;
  }
 
  /**
   * Check if the first declarator in an init-declarator-list has a pointer.
   * For "typedef struct X *handle_t;", the declarator is "*handle_t" which has a pointer.
   * Used for Issue #957 to distinguish pointer typedefs from opaque struct typedefs.
   */
  static firstDeclaratorHasPointer(
    initDeclList: InitDeclaratorListContext,
  ): boolean {
    const initDeclarators = initDeclList.initDeclarator?.();
    Iif (!initDeclarators || initDeclarators.length === 0) return false;
 
    const firstDeclarator = initDeclarators[0].declarator?.();
    Iif (!firstDeclarator) return false;
 
    return Boolean(firstDeclarator.pointer?.());
  }
}
 
export default DeclaratorUtils;