For the grammar
$< term > \to < factor > \{(*|/)< factor >\}*$
We could use the following recursive descent parsing subprogram (this one is written in C)
void term() {
factor(); /* parse first factor*/
while (next_token == ast_code ||
next_token == slash_code) {
lexical(); /* get next token */
factor(); /* parse next factor */
}
}
For a grammar of
We can remove left recursion by replacing S with
Remove left recursion from
For the grammar:
The parsing table is:
Parse
Stack | Input | Action |
---|---|---|
0 | id * id + id $ | S5 |
0 id 5 | * id + id $ | R6 |
0 F 3 | * id + id $ | R4 |
0 T 2 | * id + id $ | S7 |
0 T 2 * 7 | id + id $ | S5 |
0 T 2 * 7 id 5 | + id $ | R6 |
0 T 2 * 7 F 10 | + id $ | R3 |
0 T 2 | + id $ | R2 |
0 E 1 | + id $ | S6 |
0 E 1 + 6 | id $ | S5 |
0 E 1 + 6 id 5 | $ | R6 |
0 E 1 + 6 F 3 | $ | R4 |
0 E 1 + 6 T 9 | $ | R1 |
0 E 1 | $ | accept |
The parsing table is:
Show the parse including the stack for id * ( id + id)
Grammar:
The parsing table is:
Parse:
Stack | Input | Action |
---|---|---|
0 | id * (id + id) $ | S5 |
0 id 5 | * (id + id) $ | R6 |
0 F 3 | * (id + id) $ | R4 |
0 T 2 | * (id + id) $ | S7 |
0 T 2 * 7 | (id + id) $ | S4 |
0 T 2 * 7 ( 4 | id + id ) $ | S5 |
0 T 2 * 7 ( 4 id 5 | + id) $ | R6 |
0 T 2 * 7 ( 4 F 3 | + id) $ | R4 |
0 T 2 * 7 ( 4 T 2 | + id )$ | R2 |
0 T 2 * 7 ( 4 E 8 | + id ) $ | S6 |
0 T 2 * 7 ( 4 E 8 + 6 | id )$ | S5 |
0 T 2 * 7 ( 4 E 8 + 6 id 5 | ) $ | R6 |
0 T 2 * 7 ( 4 E 8 + 6 F 3 | ) $ | R4 |
0 T 2 * 7 ( 4 E 8 + 6 T 9 | ) $ | R1 |
0 T 2 * 7 ( 4 E 8 | ) $ | S11 |
0 T 2 * 7 ( 4 E 8 ) 11 | $ | R5 |
0 T 2 * 7 F 10 | $ | R3 |
0 T 2 | $ | R2 |
0 E 1 | $ | accept |