编译原理作业7


编译原理作业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(,)SR
0s2s3   1 
1    acc  
2s2s3   4 
3  r2r2r2  
4  s6s7  5
5  r1r1r1  
6s2s3   8 
7  r4r4r4  
8  s6s7  9
9  r3r3r3  

不会出现冲突。

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
0s5s6r3123
1  acc   
2  r1   
3s5s6r3 43
4  r2   
5s5s6   7
6r5r5r5   
7r4r4r4   

没有冲突,所以该文法是LR(1)的。

parsing过程如下:

stepsymbolstateinputreferenceactionoutput
10shift 
205shift 
3056reduce
4057reduce
503shift 
6035shift 
70356reduce
80357reduce
9033reduce
100334reduce
11034reduce
1202reduce
1301accept 

 

Exercise 7.4

Show that the grammar

is LALR(1) but not SLR(1).

扩展文法如下:

 

 

FIRST和FOLLOW如下:

state
0 s4 s9 12
1    acc  
2s3      
3    r1  
4   s7  5
5  s6    
6    r2  
7s8 r5    
8    r4  
9r5 s10    
10    r3  

不会出现冲突,所以该文法是LALR(1)的。

它不是SLR(1)的,

在这里,如果input的下一个字符是c,因为,所以可以使用进行reduce,也可以用来shift,出现了shift-reduce冲突。所以该文法不是SLR(1)的。