LR(0)分析表的构造
假若一个文法G的拓广文法G¢的活前缀识别自动机中的每个状态(项目集)不存在下述情况:1) 既含移进项目又含归约项目,或者2) 含有多个归约项目,则称G是一个LR(0)文法。换言之,LR(0)文法规范族的每个项目集不包含任何冲突项目。
对于LR(0)文法,我们可直接从它的项目集规范族C和活前缀识别自动机的状态转换函数GO构造出LR分析表。下面是构造LR(0)分析表的算法。
假定C=I0,I1,…,InC=I0,I1,…,In。前面,我们已习惯用数码表示状态,因此,令每个项目集IkIk的下标kk作为分析器的状态。特别是,令那个包含项目S¢→⋅SS¢→·S的集合IkIk的下标k为分析器的初态。分析表的ACTIONACTION子表和GOTOGOTO子表可按如下方法构造:
- 若项目A→a⋅abA→a·ab属于IkIk且GO(Ik,a)=Ij,aGO(Ik,a)=Ij,a为终结符,则置ACTION[k,a]ACTION[k,a]为“把(j,aj,a)移进栈”,简记为“sjsj”。
- 若项目A→a⋅A→a·属于IkIk,那么,对任何终结符aa(或结束符#),置ACTION[k,a]ACTION[k,a]为“用产生式A→aA→a进行归约”,简记为“rjrj”(假定产生式A→aA→a是文法G¢G¢的第jj个产生式)。
- 若项目S¢→S⋅S¢→S·属于IkIk,则置ACTION[kACTION[k,#]]为“接受”,简记为“accacc”。
- 若GO(Ik,A)=Ij,AGO(Ik,A)=Ij,A为非终结符,则置GOTO[k,A]=jGOTO[k,A]=j。
- 分析表中凡不能用规则1至4填入信息的空白格均置上“报错标志”。
由于假定LR(0)LR(0)文法规范族的每个项目集不含冲突项目,因此,按上法构造的分析表的每个入口都是唯一的(即,不含多重定义)。我们称如此构造的分析表是一张LR(0)LR(0)表。使用LR(0)LR(0)表的分析器叫做一个LR(0)
LR(0)分析器。
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include