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

79.83% Statements 99/124
79.77% Branches 71/89
82.35% Functions 14/17
79.83% Lines 99/124

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                                                                                                    137x                   137x   137x                 137x                                       137x     137x                     1644x               1096x   548x         7946x       7946x 7946x       159468x       47950x       96448x 96448x                 3014x     3014x               7946x 7946x     7946x         4110x       12056x 12056x 12056x                   22194x   22194x 32332x   32332x 9042x 23290x 4384x   32332x 18906x   13426x 13426x 3288x   10138x 10138x 10138x               22742x 22742x       548x 548x           22194x       22194x   22194x 28222x 4384x 4384x 4384x     4384x     4384x 4384x   23838x             23838x 1644x 1644x       1644x     1644x 1644x 1644x 1096x 1096x 1096x       1096x     1644x 1644x     1644x   22194x         22194x   22194x 548x   21646x 2466x   19180x                         19180x 17810x 1096x   16714x     16714x     16714x   1370x 1370x 822x 822x 822x   548x 548x 548x 548x 2192x 2192x 1644x 1644x   548x     548x 548x                       7946x    
import { ExpressionSyntaxError, tokenize } from './tokenizer';
import type { Token } from './tokenizer';
 
/**
 * AST for the safe function expression language.  Deliberately small:
 * no assignment, no arbitrary function values, no `new`, no property calls.
 */
export type ExpressionNode =
  | { type: 'literal'; value: unknown }
  | { type: 'identifier'; name: string }
  | { type: 'member'; object: ExpressionNode; property: string }
  | { type: 'index'; object: ExpressionNode; index: ExpressionNode }
  | {
      type: 'call';
      callee: string;
      args: ExpressionNode[];
      /** The receiver of an aggregate: `series` in `series.instances.max(x)`. */
      receiver?: string;
    }
  | { type: 'unary'; operator: '!' | '-' | '+'; argument: ExpressionNode }
  | {
      type: 'binary';
      operator: string;
      left: ExpressionNode;
      right: ExpressionNode;
    }
  | {
      type: 'logical';
      operator: '&&' | '||';
      left: ExpressionNode;
      right: ExpressionNode;
    }
  | {
      type: 'conditional';
      test: ExpressionNode;
      consequent: ExpressionNode;
      alternate: ExpressionNode;
    }
  | { type: 'array'; elements: ExpressionNode[] }
  | {
      type: 'template';
      parts: Array<
        { kind: 'text'; text: string } | { kind: 'expr'; node: ExpressionNode }
      >;
    };
 
/**
 * Property names that may never be accessed — they walk the prototype chain
 * and would break out of the data sandbox.
 */
export const FORBIDDEN_PROPERTIES = new Set([
  '__proto__',
  'prototype',
  'constructor',
]);
 
/**
 * The literal `defined`: an operand of `==` and `!=` only. `X == defined` holds
 * when `X` has a value (present and not empty).
 */
export const DEFINED_LITERAL: unique symbol = Symbol('defined');
 
const KEYWORD_LITERALS = new Map<string, unknown>([
  ['true', true],
  ['false', false],
  ['null', null],
  ['undefined', undefined],
  ['defined', DEFINED_LITERAL],
]);
 
/** Binary operator precedence (higher binds tighter). */
const BINARY_PRECEDENCE: Record<string, number> = {
  '||': 1,
  '&&': 2,
  '==': 3,
  '!=': 3,
  '===': 3,
  '!==': 3,
  '<': 4,
  '<=': 4,
  '>': 4,
  '>=': 4,
  in: 4,
  '+': 5,
  '-': 5,
  '*': 6,
  '/': 6,
  '%': 6,
};
 
/** The aggregates that a receiver can call: `series.instances.max(x)`. */
export const AGGREGATE_NAMES = new Set(['min', 'max', 'sum', 'count']);
 
/** The receivers of an aggregate. */
export const AGGREGATE_RECEIVERS = new Set([
  'series',
  'displaySet',
  'displaySets',
]);
 
/**
 * The receiver of `<receiver>.instances.<aggregate>`, or `undefined`. Only
 * these four names on these receivers can be called as a method.
 */
function aggregateReceiver(node: ExpressionNode): string | undefined {
  if (
    node.type === 'member' &&
    AGGREGATE_NAMES.has(node.property) &&
    node.object.type === 'member' &&
    node.object.property === 'instances' &&
    node.object.object.type === 'identifier' &&
    AGGREGATE_RECEIVERS.has(node.object.object.name)
  ) {
    return node.object.object.name;
  }
  return undefined;
}
 
class Parser {
  private tokens: Token[];
  private position = 0;
  private expression: string;
 
  constructor(source: string, expression: string) {
    this.expression = expression;
    this.tokens = tokenize(source, expression);
  }
 
  private peek(): Token {
    return this.tokens[this.position];
  }
 
  private next(): Token {
    return this.tokens[this.position++];
  }
 
  private isPunct(value: string): boolean {
    const token = this.peek();
    return token.kind === 'punct' && token.value === value;
  }
 
  private isIdent(name: string): boolean {
    const token = this.peek();
    return token.kind === 'ident' && token.name === name;
  }
 
