Recursive Decent Parsing:Functions to parse the Toy Grammar I
We start with just parsing the input. No actions will be taken on anything we match; we simply match it and move on. (This is like having a DFA inside a scanner that doesnt have any actions in it to save characters.)
A predictive parser can be built directly from the productions in the grammar. Non-terminals become function calls; terminals are matched directly against tokens by the token type returned by the scanner. To simplify coding, the returned token type is kept in a global variable.
scanner(); /* get the next lookahead token */
if( tokentype != EQUALS )
scanner(); /* get the next lookahead token */
error("EOF in assignment statement");
expression(); /* non-terminal is function call */
if( tokentype != SEMICOLON )
scanner(); /* get the next lookahead token */
The scanner is called after a match of a terminal token, to keep the global tokentype always pointing to the next token. This is called the look ahead token. The very first look ahead token has to be read by an initial call to scanner() before any of the grammars parsing functions are called. Often this is done in main(), before calling the parser.