SLR 分析表构建算法实现 - C# 代码示例
{ "title": "SLR 分析表构建算法实现 - C# 代码示例", "description": "本文介绍了使用 C# 语言实现 SLR 分析表构建算法的代码示例,包括类定义、算法实现和相关函数的调用。", "keywords": "SLR 分析表, LR(0) 分析表, 编译原理, 形式语言, C#", "content": "```c# using System; using System.Collections.Generic; using System.Linq;
public class SLR
{
//产生式结点类
public class SLRNode
{
public string Left;
public string Right;
public SLRNode(string Left, string Right)
{
this.Left = Left;
this.Right = Right;
}
}
//项目集类
public class SLRitemsets
{
public List
//DFA结点
public struct DFA
{
public int from;
public char symbol;
public int to;
public DFA(int from, char symbol, int to)
{
this.from = from;
this.symbol = symbol;
this.to = to;
}
}
//分析表 结点
public class Table
{
public bool error;//是否为ERROR
public char type;//结点类型
public int id;//数值
public Table()
{
this.error = true;
}
public Table(char type, int id)
{
this.type = type;
this.id = id;
this.error = false;
}
}
public DFA[] dfa = new DFA[100];
public Table[][] SLRAna;//分析表
public void SLRAnaly()
{
//获取LR(0)分析表
buildtable();
//初始化SLR分析表
SLRAna = new Table[states.Count][];
for (int i = 0; i < states.Count; i++)
{
SLRAna[i] = new Table[terminals.Count + nonterminal.Count];
for (int j = 0; j < terminals.Count + nonterminal.Count; j++)
{
SLRAna[i][j] = new Table();
}
}
//填充移进项和归约项
for (int i = 0; i < states.Count; i++)
{
for (int j = 0; j < terminals.Count; j++)
{
if (table[i][j] != "")
{
if (table[i][j][0] == 'S')
{
int nextstate = int.Parse(table[i][j].Substring(1));
SLRAna[i][j].type = 's';
SLRAna[i][j].id = nextstate;
}
else if (table[i][j][0] == 'r')
{
int productionIndex = int.Parse(table[i][j].Substring(1));
List<string> productionRHS = productions[production.Keys.ToList()[productionIndex - 1]][0];
string productionLHS = production.Keys.ToList()[productionIndex - 1];
int reduceState = -1;
for (int k = 0; k < states.Count; k++)
{
if (states[k].items.Any(item => item.LHS == productionLHS && item.RHS.SequenceEqual(productionRHS)))
{
reduceState = k;
break;
}
}
SLRAna[i][j].type = 'r';
SLRAna[i][j].id = reduceState;
}
}
}
}
//填充goto项
for (int i = 0; i < states.Count; i++)
{
for (int j = 0; j < nonterminal.Count; j++)
{
int nextState = -1;
if (transitions.ContainsKey(i))
{
foreach (var item in transitions[i])
{
if (item[0].ToString().Equals(nonterminal[j]))
{
nextState = int.Parse(item.Substring(1));
break;
}
}
}
if (nextState != -1)
{
SLRAna[i][terminals.Count + j].type = 'g';
SLRAna[i][terminals.Count + j].id = nextState;
}
}
}
}
//以下为LR(0)分析表的构建代码
//省略...
}
原文地址: https://www.cveoy.top/t/topic/f1PC 著作权归作者所有。请勿转载和采集!