Constructing a recursive descent parser
As shown in the previous chapter, the parser is derived from the grammar. Let’s recall all the construction rules. For each rule of the grammar, you create a method named after the non-terminal on the left-hand side of the rule to parse the right-hand side of the rule. Following the definition of the right-hand side, you 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 to continue
Let’s apply these construction rules to the following rule of grammar:
ifStatement : "IF" expression "THEN" statementSequence ( "ELSE" statementSequence )? "END" ;
We can easily translate this into the following C++ method:
void Parser::parseIfStatement() { consume...