SLR(1)分析器的Follow集计算与分析表构建
//获取非终结符的Follow集
public Dictionary<char, HashSet
//初始化
foreach (char ch in Nchar)
{
follow.Add(ch, new HashSet<char>());
}
follow['S\''] = new HashSet<char>{'#'};
bool change = true;
while (change)
{
change = false;
for (int i = 0; i < SLRproNum.Count; i++)
{
string right = SLRproNum[i].Right;
char left = SLRproNum[i].Left[0];
for (int j = 0; j < right.Length; j++)
{
if (!Nchar.Contains(right[j]))
continue;
if (j == right.Length - 1)
{//A->αB, Follow(B) = Follow(B) U Follow(A)
foreach (char ch in follow[left])
{
if (!follow[right[j]].Contains(ch))
{
follow[right[j]].Add(ch);
change = true;
}
}
}
else
{//A->αBβ, Follow(B) = Follow(B) U First(β) - ε
HashSet<char> first = GetFirst(right.Substring(j + 1), Vt, follow);
foreach (char ch in first)
{
if (!follow[right[j]].Contains(ch))
{
follow[right[j]].Add(ch);
change = true;
}
}
if (first.Contains('#'))
{
foreach (char ch in follow[left])
{
if (!follow[right[j]].Contains(ch))
{
follow[right[j]].Add(ch);
change = true;
}
}
}
}
}
}
}
return follow;
}
//获取字符串的First集
public HashSet
for (int i = 0; i < str.Length; i++)
{
if (!Nchar.Contains(str[i]))
{
first.Add(str[i]);
return first;
}
else
{
HashSet<char> temp = new HashSet<char>(GetFirst(CreObj(str, i + 1), Vt, follow));
first.UnionWith(temp);
if (!temp.Contains('#'))
return first;
}
}
first.Add('#');
return first;
}
原文地址: https://www.cveoy.top/t/topic/f0NJ 著作权归作者所有。请勿转载和采集!