![]() |
VOOZH | about |
A recursive descent parser is a top-down parser that processes input based on a set of recursive functions, where each function corresponds to a grammar rule. It parses the input from left to right, constructing a parse tree by matching the grammar's production rules. This parser is simple to implement and is suitable for LL(1) grammars, where decisions can be made based on a single lookahead token. While straightforward, recursive descent parsers struggle with left-recursive grammars and may require grammar transformations to handle such cases effectively.
A Predictive Parser is a special case of Recursive Descent Parser, where no Back Tracking is required.
By carefully writing a grammar, means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.
By carefully writing a grammar means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.
Example:
| Before removing left recursion | After removing left recursion |
|---|---|
| E β> E + T | T T β> T * F | F F β> ( E ) | id | E β> T Eβ Eβ β> + T Eβ | e T β> F Tβ Tβ β> * F Tβ | e F β> ( E ) | id |
S()
{ Choose any S production, S ->X1X2β¦..Xk;
for (i = 1 to k)
{
If ( Xi is a non-terminal)
Call procedure Xi();
else if ( Xi equals the current input, increment input)
Else /* error has occurred, backtrack and try another possibility */
}
}
Let's understand it better with an example:
The given grammar is:
E β i E'E' β + i E' | Ξ΅
Function E()
E(){if (input == 'i') { // If the input is 'i' (identifier)input++; // Consume 'i'}E'(); // Call E' to check for further expressions}
i (identifier).E'() to check if a + operation exists.Function E'()
void E`() {if (input == '+') {input++; // Consume the '+'if (input == 'i') {input++; // Consume the 'i'}E`(); // Recursively process more additions} else {return; // If no '+', return (Ξ΅ production)}}
+ i.E'() recursively.+, it returns (Ξ΅ production).Main Function
Main(){E(); // Start parsing from Eif (input == '$') // If we reach end of inputParsing Successful;}
E() to start parsing.$, which indicates a successful parse.Example Input Parsing
Letβs consider the example input:
i + i $Processing step by step:
E() starts β input == i, so consume iE'() β input == +, so consume +input == i, so consume iE'() again β no +, so return.Main(), input == $ β Parsing Successful