SLR1 分析算法错误分析及代码修正
问题出在 SLRAnaly() 函数中,具体来说是在处理归约项目时,对于每个归约项目,都只考虑了它的左部符号的 follow 集合,而没有考虑它所在的项目集中其他符号的 follow 集合。因此,在构建分析表时,只考虑了左部符号的 follow 集合,导致分析表不正确。
改正方法是,在处理归约项目时,对于每个归约项目,需要考虑它所在的项目集中所有符号的 follow 集合,将它们全部添加到分析表中。具体来说,可以在 SLRAnaly() 函数中,在遍历项目集中的所有项目时,先将该项目集中所有符号的 follow 集合求出来,再将归约项目的左部符号的 follow 集合添加进去。这样就能正确地构建分析表了。
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 < proitemset.Count; i++)//遍历所有的项目集
{
// 获取当前项目集的所有符号的 follow 集合
List<char> allFollow = new List<char>();
foreach (int index in proitemset[i].Container)
{
SLRNode item = SLRobjNum[index];
int leftIndex = FindID(Nchar, item.Left[0]);
allFollow.AddRange(Follow[leftIndex]);
}
allFollow = allFollow.Distinct().ToList();
foreach (int index in proitemset[i].Container)//遍历项目集中的所有项目
{
SLRNode item = SLRobjNum[index];
if (item.Right == "d")//归约项目
{
foreach (char c in allFollow)
{
int CID = FindID(Echar, c);
SLRAna[i][CID] = new Table('r', Find_pro(item));
if (c == '#')
{
foreach (char e in Echar)
{
int EID = FindID(Echar, e);
SLRAna[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);
}
}
}
代码修正后,在处理归约项目时,会考虑项目集中所有符号的 follow 集合,从而保证分析表的正确性。
注意: 该代码片段仅供参考,实际代码需要根据具体的语法规则进行调整。建议读者在学习和使用 SLR1 分析算法时,仔细阅读相关资料,并进行充分的测试和验证。
原文地址: https://www.cveoy.top/t/topic/f0Kc 著作权归作者所有。请勿转载和采集!