Intermediate Topic 23 of 50 Languages & Compilers
Recursive Descent Parsing
Hand-written top-down parsing with mutually recursive functions.
How it works
Recursive descent parsing is a top-down technique in which each grammar nonterminal becomes a function that consumes tokens and calls functions for the nonterminals on its right-hand side. With one token of lookahead it handles LL(1) grammars directly, and precedence climbing or Pratt parsing handles expressions with operator precedence neatly. Hand-written recursive descent parsers are simple, flexible and give excellent error messages.
Step-by-step walkthrough
- Each grammar rule becomes a function.
- parseExpr calls parseTerm.
- parseTerm calls parseFactor.
- parseFactor consumes a number or parenthesized expression.
- Functions return as rules match, so it is easy to hand-write.
Where it is used
Many production compilers and tools, including GCC's C and C++ front ends, Clang, Go, Rust and many JSON and configuration parsers, use hand-written recursive descent.
Common pitfall
Left-recursive rules cause infinite recursion and must be rewritten as loops. Grammars needing more than limited lookahead require backtracking, which can become exponential without memoization, as in packrat parsing. Deep nesting can overflow the stack. Handle error recovery by synchronizing on tokens such as semicolons, and write tests for each grammar rule.
Where it fits in the course
Recursive Descent Parsing is topic 23 of 50 in Languages & Compilers, rated Intermediate. It follows Compiler Phases. The next topic is LL and LR Parsing.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Recursive Descent Parsing?
Where do people use Recursive Descent Parsing?
What is the most common mistake with Recursive Descent Parsing?
What should I learn before this topic?
How can I practice it?
Is Recursive Descent Parsing hard to learn?
How long does it take to learn Recursive Descent Parsing?
Which topics are related to Recursive Descent Parsing?
What should I study after Recursive Descent Parsing?
Related topics
- Compiler Phases (Languages & Compilers)
- LL and LR Parsing (Languages & Compilers)
- Generics and Templates (Languages & Compilers)
- Parser Generators (Languages & Compilers)
- Gradient Descent (AI & Machine Learning)