All files / transpiler/output/codegen/helpers BaseIdentifierBuilder.ts

100% Statements 8/8
100% Branches 6/6
100% Functions 1/1
100% Lines 8/8

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                                                                84x   84x   6x     78x 15x 2x     13x       63x          
/**
 * Base Identifier Builder
 *
 * Builds the base identifier string for assignment targets,
 * handling global., this., and bare identifier prefixes.
 *
 * Extracted from CodeGenerator.doGenerateAssignmentTarget to reduce
 * cognitive complexity.
 */
 
import IBaseIdentifierResult from "../types/IBaseIdentifierResult";
 
/**
 * Static utility for building base identifiers
 */
class BaseIdentifierBuilder {
  /**
   * Build the base identifier with appropriate prefix
   *
   * @param identifier The raw identifier
   * @param hasGlobal Whether global. prefix is present
   * @param hasThis Whether this. prefix is present
   * @param currentScope The current scope name (required if hasThis)
   * @returns The built identifier and first ID
   * @throws Error if this. is used outside a scope
   */
  static build(
    identifier: string,
    hasGlobal: boolean,
    hasThis: boolean,
    currentScope: string | null,
  ): IBaseIdentifierResult {
    const firstId = identifier;
 
    if (hasGlobal) {
      // global.x - no prefix needed for code generation
      return { result: firstId, firstId };
    }
 
    if (hasThis) {
      if (!currentScope) {
        throw new Error("Error: 'this' can only be used inside a scope");
      }
      // this.x - prefix with current scope
      return { result: `${currentScope}_${firstId}`, firstId };
    }
 
    // Bare identifier with postfix ops
    return { result: firstId, firstId };
  }
}
 
export default BaseIdentifierBuilder;