All files / src/apps/tile-editor expression-parser.ts

83.5% Statements 167/200
61.53% Branches 48/78
100% Functions 22/22
83.5% Lines 167/200

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 2381x 6x 6x 6x   6x 6x 6x 2x 2x 6x 6x   6x   6x 6x 6x         53x 39x 39x 6x   6x 6x 6x 6x     6x 6x   6x 12x 12x 4x 4x 4x   4x 12x 12x   6x 16x 16x 3x 3x 3x         3x 16x 16x   6x 19x     19x   6x 20x 20x 1x 1x 1x 20x 20x   6x 20x 1x 1x 1x 1x   20x 13x 13x   6x 6x 6x 3x 1x 1x   2x 2x 2x 4x 2x 2x 3x 2x 3x 3x 2x 2x   1x         6x                     20x   6x 2x 2x   2x   2x   2x   2x         2x 1x 1x 1x 1x 2x   2x   2x 1x 1x 1x   2x   2x 2x   6x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x   1x 1x   6x 3x 3x   6x 1x 1x   1x   6x 4x 4x 4x   6x 116x 116x   6x 46x 46x   6x 39x 39x 39x   6x 185x 185x   6x 118x 19x 19x 19x 99x 118x   6x 120x 90x 120x   6x 19x 19x 19x   6x 7x 7x 7x 6x  
export class ExpressionParser {
  private pos = 0;
  private tokens: string[] = [];
  private variables: Record<string, number>;
 
  constructor(private expression: string, variables: Record<string, number> = {}) {
    this.variables = {};
    for (const [key, value] of Object.entries(variables)) {
      this.variables[key.toLowerCase()] = value;
    }
    this.tokenize();
  }
 
  private tokenize() {
    // Regex for: functions/words, numbers, operators, parens, comma
    const regex = /([a-z][a-z0-9]*)|([0-9]+(?:\.[0-9]+)?)|(\+|-|\*|\/|\^|\(|\)|,)|(\s+)/gi;
    let match;
    while ((match = regex.exec(this.expression)) !== null) {
      // Group 1: Identifier
      // Group 2: Number
      // Group 3: Operator/Punctuation
      // Group 4: Whitespace (skip)
      if (match[4]) continue;
      this.tokens.push(match[0]);
    }
  }
 
  evaluate(): number {
    this.pos = 0;
    const result = this.parseExpression();
    if (this.pos < this.tokens.length) {
      throw new Error("Unexpected token at end of expression");
    }
    return result;
  }
 
  private parseExpression(): number {
    let left = this.parseTerm();
    while (this.match("+") || this.match("-")) {
      const op = this.previous();
      const right = this.parseTerm();
      if (op === "+") left += right;
      else left -= right;
    }
    return left;
  }
 
  private parseTerm(): number {
    let left = this.parseFactor();
    while (this.match("*") || this.match("/")) {
      const op = this.previous();
      const right = this.parseFactor();
      if (op === "*") left *= right;
      else {
        if (right === 0) throw new Error("Division by zero");
        left /= right;
      }
    }
    return left;
  }
 
  private parseFactor(): number {
    return this.parsePower();
    // Power handles its own precedence usually higher than mul/div.
    // Standard precedence: ^ > * / > + -
  }
 
  private parsePower(): number {
    let left = this.parsePrimary();
    if (this.match("^")) {
      const right = this.parsePower(); // Right associative.
      left = Math.pow(left, right);
    }
    return left;
  }
 
  private parsePrimary(): number {
    if (this.match("(")) {
      const expr = this.parseExpression();
      if (!this.match(")")) throw new Error("Expected ')'");
      return expr;
    }
 
    if (this.isNumber()) {
      return parseFloat(this.advance());
    }
 
    if (this.isIdentifier()) {
      const name = this.advance().toLowerCase();
      if (this.match("(")) {
        if (this.isTrigFunction(name)) {
          return this.parseTrigCall(name);
        }
 
        const args: number[] = [];
        if (!this.check(")")) {
          do {
            args.push(this.parseExpression());
          } while (this.match(","));
        }
        if (!this.match(")")) throw new Error("Expected ')' after arguments");
        return this.callFunction(name, args);
      } else {
        if (Object.prototype.hasOwnProperty.call(this.variables, name)) {
          return this.variables[name];
        }
        // Constants
        if (name === "pi") return Math.PI;
        if (name === "e") return Math.E;
        if (name === "phi") return (1 + Math.sqrt(5)) / 2;
        throw new Error(`Unknown variable or function: ${name}`);
      }
    }
 
    if (this.match("-")) {
      return -this.parsePrimary();
    }
 
    if (this.match("+")) {
      return this.parsePrimary();
    }
 
    throw new Error(`Unexpected token: ${this.peek()}`);
  }
 
