All files / transpiler/logic/symbols/c/utils DeclaratorUtils.ts

90.13% Statements 137/152
77.08% Branches 74/96
100% Functions 18/18
96.37% Lines 133/138

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                                                      110x 110x   110x                   154x 154x 108x       46x 154x 2x         44x 154x 44x                   34x 34x       34x     17x   8x             34x 34x   34x 34x   18x 34x   18x                   22x 22x   9x 9x     9x 22x 22x   22x 9x 9x 9x 9x 9x       9x                             58x 58x     58x                 50x   50x 58x 58x 51x       50x                   200x 285x 285x 37x     163x                 100x 161x 161x 120x 120x 44x       56x                 100x 180x 180x 139x 139x 9x       91x                 60x     60x 60x 66x 66x   65x 65x 4x 4x   1x     3x     61x       66x 66x 1x     66x     60x                     3x 3x   3x 3x       3x 3x                 3x   3x 5x 5x 5x       3x                 5x 5x     5x   5x 5x         5x 5x 5x 5x 5x       5x       5x                 5x 5x 5x   5x 5x 3x     5x 2x 2x     3x                   18x 54x 54x 36x 36x 18x                             1x 1x   1x 1x   1x                     1x 1x   1x 1x   1x          
/**
 * 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,
  StructOrUnionSpecifierContext,
  EnumSpecifierContext,
  StructDeclarationListContext,
  StructDeclarationContext,
  StructDeclaratorContext,
  InitDeclaratorListContext,
} from "../../../parser/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 pointer and array in declarator
    const declarator = paramDecl.declarator?.();
    let isPointer = false;
    let isArray = false;
 
    if (declarator) {
      isPointer = Boolean(declarator.pointer?.());
      const directDecl = declarator.directDeclarator?.();
      Eif (directDecl) {
        const text = directDecl.getText();
        isArray = text.includes("[") && text.includes("]");
      }
    }
 
    return ParameterExtractorUtils.buildParameterInfo(
      declarator,
      baseType,
      isConst,
      isPointer,
      isArray,
      DeclaratorUtils.extractDeclaratorName,
    );
  }
 
  /**
   * 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(typeSpec.getText());
      }
    }
 
    return parts.join(" ") || "int";
  }
 
  /**
   * 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) {
        // Check for struct/union specifier - need to extract just the identifier
        const structSpec = typeSpec.structOrUnionSpecifier?.();
        if (structSpec) {
          const identifier = structSpec.Identifier?.();
          if (identifier) {
            // Use just the struct/union name, not "structName" concatenated
            parts.push(identifier.getText());
          } else {
            // Anonymous struct - reconstruct with proper spacing
            parts.push(DeclaratorUtils.reconstructAnonymousStruct(structSpec));
          }
        } else {
          parts.push(typeSpec.getText());
        }
      }
 
      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;