SLR 分析表构建与优化:解决归约项目显示不完整问题
代码实现了SLR分析表的构建,包括DFA的构建、项目集合的构建、归约项目的处理、Follow集合和First集合的计算以及分析表的构建。
但是在分析表中,r为表格元素的对应项只显示一部分,这是因为SLRAna数组的元素类型为Table,而Table只有type和id两个属性,无法记录归约项目对应的产生式的左部和右部。因此需要对Table类进行修改,增加记录产生式左部和右部的属性。
修改后的Table类如下:
public class Table { public bool error;//是否为ERROR public char type;//结点类型 public int id;//数值 public string left;//产生式左部 public string right;//产生式右部 public Table() { this.error = true; } public Table(char type, int id, string left, string right) { this.type = type; this.id = id; this.left = left; this.right = right; this.error = false; } }
同时,在SLRAnaly方法中,需要将归约项目对应的产生式的左部和右部记录到SLRAna数组中,修改后的代码如下:
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), item.Left, item.Right);
}
}
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, "", "");
}
}
}
修改后的SLRAnaly方法中,归约项目对应的产生式的左部和右部记录在SLRAna[Gy_itemset[i]][CID]中,可以通过SLRAna[i][j].left和SLRAna[i][j].right获取对应的产生式左部和右部。
原文地址: https://www.cveoy.top/t/topic/f0yi 著作权归作者所有。请勿转载和采集!