CS118 Programming LanguagesLecture 8Contents
Recursive ParsingSummary: Start with a regular expression grammar where all left recursion is replaced with Kleene star. Each Kleene star is replaced by a while loop. Lookahead may be needed to decide to stop the while loop. The output is the shift/reduce sequence. Example: suppose you have the little 4 rule grammar P = E; r1 E = E + T; r2 E = T; r3 T = 1; r4Translate left recursions into regular expressions P = E E = T (+ T)* T = 1Then use the grammar as a design to implement the parser
static int tok;
void P(void) {E(); reduce(r1);}
void E(void) {
T(); reduce(r3);
while(tok == PLUS) {
shift(tok); tok=nexttok();
T(); reduce(r2);
}
}
void T(void) {
if (tok == ONE) {
shift(tok); tok=nexttok();
} else error();
reduce(r4);
}
|