例 4-12:LR分析器举例
设如下LR(1)文法的LALR 分析表已给定如下,试分析输入串bab的合法性:
1) S → B B
2) B → a B
3) B → b
LALR 分 析 表
状态 动作表 状态转移表
a b # S B
0 s3 s4 1 2
1 acc
2 s3 s4 5
3 s3 s4 6
4 r3 r3 r3
5 r1
6 r2 r2 r2
解:分析过程如下
符号栈 状态 输入 动作说明
# 0 bab# action(0,b) =s4
#b 04 ab# action(4,a) = B→b goto(0,B) =2
#B 02 ab# action(2,a) =s3
#Ba 023 b# action(3,b) =s4
#Bab 0234 # action(4,#) = B→b goto(3,B) =6
#BaB 0236 # action(6,#) = B→aB goto(2,B) =5
#BB 025 # action(5,#) = S→BB goto(0,S) =1
#S 01 # action(1,#) = accept
例: LR(0)项目集规范族构造举例(参见教材P106 图5.7)
I0=closure({S’→•E}) ={S’→•E ,E→•aA爱心传递,E→•bB}
I1=GO(I0 ,E)=closure({S’→E•}) ={S’→E•}
I2=GO(I0 ,a)=closure({E→a•A})
={E→a•A,A→•cA, A→•d}
I3=GO(I0 ,b)=closure({E→b•B})
={E→b•B,B→•cB, B→韩城旅游•d}
I4=GO(I2 ,c)=closure({A→c•A})
={A→c•A ,A→•cA, A→•d}
… …
I6=GO(I2 ,A)=closure({E→aA•}) ={E→aA•}
例:对教材P111中例5.11拓广文法,构造LR(0)项目集规范族:
解:I0=closure({S’→•E})
={S’→•E ,E→•E+T,E→•T,T→•T*F,T→•F,F→•(E),F →•i}
I1=GO(I0 ,E)=closure({S’→E•,E→E•+T})={S’→E•,E→E•+T}
I2=GO(I0 ,T)=closure({E→T•, T→T • *F})={E→T•,T→T • *F}
I3=GO(I0 特殊的生日作文,F)=closure({T→F•})= {T→F•}
I4=GO(I0 ,( )=closure({F→(•E)})
={F→(•E),牢记使命E→•E+T,E→•T,T→•T*F,T→•F,F→•(E),F→•i}
I5=GO(I0 ,i )=closure({F→i•})= {F→i•}
得:C={I0, I1 , I2, I3 , I4 , I5}
二手烟对孕妇的危害I6=GO(I1 ,+)=closure({E关于科学的画→E+•T})
= {E→E+•T, T→•T*F,T→•F,F→•(E),F →•i}
I7=GO(I2,*)=closure({T→T*•F})
={T→T* • F,F→•(E),F →•i}
白酒的历史
I8=GO(I4 ,E)=closure({E→(E•),E→E•+T})
={E→(E•), E→E•+T}
GO(I4,T)=closure({E→T• ,T→T•*F})
= {E→T• ,T→T•*F}= I2
GO(I4 ,F)=closure({T→F•})= {T→F•}= I3
GO(I4,( )=closure({F→(•E)})
={F→(•E),E→•E+T,E→•T,T→•T*F,T→•F,F→•(E),F→•i}= I4
GO(I4,i )=closure({F→i•})= {F→i•}= I5
I9=GO(I6婚礼嘉宾致辞,T)=closure({E→E+T• , T→T•*F})
= {E→E+T•, T→T•*F}
GO(I6 ,F)=closure({T→F•})= {T→F•}= I3
GO(I6,( )=closure({F→(•E)})= I4
GO(I6,i )=closure({F→i•})= {F→i•}= I5
I10=GO(I7,F)=closure({T→T*F •})= {T→T*F •}
GO(I7,( )=closure({F→(•E)})= I4
GO(I7,i )=closure({F→i•})= {F→i•}= I5
I11=GO(I8,) )=closure({F→(E) •})= {F→(E) •}
GO(I8,+)=closure({E→E+•T})
= {E→E+•T, T→•T*F,T→•F,F→•(E),F →•i}=I6
GO(I9,*)=closure({T→T*•F}) ={T→T*•F,F→•(E),F →•i}=I7
得:C={I0, I1 , I2,…, I11}