Constructing a recursive descent parser
As shown in the previous chapter, the parser is derived from its grammar. Let's recall all the construction rules. For each rule of grammar, you create a method that's named after the non-terminal on the left-hand side of the rule in order to parse the right-hand side of the rule. Following the definition of the right-hand side, you must do the following:
- For each non-terminal, the corresponding method is called.
- Each token is consumed.
- For alternatives and optional or repeating groups, the look-ahead token (the next unconsumed token) is examined to decide where we can continue from.
Let's apply these construction rules to the following rule of the grammar:
ifStatement : "IF" expression "THEN" statementSequence ( "ELSE" statementSequence )? "END" ;
We can easily translate this into the following C++ method:
void Parser::parseIfStatement...