SLR1 分析表构建问题分析及修正
在 SLR 分析表的构建过程中,需要为每个含有归约项目的项目集合添加归约状态。在代码中,这个步骤被遗漏了,导致分析表中没有正确地添加归约状态。需要在 SLRAnaly() 方法中添加以下代码:
for (int i = 0; i < Gy_itemset.Count; i++)
{
SLRNode item = SLRobjNum[proitemset[Gy_itemset[i]].Container[0]];
char left = item.Left[0];
List<char> follow = GetFollow(left);
foreach (char c in follow)
{
int CID = FindID(Echar, c);
SLRAna[Gy_itemset[i]][CID] = new Table('r', Find_pro(item));
if (c == '#')
{
foreach (char e in Echar)
{
int EID = FindID(Echar, e);
SLRAna[Gy_itemset[i]][EID] = new Table('r', Find_pro(item));
}
}
}
}
这段代码会遍历所有含有归约项目的项目集合,获取该项目集合中第一个项目的左部符号,并计算其 Follow 集合。然后遍历 Follow 集合,为分析表中对应的终结符添加归约状态。注意,如果 Follow 集合中包含结束符号“#”,则需要为所有终结符都添加归约状态。
修改后的 SLRAnaly() 方法如下:
public void SLRAnaly()
{
Table tnode = new Table();
SLRAna = new Table[proitemset.Count][];
for (int i = 0; i < proitemset.Count; i++)
SLRAna[i] = new Table[Echar.Count + Nchar.Count];
for (int i = 0; i < proitemset.Count; i++)//初始化 赋予ERROR属性
for (int j = 0; j < Echar.Count + Nchar.Count; j++)//为终结符加r状态
SLRAna[i][j] = tnode;
tnode = new Table('A', 0);
SLRAna[1][FindID(Echar, '#')] = tnode;//项目集1必定是接受项目 构建[1][#]:acc的情况 先直接赋值好 dfa里没有
for (int i = 0; i < Gy_itemset.Count; i++)
{
SLRNode item = SLRobjNum[proitemset[Gy_itemset[i]].Container[0]];
char left = item.Left[0];
List<char> follow = GetFollow(left);
foreach (char c in follow)
{
int CID = FindID(Echar, c);
SLRAna[Gy_itemset[i]][CID] = new Table('r', Find_pro(item));
if (c == '#')
{
foreach (char e in Echar)
{
int EID = FindID(Echar, e);
SLRAna[Gy_itemset[i]][EID] = new Table('r', Find_pro(item));
}
}
}
}
for (int i = 0; i < Pindex; i++)
{
if (isFinalsymbol(dfa[i].symbol))//symbol为非终结符 添加状态N
{
int CID = FindID(Nchar, dfa[i].symbol);
SLRAna[dfa[i].from][CID + Echar.Count] = new Table('N', dfa[i].to);
}
else //不是归约项目 添加状态S
{
int CID = FindID(Echar, dfa[i].symbol);
SLRAna[dfa[i].from][CID] = new Table('S', dfa[i].to);
}
}
}
原文地址: https://www.cveoy.top/t/topic/f0NR 著作权归作者所有。请勿转载和采集!