Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Recursive descent parser in JavaScript

115 A recursive-descent parser for arithmetic, precedence and all

hard

Parse and evaluate arithmetic expressions with the precedence a human expects. Write one function per precedence level — sums call products, products call powers, powers call primaries — so that 2 + 3 * 4 is 14 without a precedence table anywhere. Build a tree, then evaluate it against an environment of variables and functions. Make subtraction left-associative and exponentiation right-associative, and assert both from the tree shape rather than only from the answer. Reject a missing bracket, an unknown name, and trailing input, each with a position.

Stuck? Three hints, smallest first
  1. 1. A loop makes an operator left-associative: parse one operand, then while the next token is your operator, fold what you have into the left side of a new node.
  2. 2. Recursion at the same level makes it right-associative: after ^, call the same function again rather than looping.
  3. 3. The parser is not finished when the tree is built. If the next token is not end-of-input, something was left over, and silently ignoring it is how 2 + 3 4 becomes 5.

The answer

function lex(source) {
  const tokens = [];
  let i = 0;
  while (i < source.length) {
    const c = source[i];
    if (c === ' ') { i++; continue; }
    if (c >= '0' && c <= '9') {
      let text = '';
      while (i < source.length && ((source[i] >= '0' && source[i] <= '9') || source[i] === '.')) text += source[i++];
      tokens.push({ type: 'number', value: Number(text), column: i - text.length + 1 });
      continue;
    }
    if (/[a-zA-Z_]/.test(c)) {
      let text = '';
      while (i < source.length && /[a-zA-Z0-9_]/.test(source[i])) text += source[i++];
      tokens.push({ type: 'name', value: text, column: i - text.length + 1 });
      continue;
    }
    if ('+-*/%^(),'.indexOf(c) !== -1) { tokens.push({ type: 'op', value: c, column: i + 1 }); i++; continue; }
    const err = new Error('unexpected character ' + JSON.stringify(c) + ' at column ' + (i + 1));
    err.name = 'SyntaxError';
    throw err;
  }
  tokens.push({ type: 'end', value: '', column: source.length + 1 });
  return tokens;
}

function parse(source) {
  const tokens = lex(source);
  let at = 0;

  const peek = () => tokens[at];
  const fail = (wanted) => {
    const t = tokens[at];
    const found = t.type === 'end' ? 'end of input' : JSON.stringify(String(t.value));
    const err = new Error('expected ' + wanted + ' but found ' + found + ' at column ' + t.column);
    err.name = 'SyntaxError';
    err.column = t.column;
    throw err;
  };
  const eat = (value) => {
    if (tokens[at].type === 'op' && tokens[at].value === value) { at++; return true; }
    return false;
  };

  // sum := product (('+' | '-') product)*        loop, so left-associative
  const sum = () => {
    let left = product();
    for (;;) {
      if (eat('+')) left = { op: '+', left, right: product() };
      else if (eat('-')) left = { op: '-', left, right: product() };
      else return left;
    }
  };

  // product := unary (('*' | '/' | '%') unary)*
  const product = () => {
    let left = unary();
    for (;;) {
      if (eat('*')) left = { op: '*', left, right: unary() };
      else if (eat('/')) left = { op: '/', left, right: unary() };
      else if (eat('%')) left = { op: '%', left, right: unary() };
      else return left;
    }
  };

  // unary := ('-' | '+') unary | power           so -2 ^ 2 is -(2 ^ 2)
  const unary = () => {
    if (eat('-')) return { op: 'neg', operand: unary() };
    if (eat('+')) return unary();
    return power();
  };

  // power := primary ('^' unary)?                recursion, so right-associative
  const power = () => {
    const base = primary();
    if (eat('^')) return { op: '^', left: base, right: unary() };
    return base;
  };

  const primary = () => {
    const t = peek();
    if (t.type === 'number') { at++; return { num: t.value }; }
    if (t.type === 'name') {
      at++;
      if (eat('(')) {
        const args = [];
        if (!eat(')')) {
          for (;;) {
            args.push(sum());
            if (eat(',')) continue;
            if (eat(')')) break;
            fail('"," or ")"');
          }
        }
        return { call: t.value, args };
      }
      return { name: t.value };
    }
    if (eat('(')) {
      const inner = sum();
      if (!eat(')')) fail('")"');
      return inner;
    }
    return fail('a number, a name or "("');
  };

  const tree = sum();
  if (peek().type !== 'end') fail('end of input');
  return tree;
}

const FUNCTIONS = { min: Math.min, max: Math.max, abs: Math.abs };

