All files / src/excellent tokenizer.ts

93.42% Statements 412/441
91.73% Branches 111/121
100% Functions 7/7
93.42% Lines 412/441

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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 538x 161x 159x 159x 109x 109x 109x 109x 109x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 45x 45x 45x 45x 45x 3x 3x 3x 3x 3x 3x 3x 42x 42x 42x 45x 4x 4x 45x 18x 18x 18x 18x 18x 18x 18x 24x 24x 24x 24x 24x 24x 24x 45x 35x 35x 178x 178x 178x 178x 6x 6x 6x 123x 123x     123x   123x 6x 6x 123x 117x 117x 123x 6x 6x 6x 6x 6x 6x 6x 172x 172x 178x 25x 25x 28x 28x 25x 25x 14x 1x 1x 25x 1x 1x 2x 2x 1x 25x 25x 25x 25x 25x 25x 25x 147x 147x 178x 45x 45x 45x 377x 45x 338x 338x 338x 14x 338x     338x 338x 45x 45x 45x 102x 102x 178x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 83x 166x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 64x 64x 178x 6x 6x 6x 6x 6x 6x 6x 6x 58x 58x 178x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 57x 162x 56x 55x 178x 2x 2x 2x 2x 2x 2x 2x 2x 55x 55x 162x 13x 13x 13x 13x 13x 13x 13x 13x 42x 42x 162x 5x 5x 5x 5x 5x 5x 5x 5x 37x 37x 178x 37x 37x 37x 74x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x                   35x 35x 35x 109x 109x 109x 109x 109x 109x 109x 758x 49x 49x 709x 709x 709x 709x 709x 753x 164x 164x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x                               33x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 34x 34x 34x 34x 34x 34x 34x 34x 35x 35x 35x 1x 1x 164x 129x 129x 129x 129x 129x 129x 129x 164x 164x 164x 709x 709x 733x 570x 570x 570x 571x 571x 570x 570x 570x 570x 570x 570x 570x 570x 570x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 570x 709x 709x 709x 109x 109x 109x 109x 109x 1x 1x 1x 6x 3x 1x 1x 3x 6x 1x  
import ExcellentParser from './ExcellentParser';
 
export enum TokenType {
  Text = 'text',
  ExpressionPrefix = 'prefix',
  Identifier = 'identifier',
  Paren = 'paren',
  Operator = 'operator',
  FunctionName = 'fn',
  StringLiteral = 'string',
  NumberLiteral = 'number',
  Keyword = 'keyword',
  ContextRef = 'context-ref',
  Separator = 'separator',
  Whitespace = 'ws',
  Arrow = 'arrow',
  Bracket = 'bracket',
  EscapedAt = 'escaped-at'
}
 
export interface Token {
  type: TokenType;
  text: string;
  start: number;
  depth?: number;
  balanced?: boolean;
}
 
const KEYWORDS = new Set(['true', 'false', 'null']);
const SINGLE_OPERATORS = new Set(['+', '-', '*', '/', '^', '&', '=', '<', '>']);
const isDigit = (ch: string): boolean => ch >= '0' && ch <= '9';
const isWordChar = (ch: string): boolean =>
  (ch >= 'a' && ch <= 'z') ||
  (ch >= 'A' && ch <= 'Z') ||
  (ch >= '0' && ch <= '9') ||
  ch === '_';
 
/**
 * Tokenizes the interior of a parenthesized expression (everything after the opening @().
 * The body string should NOT include the leading @ or the outer parentheses.
 */
