All files / src/shared/lib/rpn tokenizer.ts

97.67% Statements 84/86
96.42% Branches 54/56
100% Functions 8/8
97.67% Lines 84/86

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 217122x                   122x                   122x   122x         139x 139x     139x     122x       116x 116x 87x           29x 29x 29x 883x 3x 880x 31x   883x   29x 1x     28x 28x 1x     27x             122x     129x 129x   129x 380x 116x 114x       114x 114x   264x 23x 23x 23x 23x     241x 1928x   241x 1x 1x 1x     240x 155x 155x 155x     85x 85x           432x     54x   85x 85x     127x     122x 129x   378x 71x         307x 14x         293x 30x       263x 28x       235x 5x       230x 93x         137x 137x 114x               23x 23x                 127x   378x 14x 2x             12x 12x         4x               372x         122x  
import {
  isConstant,
  isFunctionSymbol,
  isNumeric,
  isOperatorSymbol,
  isVariable,
  toNumber,
} from "./helpers";
import { Token } from "./types";
 
const multiCharacterOperators = [
  "<<",
  ">>",
  "==",
  "!=",
  ">=",
  "<=",
  "&&",
  "||",
];
const singleCharacterTokens = new Set("+-*/^%&|~!(),<>");
 
const readDelimitedToken = (
  input: string,
  offset: number,
  delimiter: "$" | "@",
): number => {
  const end = input.indexOf(delimiter, offset + 1);
  Iif (end === -1) {
    throw new Error(`Unterminated ${delimiter} token`);
  }
  return end + 1;
};
 
const readVariableToken = (
  input: string,
  offset: number,
): { token: string; end: number; indexExpression?: string } => {
  const symbolEnd = readDelimitedToken(input, offset, "$");
  if (input[symbolEnd] !== "[") {
    return {
      token: input.slice(offset, symbolEnd),
      end: symbolEnd,
    };
  }
 
  let depth = 1;
  let cursor = symbolEnd + 1;
  while (cursor < input.length && depth > 0) {
    if (input[cursor] === "[") {
      depth++;
    } else if (input[cursor] === "]") {
      depth--;
    }
    cursor++;
  }
  if (depth !== 0) {
    throw new Error("Unterminated array index");
  }
 
  const indexExpression = input.slice(symbolEnd + 1, cursor - 1);
  if (!indexExpression) {
    throw new Error("Array index cannot be empty");
  }
 
  return {
    token: input.slice(offset, cursor),
    end: cursor,
    indexExpression,
  };
};
 
const splitTokens = (
  input: string,
): Array<{ token: string; indexExpression?: string }> => {
  const tokens: Array<{ token: string; indexExpression?: string }> = [];
  let offset = 0;
 
  while (offset < input.length) {
    if (input[offset] === "$") {
      const variable = readVariableToken(input, offset);
      tokens.push({
        token: variable.token,
        indexExpression: variable.indexExpression,
      });
      offset = variable.end;
      continue;
    }
    if (input[offset] === "@") {
      const end = readDelimitedToken(input, offset, "@");
      tokens.push({ token: input.slice(offset, end) });
      offset = end;
      continue;
    }
 
    const multiCharacterOperator = multiCharacterOperators.find((operator) =>
      input.startsWith(operator, offset),
    );
    if (multiCharacterOperator) {
      tokens.push({ token: multiCharacterOperator });
      offset += multiCharacterOperator.length;
      continue;
    }
 
    if (singleCharacterTokens.has(input[offset])) {
      tokens.push({ token: input[offset] });
      offset++;
      continue;
    }
 
    let end = offset + 1;
    while (
      end < input.length &&
      input[end] !== "$" &&
      input[end] !== "@" &&
      !singleCharacterTokens.has(input[end]) &&
      !multiCharacterOperators.some((operator) =>
        input.startsWith(operator, end),
      )
    ) {
      end++;
    }
    tokens.push({ token: input.slice(offset, end) });
    offset = end;
  }
 
  return tokens;
};
 
const tokenizer = (input: string): Token[] => {
  const tokens = splitTokens(input.replace(/\s+/g, "")).map(
    ({ token, indexExpression }): Token => {
      if (isNumeric(token)) {
        return {
          type: "VAL",
          value: toNumber(token),
        };
      }
      if (isFunctionSymbol(token)) {
        return {
          type: "FUN",
          function: token,
        };
      }
      if (token === "(") {
        return {
          type: "LBRACE",
        };
      }
      if (token === ")") {
        return {
          type: "RBRACE",
        };
      }
      if (token === ",") {
        return {
          type: "SEPERATOR",
        };
      }
      if (isOperatorSymbol(token)) {
        return {
          type: "OP",
          operator: token,
        };
      }
      const variableSymbol = token.replace(/\[.*\]$/s, "");
      if (isVariable(variableSymbol)) {
        return {
          type: "VAR",
          symbol: variableSymbol,
          ...(indexExpression !== undefined && {
            index: tokenizer(indexExpression),
          }),
        };
      }
      Eif (isConstant(token)) {
        return {
          type: "CONST",
          symbol: token.replaceAll(/@/g, ""),
        };
      }
      throw new Error(`Unexpected token ${token}`);
    },
  );
 
  return tokens
    .map((token, i): Token[] => {
      if (token.type === "OP" && token.operator === "-") {
        if (i === 0) {
          return [
            {
              type: "OP",
              operator: "neg",
            },
          ];
        }
        const previous = tokens[i - 1];
        if (
          previous.type === "LBRACE" ||
          previous.type === "SEPERATOR" ||
          previous.type === "OP"
        ) {
          return [
            {
              type: "OP",
              operator: "neg",
            },
          ];
        }
      }
      return [token];
    })
    .flat();
};
 
export default tokenizer;