# What is a recursive descent parser?

> A recursive descent parser turns each grammar rule into a function that calls the others. How it handles precedence and errors, with Lox as the example.

**Recursive descent parser**: A recursive descent parser is a top-down parser in which each grammar rule becomes a function, and functions call each other to match nested structure.

A **recursive descent parser** is a parser written by hand where every rule in the grammar becomes a function. To parse an expression it calls the function for the lowest-precedence rule, which calls the next, down to literals and parentheses. It is how most production compilers parse today.

## Precedence through the grammar

For Lox, the expression grammar is layered: `equality` calls `comparison`, which calls `term` (`+` and `-`), which calls `factor` (`*` and `/`), which calls `unary`, which calls `primary`. Because higher-precedence rules sit deeper, `1 + 2 * 3` groups the multiplication first without any special handling. A loop in each function gives left associativity.

## Error recovery

When a recursive descent parser hits a syntax error, it can report it and **synchronize**: skip tokens until a likely statement boundary (a semicolon, or a keyword like `class` or `fun`) and carry on, so one typo does not hide every later error. Crafting Interpreters builds exactly this in [chapter 6](https://cracked.guide/guide/ci-06). Compare the [Pratt parser](https://cracked.guide/glossary/pratt-parser) used later in clox.

## Questions

### Why not use a parser generator?

You can, but a hand-written recursive descent parser is easy to read, gives better error messages and needs no extra tool. Many large compilers use one.

### Can recursive descent handle left recursion?

Not directly; a rule like expr -> expr + term loops forever. You rewrite it as a loop, which is what the Lox grammar does.

---

Source: https://cracked.guide/glossary/recursive-descent-parser
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
