SLR1 分析表构建算法实现 - C# 代码示例
public Table[][] GET_ANA() { Table[][] ana = new Table[proitemset.Count][]; for (int i = 0; i < proitemset.Count; i++) { ana[i] = new Table[Echar.Count + Nchar.Count];//每个项目集都有Echar.Count + Nchar.Count个分析表结点 for (int j = 0; j < ana[i].Length; j++) { ana[i][j] = new Table(); }
for (int j = 0; j < proitemset[i].Container.Count; j++)
{
int index = proitemset[i].Container[j];
int point = SLRobjNum[index].Right.IndexOf('.');
if (point == SLRobjNum[index].Right.Length - 1)//.在最后 归约项目
{
for (int k = 0; k < Echar.Count; k++)
{
int id = isexist(dfa, i, Echar[k]);
if (id != -1)
{
ana[i][k] = new Table('r', index);//归约
}
}
}
else
{
char next = SLRobjNum[index].Right[point + 1];
if (isFinalsymbol(next))//终结符
{
int id = isexist(dfa, i, next);
if (id != -1)
{
ana[i][Echar.IndexOf(next)] = new Table('s', id);//移进
}
}
}
}
for (int j = 0; j < Gy_obj.Count; j++)
{
int index = Gy_obj[j];
for (int k = 0; k < Follow[Nchar.IndexOf(SLRobjNum[index].Left)].Count; k++)
{
char ch = Follow[Nchar.IndexOf(SLRobjNum[index].Left)][k];
int id = isexist(dfa, i, ch);
if (id != -1)
{
ana[i][Echar.Count + Nchar.IndexOf(ch)] = new Table('r', index);//归约
}
}
}
}
return ana;
}
public void SLRAnaly()
{
Follow = new List
SLRAna = GET_ANA();
Jz = new Analyze();
Jz.stack_state.Add("0");
Jz.stack_symbol.Add("#");
Jz.Input_str.AddRange(inputStr);
while (Jz.Input_str.Count > 0)
{
int state = int.Parse(Jz.stack_state[Jz.stack_state.Count - 1]);
int symbolIndex = Echar.IndexOf(Jz.Input_str[0][0]);
if (symbolIndex == -1)
{
symbolIndex = Echar.Count + Nchar.IndexOf(Jz.Input_str[0][0]);
}
if (SLRAna[state][symbolIndex].error)
{
Success = false;
return;
}
else if (SLRAna[state][symbolIndex].type == 's')
{
Jz.stack_state.Add(SLRAna[state][symbolIndex].id.ToString());
Jz.stack_symbol.Add(Jz.Input_str[0][0].ToString());
Jz.Input_str.RemoveAt(0);
}
else if (SLRAna[state][symbolIndex].type == 'r')
{
int index = SLRAna[state][symbolIndex].id;
string left = SLRobjNum[index].Left;
string right = SLRobjNum[index].Right;
for (int i = 0; i < right.Length; i++)
{
Jz.stack_state.RemoveAt(Jz.stack_state.Count - 1);
Jz.stack_symbol.RemoveAt(Jz.stack_symbol.Count - 1);
}
int newState = int.Parse(Jz.stack_state[Jz.stack_state.Count - 1]);
Jz.stack_symbol.Add(left);
Jz.stack_state.Add(SLRAna[newState][Nchar.Count + Echar.IndexOf(left)].id.ToString());
Jz.Tran_pro.Add(left + "->" + right);
}
else
{
Success = true;
return;
}
}
Success = true;
}
原文地址: https://www.cveoy.top/t/topic/f0LW 著作权归作者所有。请勿转载和采集!