3. Pratt Parsing

Operator precedence made simple

In the previous article, we wrote a recursive descent parser where each precedence level got its own function. It works, but it's repetitive — ten levels means ten nearly identical methods. Vaughan Pratt's 1973 paper introduced a better way: instead of encoding precedence in the call structure, encode it in a data table. One parsing function handles all binary operators by consulting the table at runtime.

The core idea

Every operator gets a binding power (also called precedence) — a number that says how tightly it holds onto its operands. Higher numbers bind tighter:

const PRECEDENCE = {
  '+': 1, '-': 1,
  '*': 2, '/': 2,
  '**': 3,
};

The parser has a single expression-parsing function that takes a minimum binding power parameter. It parses a "left-hand side," then loops: if the next operator's binding power is high enough (greater than the minimum), it consumes the operator and recursively parses the right-hand side with an updated minimum. If not, it stops and returns what it has.

parseExpression(minBP = 0) {
  let left = this.parsePrefix();

  while (true) {
    const op = this.peek();
    const bp = PRECEDENCE[op.type];
    if (bp === undefined || bp <= minBP) break;

    this.advance(); // consume operator
    const right = this.parseExpression(bp);
    left = { type: 'BinaryExpr', op: op.lexeme, left, right };
  }

  return left;
}

parsePrefix() {
  const tok = this.advance();
  if (tok.type === 'NUMBER') return { type: 'NumberLiteral', value: tok.literal };
  if (tok.type === '(') {
    const expr = this.parseExpression(0);
    this.expect(')');
    return expr;
  }
  throw new Error(`Unexpected token: ${tok.type}`);
}

That's it. Two functions replace an arbitrary number of precedence-level methods.

Tracing through an example

Let's parse 1 + 2 * 3:

  1. parseExpression(0) calls parsePrefix() → NumberLiteral(1)
  2. Peek: + has bp=1. 1 > 0, so enter the loop.
  3. Consume +. Call parseExpression(1).
  4. Inside: parsePrefix() → NumberLiteral(2)
  5. Peek: * has bp=2. 2 > 1, so enter the inner loop.
  6. Consume *. Call parseExpression(2).
  7. Inside: parsePrefix() → NumberLiteral(3)
  8. Peek: EOF. No operator. Return NumberLiteral(3).
  9. Back in step 6: build BinaryExpr(*, 2, 3).
  10. Peek: EOF. Return BinaryExpr(*, 2, 3).
  11. Back in step 3: build BinaryExpr(+, 1, BinaryExpr(*, 2, 3)).

The * bound tighter than + because its binding power (2) was high enough to continue the inner loop, while the + was not.

Left vs. right associativity

1 + 2 + 3 should parse as (1 + 2) + 3 (left-associative). But 2 ** 3 ** 4 should parse as 2 ** (3 ** 4) (right-associative). The trick is simple:

  • Left-associative: recurse with bp (same as the operator's binding power). The next same-precedence operator will not pass the > minBP check, so the loop exits and the left side grows.
  • Right-associative: recurse with bp - 1. Now a same-precedence operator will pass the check, so it gets absorbed into the right side.
parseExpression(minBP = 0) {
  let left = this.parsePrefix();

  while (true) {
    const op = this.peek();
    const info = OPERATORS[op.type];
    if (!info || info.bp <= minBP) break;

    this.advance();
    const nextMinBP = info.assoc === 'right' ? info.bp - 1 : info.bp;
    const right = this.parseExpression(nextMinBP);
    left = { type: 'BinaryExpr', op: op.lexeme, left, right };
  }

  return left;
}

Prefix operators

Unary prefix operators like -x or !flag are handled in parsePrefix. Give each prefix operator its own binding power (usually high, since -a * b should parse as (-a) * b):

parsePrefix() {
  const tok = this.advance();

  if (tok.type === '-') {
    const operand = this.parseExpression(PREFIX_BP);
    return { type: 'UnaryExpr', op: '-', operand };
  }

  if (tok.type === 'NUMBER') return { type: 'NumberLiteral', value: tok.literal };
  // ...
}

Postfix operators

Postfix operators like x! (factorial) or x++ fit naturally into the infix loop. Check for them after the left-hand side, give them a binding power, and don't recurse (there's no right operand):

if (op.type === '!') {
  this.advance();
  left = { type: 'PostfixExpr', op: '!', operand: left };
  continue;
}

Mixfix: ternary and indexing

The ternary operator a ? b : c is just an infix operator with extra structure. When you see ?, parse the middle expression, expect :, parse the right expression:

if (op.type === '?') {
  this.advance();
  const consequent = this.parseExpression(0); // reset precedence inside
  this.expect(':');
  const alternate = this.parseExpression(TERNARY_BP - 1); // right-associative
  left = { type: 'TernaryExpr', condition: left, consequent, alternate };
  continue;
}

Array indexing a[i] and function calls f(x, y) work the same way — they're infix operators where the "right operand" is delimited by brackets or parentheses.

Why Pratt parsing?

  • Minimal code: one loop handles all binary operators.
  • Easy to extend: adding an operator means one table entry.
  • Composable with recursive descent: use Pratt for expressions, recursive descent for statements. This is how most real parsers work.
  • Great error messages: you always know what you were trying to parse and what you got instead.

Douglas Crockford popularized this technique in JavaScript (it powers JSLint's parser). Bob Nystrom's Crafting Interpreters calls it the "most elegant" parsing algorithm. Once you see it, you'll never go back to writing a separate function per precedence level.

Try It Yourself — Pratt Parser

Type an expression with +, -, *, /, and ** (right-associative exponentiation). Watch how binding power controls which operator "wins" each operand.

Binding Power Table

Parse Tree

Binding Power Decisions

Evaluation