编译原理作业7
由于格式的问题,dollar用代替。
Exercise 7.1
Consider the grammar
Try to construct an SLR(1) parsing table for the grammar, and see if there are conflicts in the parsing table.
对文法做扩展如下:
做出DFA如下:
计算FIRST和FOLLOW如下:
填充parsing table如下:
state | ( | , | ) | S | R | ||
---|---|---|---|---|---|---|---|
0 | s2 | s3 | 1 | ||||
1 | acc | ||||||
2 | s2 | s3 | 4 | ||||
3 | r2 | r2 | r2 | ||||
4 | s6 | s7 | 5 | ||||
5 | r1 | r1 | r1 | ||||
6 | s2 | s3 | 8 | ||||
7 | r4 | r4 | r4 | ||||
8 | s6 | s7 | 9 | ||||
9 | r3 | r3 | r3 |
不会出现冲突。
Exercise 7.2
Consider the grammar
Is the grammar an SLR(1) grammar? and why?
对文法做扩展如下:
计算FIRST和FOLLOW如下:
在处,遇到可以shift,同时由于,所以在SLR(1)中,可以使用r4来做reduce,这时候就出现了冲突。
所以该文法不是SLR(1)的。
Exercise 7.3
Consider the grammar
Prove that the grammar is an LR(1) grammar.
Construct an LR(1) parsing table for the grammar.
Show the detailed parsing procedure for the sentence , following the style in slides of this lecture.
扩展文法如下:
求FIRST和FOLLOW:
做出DFA如下:
构建parse table:
state | ||||||
---|---|---|---|---|---|---|
0 | s5 | s6 | r3 | 1 | 2 | 3 |
1 | acc | |||||
2 | r1 | |||||
3 | s5 | s6 | r3 | 4 | 3 | |
4 | r2 | |||||
5 | s5 | s6 | 7 | |||
6 | r5 | r5 | r5 | |||
7 | r4 | r4 | r4 |
没有冲突,所以该文法是LR(1)的。
parsing过程如下:
step | symbol | state | input | reference | action | output |
---|---|---|---|---|---|---|
1 | 0 | shift | ||||
2 | 05 | shift | ||||
3 | 056 | reduce | ||||
4 | 057 | reduce | ||||
5 | 03 | shift | ||||
6 | 035 | shift | ||||
7 | 0356 | reduce | ||||
8 | 0357 | reduce | ||||
9 | 033 | reduce | ||||
10 | 0334 | reduce | ||||
11 | 034 | reduce | ||||
12 | 02 | reduce | ||||
13 | 01 | accept |
Exercise 7.4
Show that the grammar
is LALR(1) but not SLR(1).
扩展文法如下:
FIRST和FOLLOW如下:
state | |||||||
---|---|---|---|---|---|---|---|
0 | s4 | s9 | 1 | 2 | |||
1 | acc | ||||||
2 | s3 | ||||||
3 | r1 | ||||||
4 | s7 | 5 | |||||
5 | s6 | ||||||
6 | r2 | ||||||
7 | s8 | r5 | |||||
8 | r4 | ||||||
9 | r5 | s10 | |||||
10 | r3 |
不会出现冲突,所以该文法是LALR(1)的。
它不是SLR(1)的,
在这里,如果input的下一个字符是c,因为,所以可以使用进行reduce,也可以用来shift,出现了shift-reduce冲突。所以该文法不是SLR(1)的。