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

78.76% Statements 89/113
64.7% Branches 55/85
100% Functions 16/16
79.27% Lines 88/111

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                                                93x 93x 93x 93x 93x           93x                     139x 139x 93x 93x 93x 93x 93x 93x 91x             48x 139x 45x           3x 139x 1x         2x             38x 38x 38x 38x 14x       24x 38x       24x             27x     27x 27x 27x 27x 27x   27x       27x         27x 27x 13x       14x 27x       14x                     15x 15x       15x 15x     15x 15x     15x           15x                         21x 21x   21x 21x 11x     10x       10x                                                                 17x 17x 17x 17x 1x   16x                         4x 4x 4x                 18x                   19x       22x                       97x   97x 107x 107x 98x 98x 75x 75x 68x           97x                 24x 24x 24x 24x 24x         24x                         24x          
/**
 * 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 SymbolUtils from "../../SymbolUtils";
import type {
  DeclaratorContext,
  DeclSpecifierSeqContext,
  PointerOperatorContext,
} from "../../../2-Parse/cpp/grammar/CPP14Parser";
import IExtractedParameter from "../../shared/IExtractedParameter";
import ParameterExtractorUtils from "../../shared/ParameterExtractorUtils";
 
class DeclaratorUtils {
  /**
   * Extract name from a declarator context.
   */
  static extractDeclaratorName(declarator: any): string | null {
    // Pointer declarator -> noPointerDeclarator
    const ptrDecl = declarator.pointerDeclarator?.();
    Eif (ptrDecl) {
      const noPtr = ptrDecl.noPointerDeclarator?.();
      Eif (noPtr) {
        return DeclaratorUtils.extractNoPointerDeclaratorName(noPtr);
      }
    }
 
    // No pointer declarator
    const noPtr = declarator.noPointerDeclarator?.();
    Iif (noPtr) {
      return DeclaratorUtils.extractNoPointerDeclaratorName(noPtr);
    }
 
    return null;
  }
 
  /**
   * Extract name from a noPointerDeclarator context.
   */
  static 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 DeclaratorUtils.extractNoPointerDeclaratorName(innerNoPtr);
    }
 
    // A parenthesized pointer declarator, `(*readLevel)` in `float (*readLevel)()`: its
    // name is inside it (#1760 review: such a member had no name, so it was
    // dropped)
    const innerPtr = noPtr.pointerDeclarator?.();
    if (innerPtr) {
      return DeclaratorUtils.extractNoPointerDeclaratorName(
        innerPtr.noPointerDeclarator(),
      );
    }
 
    return null;
  }
 
  /**
   * Check if a declarator represents a function.
   */
  static 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;
  }
 
  /**
   * Extract function parameters from a declarator.
   */
  static extractFunctionParameters(declarator: any): IExtractedParameter[] {
    const params: IExtractedParameter[] = [];
 
    // 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;
    }
 
    return ParameterExtractorUtils.processParameterList(
      paramList,
      DeclaratorUtils.extractParameterInfo,
    );
  }
 
  /**
   * Extract parameter info from a single parameter declaration.
   */
  static extractParameterInfo(paramDecl: any): IExtractedParameter | null {
    // Get the type from declSpecifierSeq
    const declSpecSeq = paramDecl.declSpecifierSeq?.();
    Iif (!declSpecSeq) {
      return null;
    }
 
    const baseType = DeclaratorUtils.extractTypeFromDeclSpecSeq(declSpecSeq);
    const isConst = declSpecSeq.getText().includes("const");
 
    // Check for pointer in declarator or abstractDeclarator
    const declarator = paramDecl.declarator?.();
    const abstractDecl = paramDecl.abstractDeclarator?.();
 
    const isPointer =
      (declarator && DeclaratorUtils.declaratorHasPointer(declarator)) ||
      (abstractDecl &&
        DeclaratorUtils.abstractDeclaratorHasPointer(abstractDecl));
 
    // One `*` whatever the declarator spells -- `Dev**` and a reference alike.
    // The C extractor keeps the depth; this one never has.
    return ParameterExtractorUtils.buildParameterInfo(
      declarator,
      isPointer ? `${baseType}*` : baseType,
      isConst,
      false, // isArray - could be enhanced
      DeclaratorUtils.extractDeclaratorName,
    );
  }
 
  /**
   * Check if a declarator contains a pointer operator.
   */
  static 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 *
      Iif (ptrDecl.getText().includes("*")) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Check if an abstract declarator contains a pointer.
   */
  static abstractDeclaratorHasPointer(abstractDecl: any): boolean {
    // Check for pointerAbstractDeclarator
    const ptrAbstract = abstractDecl.pointerAbstractDeclarator?.();
    if (ptrAbstract) {
      const ptrOps = ptrAbstract.pointerOperator?.();
      if (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;
  }
 
  /**
   * The type a data member's declarator records: its base type with the
   * declarator's indirection -- a pointer's depth, or a function pointer's
   * `T (*)(params)` -- the spellings the C side records (#1760 review: a
   * member recorded its specifiers alone, so `uint8_t *buf` was a `uint8_t`
   * and `float (*readLevel)()` a `float`). A reference keeps its base type.
   */
  static declaredType(baseType: string, declarator: DeclaratorContext): string {
    const pointer = declarator.pointerDeclarator();
    Iif (!pointer) return baseType;
    const params = pointer.noPointerDeclarator().parametersAndQualifiers();
    if (params && DeclaratorUtils.isFunctionPointer(declarator)) {
      return `${baseType} (*)(${params.getText().slice(1, -1)})`;
    }
    return (
      baseType +
      "*".repeat(DeclaratorUtils.starCount(pointer.pointerOperator()))
    );
  }
 
  /**
   * Whether a declarator declares a pointer to a function, `(*readLevel)()`: its
   * parameters apply to a parenthesized pointer declarator, where a
   * function's apply to its name. A class's member of this shape is a data
   * member (#1760 review: it was taken for a member function and dropped).
   */
  static isFunctionPointer(declarator: DeclaratorContext): boolean {
    const outer = declarator.pointerDeclarator()?.noPointerDeclarator();
    const inner = outer?.noPointerDeclarator()?.pointerDeclarator();
    return (
      outer?.parametersAndQualifiers() != null &&
      inner != null &&
      DeclaratorUtils.starCount(inner.pointerOperator()) > 0
    );
  }
 
  /** How many of a declarator's pointer operators are `*`, not `&` */
  private static starCount(operators: PointerOperatorContext[]): number {
    return operators.filter((op) => op.getText().startsWith("*")).length;
  }
 
  /**
   * Whether a declaration is `volatile` (#1760 review): the type string below
   * keeps simple type specifiers alone, so a `volatile float` variable was
   * recorded as `float`, and the typer could not know that reading it has a
   * side effect.
   */
  static isVolatile(declSpecSeq: DeclSpecifierSeqContext): boolean {
    return declSpecSeq
      .declSpecifier()
      .some(
        (spec) =>
          spec
            .typeSpecifier()
            ?.trailingTypeSpecifier()
            ?.cvQualifier()
            ?.getText() === "volatile",
      );
  }
 
  /**
   * Extract type string from a declSpecifierSeq context.
   */
  static 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";
  }
 
  /**
   * Extract array dimensions from a declarator.
   * Issue #981: Returns (number | string)[] to support macro-sized arrays.
   */
  static extractArrayDimensions(declarator: any): (number | string)[] {
    // 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 DeclaratorUtils.extractArrayDimensionsFromNoPtr(noPtr);
      }
    }
 
    const noPtr = declarator.noPointerDeclarator?.();
    Iif (noPtr) {
      return DeclaratorUtils.extractArrayDimensionsFromNoPtr(noPtr);
    }
 
    return [];
  }
 
  /**
   * Extract array dimensions from a noPointerDeclarator.
   * Issue #981: Returns (number | string)[] to support macro-sized arrays.
   */
  static extractArrayDimensionsFromNoPtr(noPtr: any): (number | string)[] {
    // Use shared utility for regex-based extraction
    return SymbolUtils.parseArrayDimensions(noPtr.getText());
  }
}
 
export default DeclaratorUtils;