function tokenizeExpressionBody(
  body: string,
  baseOffset: number,
  initialDepth: number
): Token[] {
  const tokens: Token[] = [];
  let pos = 0;
  let depth = initialDepth;
 
  const peek = (offset = 0): string | undefined => body[pos + offset];
 
  const flushIdentifier = (start: number, end: number): void => {
    const text = body.substring(start, end);
    const absStart = baseOffset + start;
 
    // check if keyword
    if (KEYWORDS.has(text.toLowerCase())) {
      tokens.push({
        type: TokenType.Keyword,
        text,
        start: absStart
      });
      return;
    }
 
    // check if followed by ( → function name
    let lookAhead = end;
    while (lookAhead < body.length && body[lookAhead] === ' ') {
      lookAhead++;
    }
    if (lookAhead < body.length && body[lookAhead] === '(') {
      tokens.push({
        type: TokenType.FunctionName,
        text,
        start: absStart
      });
      return;
    }
 
    // otherwise context reference
    tokens.push({
      type: TokenType.ContextRef,
      text,
      start: absStart
    });
  };
 
  while (pos < body.length) {
    const ch = body[pos];
 
    // string literal
    if (ch === '"') {
      const start = pos;
      pos++; // skip opening quote
      while (pos < body.length) {
        if (
          body[pos] === '\\' &&
          pos + 1 < body.length &&
          body[pos + 1] === '"'
        ) {
          pos += 2; // skip escaped quote
        } else if (body[pos] === '"') {
          pos++; // skip closing quote
          break;
        } else {
          pos++;
        }
      }
      tokens.push({
        type: TokenType.StringLiteral,
        text: body.substring(start, pos),
        start: baseOffset + start
      });
      continue;
    }
 
    // number literal
    if (isDigit(ch) || (ch === '.' && peek(1) && isDigit(peek(1)))) {
      const start = pos;
      while (pos < body.length && isDigit(body[pos])) {
        pos++;
      }
      if (
        pos < body.length &&
        body[pos] === '.' &&
        pos + 1 < body.length &&
        isDigit(body[pos + 1])
      ) {
        pos++; // skip decimal point
        while (pos < body.length && isDigit(body[pos])) {
          pos++;
        }
      }
      tokens.push({
        type: TokenType.NumberLiteral,
        text: body.substring(start, pos),
        start: baseOffset + start
      });
      continue;
    }
 
    // identifier (word chars and dots)
    if (isWordChar(ch) && !isDigit(ch)) {
      const start = pos;
      while (
        pos < body.length &&
        (isWordChar(body[pos]) || body[pos] === '.')
      ) {
        // don't end on a trailing dot
        if (
          body[pos] === '.' &&
          (pos + 1 >= body.length || !isWordChar(body[pos + 1]))
        ) {
          break;
        }
        pos++;
      }
      flushIdentifier(start, pos);
      continue;
    }
 
    // parentheses
    if (ch === '(') {
      tokens.push({
        type: TokenType.Paren,
        text: '(',
        start: baseOffset + pos,
        depth,
        balanced: true // will be corrected later if needed
      });
      depth++;
      pos++;
      continue;
    }
 
    if (ch === ')') {
      depth--;
      tokens.push({
        type: TokenType.Paren,
        text: ')',
        start: baseOffset + pos,
        depth: Math.max(0, depth),
        balanced: true
      });
      pos++;
      continue;
    }
 
    // brackets
    if (ch === '[' || ch === ']') {
      tokens.push({
        type: TokenType.Bracket,
        text: ch,
        start: baseOffset + pos
      });
      pos++;
      continue;
    }
 
    // arrow =>
    if (ch === '=' && peek(1) === '>') {
      tokens.push({
        type: TokenType.Arrow,
        text: '=>',
        start: baseOffset + pos
      });
      pos += 2;
      continue;
    }
 
    // two-char operators: !=, <=, >=
    if (
      (ch === '!' && peek(1) === '=') ||
      (ch === '<' && peek(1) === '=') ||
      (ch === '>' && peek(1) === '=')
    ) {
      tokens.push({
        type: TokenType.Operator,
        text: ch + peek(1),
        start: baseOffset + pos
      });
      pos += 2;
      continue;
    }
 
    // single-char operators
    if (SINGLE_OPERATORS.has(ch)) {
      tokens.push({
        type: TokenType.Operator,
        text: ch,
        start: baseOffset + pos
      });
      pos++;
      continue;
    }
 
    // comma separator
    if (ch === ',') {
      tokens.push({
        type: TokenType.Separator,
        text: ',',
        start: baseOffset + pos
      });
      pos++;
      continue;
    }
 
    // whitespace
    if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
      const start = pos;
      while (
        pos < body.length &&
        (body[pos] === ' ' ||
          body[pos] === '\t' ||
          body[pos] === '\n' ||
          body[pos] === '\r')
      ) {
        pos++;
      }
      tokens.push({
        type: TokenType.Whitespace,
        text: body.substring(start, pos),
        start: baseOffset + start
      });
      continue;
    }

    // unknown character - emit as text
    tokens.push({
      type: TokenType.Text,
      text: ch,
      start: baseOffset + pos
    });
    pos++;
  }
 
  return tokens;
}
 
