All files / metadata/src/safeFunctions/expression tokenizer.ts

41.93% Statements 52/124
39.47% Branches 30/76
57.14% Functions 4/7
40% Lines 48/120

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                                  137x                                                       44936x 286330x 52334x                                                                                                                                                                                                                     7946x 7946x   7946x 69870x   69870x 21920x 21920x     47950x 548x 548x 548x         548x                         548x 548x 548x     548x 548x 548x     47402x 2466x 2466x 2466x 27126x         27126x 27126x     2466x           2466x 2466x 2466x     44936x             44936x 26578x 26578x 265506x   26578x 26578x 26578x     18358x 286878x 18358x 18358x 18358x             7946x 7946x    
/**
 * Tokenizer for the safe function expression language. See
 * `compileExpression` for the grammar.
 */
 
export type Token =
  | { kind: 'number'; value: number }
  | { kind: 'string'; value: string }
  | { kind: 'template'; parts: TemplatePart[] }
  | { kind: 'ident'; name: string }
  | { kind: 'punct'; value: string }
  | { kind: 'end' };
 
export type TemplatePart =
  | { kind: 'text'; text: string }
  | { kind: 'expr'; source: string };
 
const PUNCTUATORS = [
  // Longest first so multi-character operators win.
  '===',
  '!==',
  '==',
  '!=',
  '<=',
  '>=',
  '&&',
  '||',
  '<',
  '>',
  '+',
  '-',
  '*',
  '/',
  '%',
  '!',
  '(',
  ')',
  '[',
  ']',
  ',',
  '.',
  '?',
  ':',
];
 
const isIdentStart = (ch: string) => /[A-Za-z_$]/.test(ch);
const isIdentPart = (ch: string) => /[A-Za-z0-9_$]/.test(ch);
const isDigit = (ch: string) => ch >= '0' && ch <= '9';
 
export class ExpressionSyntaxError extends Error {
  constructor(message: string, expression: string) {
    super(`${message} in expression: ${expression}`);
    this.name = 'ExpressionSyntaxError';
  }
}
 
function readEscape(
  source: string,
  index: number
): { ch: string; next: number } {
  const escaped = source[index];
  const map = {
    n: '\n',
    t: '\t',
    r: '\r',
    '\\': '\\',
    "'": "'",
    '"': '"',
    '`': '`',
    $: '$',
  };
  return { ch: map[escaped] ?? escaped, next: index + 1 };
}
 
/**
 * Reads a template literal body starting after the opening backtick.
 * Returns the parts (literal text and raw `${...}` expression sources) and
 * the index just after the closing backtick.
 */
function readTemplate(
  source: string,
  start: number,
  expression: string
): { parts: TemplatePart[]; next: number } {
  const parts: TemplatePart[] = [];
  let text = '';
  let i = start;
  while (i < source.length) {
    const ch = source[i];
    if (ch === '`') {
      if (text) {
        parts.push({ kind: 'text', text });
      }
      return { parts, next: i + 1 };
    }
    if (ch === '\\') {
      const { ch: escaped, next } = readEscape(source, i + 1);
      text += escaped;
      i = next;
      continue;
    }
    if (ch === '$' && source[i + 1] === '{') {
      if (text) {
        parts.push({ kind: 'text', text });
        text = '';
      }
      // Find the matching close brace, tracking nesting from strings.
      let depth = 1;
      let j = i + 2;
      let exprSource = '';
      while (j < source.length && depth > 0) {
        const c = source[j];
        if (c === '{') {
          depth++;
        } else if (c === '}') {
          depth--;
          if (depth === 0) {
            break;
          }
        } else if (c === "'" || c === '"') {
          // Skip string contents inside the interpolation.
          const quote = c;
          exprSource += c;
          j++;
          while (j < source.length && source[j] !== quote) {
            if (source[j] === '\\') {
              exprSource += source[j];
              j++;
            }
            exprSource += source[j];
            j++;
          }
        }
        exprSource += source[j];
        j++;
      }
      if (depth !== 0) {
        throw new ExpressionSyntaxError(
          'Unterminated template interpolation',
          expression
        );
      }
      parts.push({ kind: 'expr', source: exprSource });
      i = j + 1;
      continue;
    }
    text += ch;
    i++;
  }
  throw new ExpressionSyntaxError('Unterminated template literal', expression);
}
 
/** Converts an expression source string into a token list. */
export function tokenize(source: string, expression = source): Token[] {
  const tokens: Token[] = [];
  let i = 0;
 
  outer: while (i < source.length) {
    const ch = source[i];
 
    if (/\s/.test(ch)) {
      i++;
      continue;
    }
 
    if (isDigit(ch) || (ch === '.' && isDigit(source[i + 1]))) {
      let j = i;
      while (j < source.length && /[0-9.]/.test(source[j])) {
        j++;
      }
      // Exponent notation: consume `e`/`E` with an optional sign only when at
      // least one digit follows, so `1e5` and `2.5E-3` are numbers while the
      // `e` of an identifier like `1 e` is left to the identifier scanner.
      Iif (source[j] === 'e' || source[j] === 'E') {
        let k = j + 1;
        if (source[k] === '+' || source[k] === '-') {
          k++;
        }
        if (isDigit(source[k])) {
          k++;
          while (k < source.length && isDigit(source[k])) {
            k++;
          }
          j = k;
        }
      }
      const raw = source.slice(i, j);
      const value = Number(raw);
      Iif (Number.isNaN(value)) {
        throw new ExpressionSyntaxError(`Invalid number '${raw}'`, expression);
      }
      tokens.push({ kind: 'number', value });
      i = j;
      continue;
    }
 
    if (ch === "'" || ch === '"') {
      let value = '';
      let j = i + 1;
      while (j < source.length && source[j] !== ch) {
        Iif (source[j] === '\\') {
          const { ch: escaped, next } = readEscape(source, j + 1);
          value += escaped;
          j = next;
        } else {
          value += source[j];
          j++;
        }
      }
      Iif (j >= source.length) {
        throw new ExpressionSyntaxError(
          'Unterminated string literal',
          expression
        );
      }
      tokens.push({ kind: 'string', value });
      i = j + 1;
      continue;
    }
 
    Iif (ch === '`') {
      const { parts, next } = readTemplate(source, i + 1, expression);
      tokens.push({ kind: 'template', parts });
      i = next;
      continue;
    }
 
    if (isIdentStart(ch)) {
      let j = i + 1;
      while (j < source.length && isIdentPart(source[j])) {
        j++;
      }
      tokens.push({ kind: 'ident', name: source.slice(i, j) });
      i = j;
      continue;
    }
 
    for (const punct of PUNCTUATORS) {
      if (source.startsWith(punct, i)) {
        tokens.push({ kind: 'punct', value: punct });
        i += punct.length;
        continue outer;
      }
    }
 
    throw new ExpressionSyntaxError(`Unexpected character '${ch}'`, expression);
  }
 
  tokens.push({ kind: 'end' });
  return tokens;
}