  private expectPunct(value: string): void {
    Iif (!this.isPunct(value)) {
      throw new ExpressionSyntaxError(`Expected '${value}'`, this.expression);
    }
    this.next();
  }
 
  private fail(message: string): never {
    throw new ExpressionSyntaxError(message, this.expression);
  }
 
  parse(): ExpressionNode {
    const node = this.parseConditional();
    Iif (this.peek().kind !== 'end') {
      this.fail('Unexpected trailing input');
    }
    return node;
  }
 
  /** Also used for template interpolations and call arguments. */
  parseSubExpression(): ExpressionNode {
    return this.parseConditional();
  }
 
  private parseConditional(): ExpressionNode {
    const test = this.parseBinary(0);
    Eif (!this.isPunct('?')) {
      return test;
    }
    this.next();
    const consequent = this.parseConditional();
    this.expectPunct(':');
    const alternate = this.parseConditional();
    return { type: 'conditional', test, consequent, alternate };
  }
 
  private parseBinary(minPrecedence: number): ExpressionNode {
    let left = this.parseUnary();
 
    for (;;) {
      const token = this.peek();
      let operator: string | undefined;
      if (token.kind === 'punct' && BINARY_PRECEDENCE[token.value]) {
        operator = token.value;
      } else if (token.kind === 'ident' && token.name === 'in') {
        operator = 'in';
      }
      if (!operator) {
        return left;
      }
      const precedence = BINARY_PRECEDENCE[operator];
      if (precedence <= minPrecedence) {
        return left;
      }
      this.next();
      const right = this.parseBinary(precedence);
      left =
        operator === '&&' || operator === '||'
          ? { type: 'logical', operator, left, right }
          : { type: 'binary', operator, left, right };
    }
  }
 
  private parseUnary(): ExpressionNode {
    const token = this.peek();
    if (
      token.kind === 'punct' &&
      (token.value === '!' || token.value === '-' || token.value === '+')
    ) {
      this.next();
      return {
        type: 'unary',
        operator: token.value,
        argument: this.parseUnary(),
      };
    }
    return this.parsePostfix();
  }
 
  private parsePostfix(): ExpressionNode {
    let node = this.parsePrimary();
 
    for (;;) {
      if (this.isPunct('.')) {
        this.next();
        const property = this.next();
        Iif (property.kind !== 'ident') {
          this.fail("Expected a property name after '.'");
        }
        Iif (FORBIDDEN_PROPERTIES.has(property.name)) {
          this.fail(`Access to '${property.name}' is not allowed`);
        }
        node = { type: 'member', object: node, property: property.name };
        continue;
      }
      Iif (this.isPunct('[')) {
        this.next();
        const index = this.parseSubExpression();
        this.expectPunct(']');
        node = { type: 'index', object: node, index };
        continue;
      }
      if (this.isPunct('(')) {
        const receiver = aggregateReceiver(node);
        Iif (node.type !== 'identifier' && !receiver) {
          this.fail('Only whitelisted helper functions may be called');
        }
        const callee =
          node.type === 'identifier'
            ? node.name
            : (node as { property: string }).property;
        this.next();
        const args: ExpressionNode[] = [];
        if (!this.isPunct(')')) {
          for (;;) {
            args.push(this.parseSubExpression());
            Iif (this.isPunct(',')) {
              this.next();
              continue;
            }
            break;
          }
        }
        this.expectPunct(')');
        node = receiver
          ? { type: 'call', callee, args, receiver }
          : { type: 'call', callee, args };
        continue;
      }
      return node;
    }
  }
 
  private parsePrimary(): ExpressionNode {
    const token = this.next();
 
    if (token.kind === 'number') {
      return { type: 'literal', value: token.value };
    }
    if (token.kind === 'string') {
      return { type: 'literal', value: token.value };
    }
    Iif (token.kind === 'template') {
      return {
        type: 'template',
        parts: token.parts.map((part) =>
          part.kind === 'text'
            ? part
            : {
                kind: 'expr' as const,
                node: parseExpressionSource(part.source, this.expression),
              }
        ),
      };
    }
    if (token.kind === 'ident') {
      if (KEYWORD_LITERALS.has(token.name)) {
        return { type: 'literal', value: KEYWORD_LITERALS.get(token.name) };
      }
      Iif (token.name === 'in') {
        this.fail("Unexpected 'in'");
      }
      Iif (FORBIDDEN_PROPERTIES.has(token.name)) {
        this.fail(`Access to '${token.name}' is not allowed`);
      }
      return { type: 'identifier', name: token.name };
    }
    Eif (token.kind === 'punct') {
      if (token.value === '(') {
        const node = this.parseSubExpression();
        this.expectPunct(')');
        return node;
      }
      Eif (token.value === '[') {
        const elements: ExpressionNode[] = [];
        Eif (!this.isPunct(']')) {
          for (;;) {
            elements.push(this.parseSubExpression());
            if (this.isPunct(',')) {
              this.next();
              continue;
            }
            break;
          }
        }
        this.expectPunct(']');
        return { type: 'array', elements };
      }
    }
    this.fail('Unexpected token');
  }
}
 
/** Parses a raw expression source string into an AST. */
export function parseExpressionSource(
  source: string,
  expression = source
): ExpressionNode {
  return new Parser(source, expression).parse();
}