/**
 * Tokenizes text containing Excellent expressions into a stream of typed tokens.
 * Uses ExcellentParser.findExpressions() to find expression boundaries, then
 * tokenizes expression interiors.
 */
export function tokenize(text: string, parser: ExcellentParser): Token[] {
  if (!text) {
    return [];
  }
 
  const expressions = parser.findExpressions(text);
  const tokens: Token[] = [];
  let lastEnd = 0;
 
  for (const expr of expressions) {
    // emit plain text before this expression
    if (expr.start > lastEnd) {
      const plainText = text.substring(lastEnd, expr.start);
      // check for escaped @@ in plain text
      let plainPos = 0;
      while (plainPos < plainText.length) {
        const atIdx = plainText.indexOf('@@', plainPos);
        if (atIdx === -1) {
          if (plainPos < plainText.length) {
            tokens.push({
              type: TokenType.Text,
              text: plainText.substring(plainPos),
              start: lastEnd + plainPos
            });
          }
          break;
        }
        // text before @@
        if (atIdx > plainPos) {
          tokens.push({
            type: TokenType.Text,
            text: plainText.substring(plainPos, atIdx),
            start: lastEnd + plainPos
          });
        }
        tokens.push({
          type: TokenType.EscapedAt,
          text: '@@',
          start: lastEnd + atIdx
        });
        plainPos = atIdx + 2;
      }
    }
 
    // emit expression tokens
    const exprText = expr.text;
 
    // emit the @ prefix
    tokens.push({
      type: TokenType.ExpressionPrefix,
      text: '@',
      start: expr.start
    });
 
    if (exprText.length > 1 && exprText[1] === '(') {
      // parenthesized expression: @(...)
      // emit the outer opening paren
      tokens.push({
        type: TokenType.Paren,
        text: '(',
        start: expr.start + 1,
        depth: 0,
        balanced: expr.closed
      });
 
      // determine if there's a closing paren
      const hasClosingParen =
        expr.closed && exprText[exprText.length - 1] === ')';
      const bodyEnd = hasClosingParen ? exprText.length - 1 : exprText.length;
      const body = exprText.substring(2, bodyEnd);
 
      if (body.length > 0) {
        const bodyTokens = tokenizeExpressionBody(
          body,
          expr.start + 2,
          1 // depth starts at 1 (inside the outer parens)
        );
        tokens.push(...bodyTokens);
      }
 
      // emit the outer closing paren if present
      if (hasClosingParen) {
        tokens.push({
          type: TokenType.Paren,
          text: ')',
          start: expr.start + exprText.length - 1,
          depth: 0,
          balanced: true
        });
      }
 
      // mark unbalanced parens if expression is not closed
      if (!expr.closed) {
        markUnbalancedParens(tokens, expr.start);
      }
    } else {
      // identifier expression: @contact.name
      tokens.push({
        type: TokenType.Identifier,
        text: exprText.substring(1),
        start: expr.start + 1
      });
    }
 
    lastEnd = expr.end;
  }
 
  // emit remaining plain text
  if (lastEnd < text.length) {
    const remaining = text.substring(lastEnd);
    let plainPos = 0;
    while (plainPos < remaining.length) {
      const atIdx = remaining.indexOf('@@', plainPos);
      if (atIdx === -1) {
        if (plainPos < remaining.length) {
          tokens.push({
            type: TokenType.Text,
            text: remaining.substring(plainPos),
            start: lastEnd + plainPos
          });
        }
        break;
      }
      if (atIdx > plainPos) {
        tokens.push({
          type: TokenType.Text,
          text: remaining.substring(plainPos, atIdx),
          start: lastEnd + plainPos
        });
      }
      tokens.push({
        type: TokenType.EscapedAt,
        text: '@@',
        start: lastEnd + atIdx
      });
      plainPos = atIdx + 2;
    }
  }
 
  return tokens;
}
 
/**
 * Marks paren tokens as unbalanced when the expression is not closed.
 * The outermost opening paren that doesn't have a matching close is marked.
 */
function markUnbalancedParens(tokens: Token[], exprStart: number): void {
  // find all paren tokens belonging to this expression
  for (const token of tokens) {
    if (token.type === TokenType.Paren && token.start >= exprStart) {
      if (token.text === '(' && token.depth === 0) {
        token.balanced = false;
      }
    }
  }
}