Recursive Decent Parsing:Functions to parse the Toy Grammar II
Here are two more of the four functions needed to parse the Toy Grammar. Note the use of a while() loop to match possibly repeated (optional) elements in a grammar production, based on whether the look ahead token indicates that a repeated element is present.
The Scanner is called to re-load the look-ahead token only if a match occurs. If the token isnt matched, we assume some other part of the Grammar must match it, so the Scanner is not called on a mis-match.
<> --> <> ( (+|-) <> )*
term(); /* non-terminal is function call */
while( tokentype == PLUS || tokentype == MINUS ){
scanner(); /* get next lookahead token */
term(); /* non-terminal is function call */
<> --> <> ( (*|/) <> )*
factor(); /* non-terminal is function call */
while( tokentype == MULT || tokentype == DIV ){
scanner(); /* get next lookahead token */
factor();/* non-terminal is function call */