  private callFunction(name: string, args: number[]): number {
    switch (name) {
      case "sin":
        return Math.sin(this.checkArgs(name, args, 1));
      case "cos":
        return Math.cos(this.checkArgs(name, args, 1));
      case "tan":
        return Math.tan(this.checkArgs(name, args, 1));
      case "tanh":
        return Math.tanh(this.checkArgs(name, args, 1));
      case "tanh2":
        return Math.atan2(
          this.checkArgs(name, args, 2, 0),
          this.checkArgs(name, args, 2, 1)
        );
      case "pow":
        return Math.pow(
          this.checkArgs(name, args, 2, 0),
          this.checkArgs(name, args, 2, 1)
        );
      case "sqrt":
        return Math.sqrt(this.checkArgs(name, args, 1));
      case "cbrt":
        return Math.cbrt(this.checkArgs(name, args, 1));
      case "log":
        return (
          Math.log(this.checkArgs(name, args, 2, 0)) /
          Math.log(this.checkArgs(name, args, 2, 1))
        );
      default:
        throw new Error(`Unknown function: ${name}`);
    }
  }
 
  private parseTrigCall(name: string): number {
    const angle = this.parseExpression();
    let unit: "rad" | "deg" = "rad";
    if (this.match(",")) {
      if (!this.isIdentifier()) throw new Error(`Expected angle unit for ${name}()`);
      const token = this.advance().toLowerCase();
      unit = this.parseAngleUnit(token);
    }
    if (!this.match(")")) throw new Error("Expected ')' after arguments");
 
    const radians = unit === "deg" ? (angle * Math.PI) / 180 : angle;
    switch (name) {
      case "sin":
        return Math.sin(radians);
      case "cos":
        return Math.cos(radians);
      case "tan":
        return Math.tan(radians);
      default:
        throw new Error(`Unknown trigonometric function: ${name}`);
    }
  }
 
  private isTrigFunction(name: string): boolean {
    return name === "sin" || name === "cos" || name === "tan";
  }
 
  private parseAngleUnit(token: string): "rad" | "deg" {
    if (token === "d" || token === "deg" || token === "degree" || token === "degrees") return "deg";
    if (token === "r" || token === "rad" || token === "radian" || token === "radians") return "rad";
    throw new Error(`Unknown angle unit: ${token}`);
  }
 
  private checkArgs(name: string, args: number[], count: number, index: number = 0): number {
    if (args.length !== count) throw new Error(`Function '${name}' expects ${count} arguments`);
    return args[index];
  }
 
  private peek(): string {
    return this.tokens[this.pos];
  }
 
  private previous(): string {
    return this.tokens[this.pos - 1];
  }
 
  private advance(): string {
    if (!this.isAtEnd()) this.pos++;
    return this.previous();
  }
 
  private isAtEnd(): boolean {
    return this.pos >= this.tokens.length;
  }
 
  private match(expected: string): boolean {
    if (this.check(expected)) {
      this.advance();
      return true;
    }
    return false;
  }
 
  private check(expected: string): boolean {
    if (this.isAtEnd()) return false;
    return this.peek() === expected;
  }
 
  private isNumber(): boolean {
    if (this.isAtEnd()) return false;
    return /^[0-9]+(\.[0-9]+)?$/.test(this.peek());
  }
 
  private isIdentifier(): boolean {
    if (this.isAtEnd()) return false;
    return /^[a-z][a-z0-9]*$/i.test(this.peek());
  }
}