function evaluate(node, env = {}) {
  if ('num' in node) return node.num;
  if ('name' in node) {
    if (!Object.prototype.hasOwnProperty.call(env, node.name)) {
      const err = new Error('unknown name "' + node.name + '"');
      err.name = 'ReferenceError';
      throw err;
    }
    return env[node.name];
  }
  if ('call' in node) {
    const fn = FUNCTIONS[node.call];
    if (!fn) {
      const err = new Error('unknown function "' + node.call + '"');
      err.name = 'ReferenceError';
      throw err;
    }
    return fn(...node.args.map((a) => evaluate(a, env)));
  }
  if (node.op === 'neg') return -evaluate(node.operand, env);
  const l = evaluate(node.left, env);
  const r = evaluate(node.right, env);
  if (node.op === '+') return l + r;
  if (node.op === '-') return l - r;
  if (node.op === '*') return l * r;
  if (node.op === '/') return l / r;
  if (node.op === '%') return l % r;
  return Math.pow(l, r);
}

const run = (source, env) => evaluate(parse(source), env);
const errorOf = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name + ': ' + err.message; } };

const precedence = [run('2 + 3 * 4'), run('(2 + 3) * 4'), run('2 * 3 + 4 * 5')];
const leftAssociative = [run('10 - 3 - 2'), parse('10 - 3 - 2')];
const rightAssociative = [run('2 ^ 3 ^ 2'), parse('2 ^ 3 ^ 2')];
const unaryVsPower = [run('-2 ^ 2'), run('(-2) ^ 2'), errorOf(() => new Function('return -2 ** 2'))];

const env = { rate: 0.075, items: 42, floor: 2 };
const withNames = [run('items * rate', env), run('max(items * rate, floor) + 1', env), run('abs(0 - items)', env)];

const unknownName = errorOf(() => run('items * vat', env));
const missingBracket = errorOf(() => run('2 * (3 + 4'));
const leftovers = errorOf(() => run('2 + 3 4'));
const emptyInput = errorOf(() => run(''));
const oddEdges = [run('7 / 0') === Infinity, run('0 - 7 / 0') === -Infinity, run('7 % 3'), run('0 - 7 % 3')];

console.log('precedence      :', precedence);
console.log('10 - 3 - 2 tree :', JSON.stringify(leftAssociative[1]));
console.log('2 ^ 3 ^ 2 tree  :', JSON.stringify(rightAssociative[1]));
console.log('errors          :', [unknownName, missingBracket, leftovers]);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('one function per precedence level gets multiplication first, with no table', precedence, [14, 20, 26]);
test('subtraction is left-associative, and the tree nests to the left to prove it', leftAssociative, [5, { op: '-', left: { op: '-', left: { num: 10 }, right: { num: 3 } }, right: { num: 2 } }]);
test('exponentiation is right-associative, and nests the other way', rightAssociative, [512, { op: '^', left: { num: 2 }, right: { op: '^', left: { num: 3 }, right: { num: 2 } } }]);
test('unary minus is weaker than ^, which is why JavaScript refuses -2 ** 2 outright', unaryVsPower, [-4, 4, 'SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence']);
test('names and calls resolve against the environment handed to the evaluator', withNames, [3.15, 4.15, 42]);
test('an unknown name is a ReferenceError naming it, not a silent NaN', unknownName, 'ReferenceError: unknown name "vat"');
test('a missing bracket says what it wanted and where it gave up', missingBracket, 'SyntaxError: expected ")" but found end of input at column 11');
test('trailing input is rejected rather than quietly ignored, and empty input too', [leftovers, emptyInput], ['SyntaxError: expected end of input but found "4" at column 7', 'SyntaxError: expected a number, a name or "(" but found end of input at column 1']);
test('division by zero gives a signed Infinity, and % keeps the sign of the left operand', oddEdges, [true, true, 1, -1]);

Precedence needs no table because it is in the shape of the call graph. sum can only build a + node out of whatever product returned, so a product is always finished before a sum can see it, and 2 + 3 * 4 comes out as 2 + (3 * 4) with nothing deciding that explicitly. Adding a level means adding a function between two existing ones — that is the whole appeal of recursive descent, and why hand-written parsers outnumber generated ones in real compilers.

Associativity is the difference between a loop and a recursion, and the second and third assertions show it in the trees rather than in the answers. sum loops and folds each new operand into the left slot, so 10 - 3 - 2 nests leftwards and evaluates to 5; get it wrong and you get 10 - (3 - 2), which is 9, and a plausible-looking 9 is a very hard bug to see. power calls back into unary for its right operand, so 2 ^ 3 ^ 2 nests rightwards and is 512 rather than 64.

The fourth assertion is the trap the language itself refuses to fall into. Putting unary minus below ^ makes -2 ^ 2 equal -(2 ^ 2), which is −4 and matches ordinary mathematical notation — but plenty of languages and spreadsheets choose the other reading and return 4. The disagreement is real enough that JavaScript declines to pick: -2 ** 2 is a syntax error, and the engine tells you to add brackets.

The last piece of the parser is the easiest to leave out. After the tree is built, the next token must be end-of-input; without that check 2 + 3 4 parses as 2 + 3 and the stray 4 disappears. A parser that accepts a prefix of its input and ignores the rest is worse than one that rejects, because the answer looks right.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.