All files / transpiler/logic/symbols/cnext/utils ExpressionEvaluator.ts

87.5% Statements 7/8
90% Branches 9/10
100% Functions 1/1
87.5% Lines 7/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                                      28x 3x       25x 4x       21x 21x       21x          
/**
 * ExpressionEvaluator - Evaluates constant expressions for symbol collection.
 * Handles hex, binary, and decimal integer literals.
 */
 
class ExpressionEvaluator {
  /**
   * Evaluate a constant expression string to a number.
   * Supports:
   * - Hexadecimal: 0x1F, 0X1F
   * - Binary: 0b1010, 0B1010
   * - Decimal: 42, -10
   *
   * @param expr The expression string
   * @returns The numeric value
   * @throws Error if the expression is invalid
   */
  static evaluateConstant(expr: string): number {
    // Handle hex literals
    if (expr.startsWith("0x") || expr.startsWith("0X")) {
      return Number.parseInt(expr, 16);
    }
 
    // Handle binary literals
    if (expr.startsWith("0b") || expr.startsWith("0B")) {
      return Number.parseInt(expr.substring(2), 2);
    }
 
    // Handle decimal
    const value = Number.parseInt(expr, 10);
    Iif (Number.isNaN(value)) {
      throw new TypeError(`Invalid constant expression: ${expr}`);
    }
 
    return value;
  }
}
 
export default ExpressionEvaluator;