2. Recursive Descent Parsing

Top-down parsing by hand

You have a list of tokens. Now what? You need to figure out what they mean — which numbers are operands, which operators bind tighter, where one expression ends and the next begins. This is parsing, and the simplest way to do it by hand is called recursive descent.

The idea

A recursive descent parser is a collection of mutually recursive functions, one per grammar rule. Each function knows how to parse one kind of construct (an expression, a statement, a function declaration) and calls the others as needed.

It's called top-down because you start from the broadest rule (e.g. "program") and work your way down to the smallest pieces (e.g. "number literal"). It's called recursive because the functions call each other — and often themselves.

A tiny grammar

Let's parse arithmetic expressions with +, -, *, /, and parentheses. The grammar, written informally:

expression  = term (('+' | '-') term)*
term        = factor (('*' | '/') factor)*
factor      = NUMBER | '(' expression ')'

This grammar encodes precedence: multiplication binds tighter than addition because term (which handles * and /) is nested inside expression (which handles + and -). The deeper a rule sits, the tighter it binds.

The parser skeleton

We need a way to walk through the token list. A Parser object holds the tokens and a cursor:

class Parser {
  constructor(tokens) {
    this.tokens = tokens;
    this.pos = 0;
  }

  peek()    { return this.tokens[this.pos]; }
  advance() { return this.tokens[this.pos++]; }

  expect(type) {
    const tok = this.advance();
    if (tok.type !== type) {
      throw new Error(`Expected ${type}, got ${tok.type}`);
    }
    return tok;
  }

  match(...types) {
    if (types.includes(this.peek().type)) {
      return this.advance();
    }
    return null;
  }
}

peek looks at the current token without consuming it. advance consumes and returns it. expect consumes a token and throws if it's not the right type. match consumes only if the current token is one of the given types.

These four helpers are all you need.

Translating the grammar

Each grammar rule becomes a method. The translation is almost mechanical:

  • A sequence (A B C) becomes consecutive calls: parseA(); parseB(); parseC();
  • An alternative (A | B) becomes an if/else checking the current token
  • A repetition ((A)*) becomes a while loop
// expression = term (('+' | '-') term)*
parseExpression() {
  let left = this.parseTerm();

  while (this.peek().type === '+' || this.peek().type === '-') {
    const op = this.advance();
    const right = this.parseTerm();
    left = { type: 'BinaryExpr', op: op.lexeme, left, right };
  }

  return left;
}

// term = factor (('*' | '/') factor)*
parseTerm() {
  let left = this.parseFactor();

  while (this.peek().type === '*' || this.peek().type === '/') {
    const op = this.advance();
    const right = this.parseFactor();
    left = { type: 'BinaryExpr', op: op.lexeme, left, right };
  }

  return left;
}

// factor = NUMBER | '(' expression ')'
parseFactor() {
  if (this.peek().type === 'NUMBER') {
    const tok = this.advance();
    return { type: 'NumberLiteral', value: tok.literal };
  }

  if (this.match('(')) {
    const expr = this.parseExpression();
    this.expect(')');
    return expr;
  }

  throw new Error(`Unexpected token: ${this.peek().type}`);
}

That's the entire parser. Feed it 3 + 4 * 2 and trace the calls:

  1. parseExpression calls parseTerm
  2. parseTerm calls parseFactor → returns NumberLiteral(3)
  3. parseTerm sees no * or /, returns 3
  4. parseExpression sees +, consumes it, calls parseTerm again
  5. parseTerm calls parseFactor → returns NumberLiteral(4)
  6. parseTerm sees *, consumes it, calls parseFactor → returns NumberLiteral(2)
  7. parseTerm builds BinaryExpr(*, 4, 2) and returns it
  8. parseExpression builds BinaryExpr(+, 3, BinaryExpr(*, 4, 2))

The tree correctly reflects that * binds tighter than +.

Precedence through nesting

This is the key insight: each precedence level gets its own function. Higher-precedence operators live in functions that are called deeper in the call stack. When you add a new precedence level (say, exponentiation **), you add a new function between the existing ones.

This works beautifully but has a cost: if you have ten precedence levels, you have ten nearly identical functions. The Pratt parser (next article) solves exactly this problem.

Parsing statements

Expressions are only half the story. A real language also has statements: variable declarations, if/else, while loops, function definitions. Each one gets its own parse function:

parseStatement() {
  if (this.peek().type === 'LET')    return this.parseLetStatement();
  if (this.peek().type === 'IF')     return this.parseIfStatement();
  if (this.peek().type === 'WHILE')  return this.parseWhileStatement();
  if (this.peek().type === 'RETURN') return this.parseReturnStatement();
  return this.parseExpressionStatement();
}

parseLetStatement() {
  this.expect('LET');
  const name = this.expect('IDENTIFIER');
  this.expect('=');
  const value = this.parseExpression();
  this.expect(';');
  return { type: 'LetStatement', name: name.lexeme, value };
}

The pattern repeats: look at the current token to decide which rule to enter, then consume tokens in the expected order.

Error recovery

A simple throw stops at the first error. A production parser wants to report multiple errors. The classic technique is panic mode: when you hit an unexpected token, skip tokens until you find a synchronization point — typically a semicolon or a keyword like if, while, fn — and then resume parsing from the next statement.

Left recursion

One grammar shape that recursive descent cannot handle is left recursion:

expr = expr '+' term

This would cause parseExpr to call parseExpr immediately, with no token consumed, creating infinite recursion. The fix is to rewrite the rule using iteration (a while loop), which is exactly what we did above. Any left-recursive grammar can be mechanically transformed into a right-recursive or iterative one.

Why recursive descent?

It's the most popular hand-written parsing technique because it's simple, flexible, and produces excellent error messages. Most major language implementations — GCC, V8, Go, Rust, Swift — use recursive descent (often augmented with Pratt parsing for expressions). When you need full control over parsing, this is where you start.

Try It Yourself — Step-Through Parser

Type an arithmetic expression and watch the recursive descent parser build a parse tree. The trace on the right shows which functions are called and in what order.

Parse Tree

Parser Call Trace

Evaluation