Concepts of Programming Languages

(Sean Pound) #1

184 Chapter 4 Lexical and Syntax Analysis


produced when an error is detected. Furthermore, parsers must recover from
the error so that the parsing process can continue.

/* factor
Parses strings in the language generated by the rule:
<factor> -> id | int_constant | ( <expr )
*/
void factor() {
printf("Enter <factor>\n");

/* Determine which RHS */
if (nextToken == IDENT || nextToken == INT_LIT)

/* Get the next token */
lex();

/* If the RHS is ( <expr>), call lex to pass over the
left parenthesis, call expr, and check for the right
parenthesis */
else {
if (nextToken == LEFT_PAREN) {
lex();
expr();
if (nextToken == RIGHT_PAREN)
lex();
else
error();
} /* End of if (nextToken == ... */

/* It was not an id, an integer literal, or a left
parenthesis */
else
error();
} /* End of else */

printf("Exit <factor>\n");;
} /* End of function factor */

Following is the trace of the parse of the example expression (sum + 47) /
total, using the parsing functions expr, term, and factor, and the function
lex from Section 4.2. Note that the parse begins by calling lex and the start
symbol routine, in this case, expr.

Next token is: 25 Next lexeme is (
Enter <expr>
Enter <term>
Enter <factor>
Free download pdf