SLR1文法分析表构建代码实现
//计算Follow集
public void Follow()
{
Dictionary<char, HashSet<char>> follow = new Dictionary<char, HashSet<char>>();//非终结符的Follow集
foreach (char c in Nchar)
{
follow[c] = new HashSet<char>();
}
follow[Nchar[0]].Add('#');//将开始符号的Follow集加入#
bool flag = true;
while (flag)
{
flag = false;
foreach (LRNode lr in LRproNum)//遍历每个产生式
{
string right = lr.Right;
int len = right.Length;
for (int i = 0; i < len; i++)
{
if (isFinalsymbol(right[i])) continue;//终结符不考虑
HashSet<char> fset = follow[right[i]];
if (i == len - 1)//如果是产生式右边的最后一个符号
{
HashSet<char> fset2 = follow[lr.Left[i]];
if (fset2.IsSupersetOf(fset)) continue;//如果已经包含了就不用再添加了
fset2.UnionWith(fset);
follow[lr.Left[i]] = fset2;
flag = true;
}
else
{
HashSet<char> fset2 = first(right.Substring(i + 1));
if (fset2.Contains('#'))//如果后继符号可以为空
{
fset2.Remove('#');
fset2.UnionWith(follow[lr.Left[i]]);
}
if (fset2.IsSubsetOf(fset)) continue;//如果已经包含了就不用再添加了
fset.UnionWith(fset2);
follow[right[i]] = fset;
flag = true;
}
}
}
}
//输出Follow集
RStr += "\r\nFollow集:\r\n";
foreach (char c in Nchar)
{
RStr += c + ": { ";
foreach (char f in follow[c])
{
RStr += f + " ";
}
RStr += "}";
RStr += "\r\n";
}
}
//计算一个字符串的First集
public HashSet<char> first(string str)
{
HashSet<char> fset = new HashSet<char>();
if (str.Length == 0) return fset;
if (isFinalsymbol(str[0]))
{
fset.Add(str[0]);
}
else
{
HashSet<char> fset2 = first(str.Substring(1));
fset.UnionWith(fset2);
if (fset2.Contains('#'))
{
fset.Remove('#');
fset.UnionWith(first(str.Substring(1)));
}
}
return fset;
}
// SLR1 分析表构建函数
public void SLRAnaly()
{
Table tnode = new Table();
LRAna = new Table[proitemset.Count][];
for (int i = 0; i < proitemset.Count; i++)
LRAna[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状态
LRAna[i][j] = tnode;
tnode = new Table('A', 0);
LRAna[1][FindID(Echar, '#')] = tnode;//项目集1必定是接受项目 构建[1][#]:acc的情况 先直接赋值好 dfa里没有
// 计算Follow集
Follow();
// 遍历所有含有归约项目的项目集
for (int i = 0; i < Gy_itemset.Count; i++)
{
// 获取当前项目集中的第一个项目
int firstItemIndex = proitemset[Gy_itemset[i]].Container[0];
// 获取第一个项目的产生式
LRNode firstItem = LRobjNum[firstItemIndex];
// 找到原产生式序号
int prodIndex = Find_pro(firstItem);
// 获取产生式右边的符号集合
HashSet<char> followSet = follow[firstItem.Left[0]];
// 遍历Follow集中的符号
foreach (char symbol in followSet)
{
// 构建r状态
tnode = new Table('r', prodIndex);
// 将r状态添加到分析表中
LRAna[Gy_itemset[i]][FindID(Echar, symbol)] = tnode;
}
}
// 遍历DFA数组
for (int i = 0; i < Pindex; i++)
{
if (isFinalsymbol(dfa[i].symbol))//symbol为非终结符 添加状态N
{
int CID = FindID(Nchar, dfa[i].symbol);
tnode = new Table('N', dfa[i].to);
LRAna[dfa[i].from][CID + Echar.Count] = tnode;
}
else //不是归约项目 添加状态S
{
int CID = FindID(Echar, dfa[i].symbol);
tnode = new Table('S', dfa[i].to);
LRAna[dfa[i].from][CID] = tnode;
}
}
}
原文地址: https://www.cveoy.top/t/topic/f0Mb 著作权归作者所有。请勿转载和采集!