SLR分析表构建算法实现
{ "title": "SLR分析表构建算法实现", "description": "本文介绍了如何使用C#代码实现SLR分析表构建算法,并提供了详细的代码示例,涵盖了项目集、DFA、分析表等关键概念。", "keywords": "SLR分析表, 编译原理, C#代码, 项目集, DFA, 分析表, 构建算法", "content": "```C#
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() { //初始化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 < dfa.Length; i++)
{
if (dfa[i].from != -1 && dfa[i].to != -1 && terminals.Contains(dfa[i].symbol.ToString()))
{
int from = dfa[i].from;
int to = dfa[i].to;
int symbolIndex = terminals.IndexOf(dfa[i].symbol.ToString());
SLRAna[from][symbolIndex] = new Table('s', to);
}
}
//填充归约项
for (int i = 0; i < states.Count; i++)
{
foreach (var item in states[i].items)
{
if (item.dotIndex == item.RHS.Count)
{
int index = getproconut(item);
foreach (var symbol in isLR_0.getLR0().follow.getfollows()[item.LHS])
{
int symbolIndex = terminals.IndexOf(symbol);
SLRAna[i][symbolIndex] = new Table('r', index);
}
}
}
}
//填充接受项
int acceptIndex = terminals.IndexOf("#");
for (int i = 0; i < states.Count; i++)
{
foreach (var item in states[i].items)
{
if (item.LHS.Equals(production.Keys.First() + ''' ) && item.dotIndex == item.RHS.Count)
{
SLRAna[i][acceptIndex] = new Table('a', 0);
}
}
}
}
}
原文地址: https://www.cveoy.top/t/topic/f1PF 著作权归作者所有。请勿转载和采集!