SLR 语法分析表构造方法:详细解析及 C# 实现
SLR 语法分析表构造方法:详细解析及 C# 实现
1. 引言
SLR (Simple LR) 分析法是一种自底向上的语法分析方法,它利用 LR(0) 项目集规范族和活前缀识别自动机来构建语法分析表,并根据分析表进行句子的语法分析。
2. SLR 语法分析表的构建过程
SLR 分析表的构建过程可以概括为以下步骤:
- 拓广文法: 将原文法 G 拓广为 G',添加一个新的开始符号 S' 和产生式 S' → S。
- 构造 LR(0) 项目集规范族: 对 G' 构造 LR(0) 项目集规范族 C,即所有可能的项目集的集合。
- 构造活前缀识别自动机: 根据 LR(0) 项目集规范族 C,构造活前缀识别自动机的状态转换函数 GO。
- 构造 ACTION 和 GOTO 函数: 根据 LR(0) 项目集规范族 C 和 GO 函数,构造 ACTION 和 GOTO 函数。
- 构建语法分析表: 根据 ACTION 和 GOTO 函数,构建语法分析表。
3. C# 实现 SLR 分析表构建功能
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<int> Container = new List<int>(100);
// 记录项目在项目集合中的序号
}
// 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 int Pindex = 0; // dfa 数组指针
public Table[][] SLRAna; // 分析表
public List<SLRNode> SLRproNum = new List<SLRNode>(50); // 产生式 列表
public List<SLRNode> SLRobjNum = new List<SLRNode>(50); // 项目 列表
public List<SLRitemsets> proitemset = new List<SLRitemsets>(100); // 项目集合
public List<int> Gy_obj = new List<int>(50); // 归约项目序号集合
public List<int> Gy_itemset = new List<int>(50); // 含有归约项目的集合的序号 的集合
public List<char> Nchar = new List<char>(50); // 非终结符集合
public List<char> Echar = new List<char>(50); // 终结符集合
// 构建产生式列表
public void Buildprod(string str)
{
SLRNode SLr;
int i = 0;
string left = '';
string right = '';
left += 'S';
right += str[0];
SLr = new SLRNode(left, right); // 拓广文法开始
SLRproNum.Add(SLr);
while (i < str.Length)
{
left = right = ''; // 还原
int j = i;
while (i < str.Length && str[i] != '\r' && str[i] != '\n') // 换行符 '\r\n'
{
if (str[i] == ' ')
{
i++;
continue;
}
if (str[i] == '|') // 遇到 '|' 可构造一条产生式
{
SLr = new SLRNode(left, right);
SLRproNum.Add(SLr);
right = ''; // 产生式左边相同 右边重新积累
i++; // 跳过 '|'
continue;
}
if ((i - j) == 0)
{
if (!exist(Nchar, str[i])) // 如果非终结符集合中不存在 str[i], 加入 Nchar 产生式左边 只有非终结符 不必判断终结符
Nchar.Add(str[i]);
left += str[i++];
}
else if (i - j <= 2)
i++;
else
{
if (isFinalsymbol(str[i]) && !exist(Nchar, str[i])) // 如果非终结符集合中不存在 str[i], 加入 Nchar isfinalsymbol 非终结符返回 T 终结符返回 F
Nchar.Add(str[i]);
else if (!isFinalsymbol(str[i]) && !exist(Echar, str[i])) // 产生式右边 需要判断终结符
Echar.Add(str[i]);
right += str[i++];
}
} // while
i++; // 跳过换行符
if (left != '' && right != '')
{
SLr = new SLRNode(left, right); // 构造每一行最后一个产生式,不存在 '|' 时就是该行产生式本身
SLRproNum.Add(SLr);
}
} // while
Echar.Add('#');
// 构造项目 对产生式集合 LRproNum 中的所有产生式都循环插 '.'
SLRNode Lobj;
for (i = 0; i < SLRproNum.Count; i++)
{
left = '';
right = '';
for (int j = 0; j <= SLRproNum[i].Right.Length; j++) // j 可以等于 length 项目共 length+1 个
{
left = SLRproNum[i].Left;
right = CreObj(SLRproNum[i].Right, j); // 在第 j 个位置插入 '.'
if (j == SLRproNum[i].Right.Length && SLRobjNum.Count != 1)
{ // 在产生式最后的位置插入 . 即为归约项目 项目集中 1 号位置为接受项目
Gy_obj.Add(SLRobjNum.Count); // 归约项目在项目集中的序号 不用 +1 本身就是从 0 开始的
}
Lobj = new SLRNode(left, right);
SLRobjNum.Add(Lobj);
left = ''; // 还原
right = '';
}
}
Creteitemsets(); // 项目集
RStr_obitemset += '\r\n项目集构建:\r\n';
for (int j = 0; j < proitemset.Count; j++)
{
RStr_obitemset += 'I' + j.ToString() + ':' + '\r\n';
for (i = 0; i < proitemset[j].Container.Count; i++)
{
RStr_obitemset += SLRobjNum[proitemset[j].Container[i]].Left.ToString() + '->' + SLRobjNum[proitemset[j].Container[i]].Right.ToString() + '\r\n';
}
}
}
// 求项目集
public void Creteitemsets()
{
List<int> lr_item = new List<int>(100); // 记录项目的序号
lr_item.Add(0);
lr_item = Closure(lr_item); // 构造初始项目集 求闭包
SLRitemsets LR_C = new SLRitemsets();
LR_C.Container = lr_item; // 集合----项目集序号的集合
proitemset.Add(LR_C); // 集合的集合----存放项目集序号集合 的集合
for (int i = 0; i < proitemset.Count; i++) // 整体集合中 第 i 个项目集
{
proitemset[i].Container.Sort(); // 排序由小到大 后面用于判断是否存在的比较
int[] flag = new int[proitemset[i].Container.Count];
for (int fi = 0; fi < proitemset[i].Container.Count; fi++) // 标志位,用来判断该序号是否已经构造
{
flag[fi] = 0;
}
for (int j = 0; j < proitemset[i].Container.Count; j++) // 第 i 个项目集的第 j 个项目
{
if (flag[j] == 1) // 如果已经访问过 就不再构造 找下一个项目
continue;
int index = proitemset[i].Container[j];
for (int pi = 0; pi < SLRobjNum[index].Right.Length - 1; pi++) // length-1 是避免匹配到 . 在最后的规约项目
{
if (SLRobjNum[index].Right[pi] == '.')
{
List<int> lr2_club = new List<int>(100); // 记录项目的序号
char symbol = SLRobjNum[index].Right[pi + 1]; // 记录 .a 转移状态 a. 的符号 a
lr2_club.Add((index + 1)); // 如果遇到 .a 形式的项目序号为 index 那么项目 a. 的序号为 index+1
for (int m1 = j + 1; m1 < proitemset[i].Container.Count; m1++)
{ // 在第 i 个项目集中找到了可以移动的 .:.a 重新遍历第 i 个项目集 j 项目之后的 找到同样可以移动 a 的项目集
int index2 = proitemset[i].Container[m1];
for (int m2 = 0; m2 < SLRobjNum[index2].Right.Length - 1; m2++)
{
if (SLRobjNum[index2].Right[m2] == '.' && SLRobjNum[index2].Right[m2 + 1] == symbol)
{
flag[m1] = 1; // 标记位置为 1 已经访问 之后不再访问
lr2_club.Add(index2 + 1);
}
}
}
lr2_club = Closure(lr2_club); // 求闭包
int value = isexist(lr2_club);
if (value == -1) // -1 表示不存在相同的
{
for (int m3 = 0; m3 < Gy_obj.Count; m3++)
{
if (isnexist(lr2_club, Gy_obj[m3]))
{
Gy_itemset.Add(proitemset.Count);
}
}
SLRitemsets LR_C2 = new SLRitemsets();
dfa[Pindex++] = new DFA(i, symbol, proitemset.Count); // count 不用加 1 本身从 0 开始
LR_C2.Container = lr2_club;
proitemset.Add(LR_C2);
}
else
{
dfa[Pindex++] = new DFA(i, symbol, value);
}
break;
}
}
}
}
}
// 分析表
public void SLRAnaly()
{
SLRAna = new Table[proitemset.Count][];
for (int i = 0; i < proitemset.Count; i++)
{
SLRAna[i] = new Table[Echar.Count + Nchar.Count];
for (int j = 0; j < Echar.Count + Nchar.Count; j++)
{
SLRAna[i][j] = new Table();
}
}
for (int i = 0; i < proitemset.Count; i++)
{
for (int j = 0; j < proitemset[i].Container.Count; j++)
{
int index = proitemset[i].Container[j];
string right = SLRobjNum[index].Right;
if (right.IndexOf('.') == right.Length - 1) // 规约项目
{
for (int k = 0; k < Echar.Count + Nchar.Count; k++)
{
if (SLRAna[i][k].error)
{
SLRAna[i][k] = new Table('r', index); // 规约操作
}
}
}
else
{
int pos = right.IndexOf('.') + 1; // . 的位置
char next = right[pos]; // . 后面的符号
if (isFinalsymbol(next))
{
int to = Move(proitemset[i].Container, next);
if (to != -1)
{
if (SLRAna[i][Echar.IndexOf(next)].error)
{
SLRAna[i][Echar.IndexOf(next)] = new Table('s', to); // 移进操作
}
else
{
Console.WriteLine('移进-规约冲突');
}
}
}
else
{
int to = Move(proitemset[i].Container, next);
if (to != -1)
{
if (SLRAna[i][Nchar.IndexOf(next) + Echar.Count].error)
{
SLRAna[i][Nchar.IndexOf(next) + Echar.Count] = new Table('g', to); // 转移操作
}
else
{
Console.WriteLine('转移-规约冲突');
}
}
}
}
}
}
for (int i = 0; i < Gy_itemset.Count; i++)
{
for (int j = 0; j < Echar.Count + Nchar.Count; j++)
{
if (SLRAna[Gy_itemset[i]][j].error)
{
SLRAna[Gy_itemset[i]][j] = new Table('r', Gy_obj[0]); // 归约操作
}
else
{
Console.WriteLine('归约-移进/转移冲突');
}
}
}
for (int i = 0; i < proitemset.Count; i++)
{
if (proitemset[i].Container.Contains(0))
{
SLRAna[i][Echar.IndexOf('#')] = new Table('a', 0); // 接受操作
}
}
}
// 移动函数
public int Move(List<int> itemset, char symbol)
{
List<int> newitemset = new List<int>(100);
for (int i = 0; i < itemset.Count; i++)
{
int index = itemset[i];
string right = SLRobjNum[index].Right;
if (right.IndexOf('.') != right.Length - 1 && right[right.IndexOf('.') + 1] == symbol)
{
string newright = right.Substring(0, right.IndexOf('.')) + symbol + '.' + right.Substring(right.IndexOf('.') + 2);
int newindex = isexist(new SLRNode(SLRobjNum[index].Left, newright));
if (newindex != -1)
{
newitemset.Add(newindex);
}
}
}
newitemset = Closure(newitemset);
int value = isexist(newitemset);
return value;
}
// 判断是否存在相同项目集
public int isexist(List<int> itemset)
{
for (int i = 0; i < proitemset.Count; i++)
{
if (proitemset[i].Container.Count != itemset.Count)
{
continue;
}
int flag = 1;
for (int j = 0; j < itemset.Count; j++)
{
if (!proitemset[i].Container.Contains(itemset[j]))
{
flag = 0;
break;
}
}
if (flag == 1)
{
return i;
}
}
return -1;
}
// 判断是否存在相同项目
public int isexist(SLRNode obj)
{
for (int i = 0; i < SLRobjNum.Count; i++)
{
if (SLRobjNum[i].Left == obj.Left && SLRobjNum[i].Right == obj.Right)
{
return i;
}
}
return -1;
}
// 求闭包
public List<int> Closure(List<int> itemset)
{
List<int> newitemset = new List<int>(100);
newitemset.AddRange(itemset);
for (int i = 0; i < newitemset.Count; i++)
{
int index = newitemset[i];
string right = SLRobjNum[index].Right;
if (right.IndexOf('.') != right.Length - 1)
{
char symbol = right[right.IndexOf('.') + 1];
if (!isFinalsymbol(symbol))
{
for (int j = 0; j < SLRproNum.Count; j++)
{
if (SLRproNum[j].Left == symbol.ToString())
{
string newright = '.' + SLRproNum[j].Right;
int newindex = isexist(new SLRNode(SLRproNum[j].Left, newright));
if (newindex == -1)
{
SLRNode obj = new SLRNode(SLRproNum[j].Left, newright);
SLRobjNum.Add(obj);
newindex = SLRobjNum.Count - 1;
}
if (!newitemset.Contains(newindex))
{
newitemset.Add(newindex);
}
}
}
}
}
}
return newitemset;
}
// 判断是否是终结符
public bool isFinalsymbol(char symbol)
{
return !Nchar.Contains(symbol);
}
// 判断集合中是否存在元素
public bool exist(List<char> list, char symbol)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i] == symbol)
{
return true;
}
}
return false;
}
// 判断集合中是否存在元素
public bool isnexist(List<int> list, int symbol)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i] == symbol)
{
return false;
}
}
return true;
}
// 在字符串指定位置插入 '.'
public string CreObj(string str, int i)
{
if (i < 0 || i > str.Length)
{
return str;
}
string str2 = str.Substring(0, i) + '.' + str.Substring(i, str.Length - i);
return str2;
}
}
4. 代码解释
代码中主要包含以下几个函数:
- Buildprod(string str): 构建产生式列表,并将产生式加入到 SLRproNum 中。
- Creteitemsets(): 构造项目集规范族,并将项目集加入到 proitemset 中。
- SLRAnaly(): 构建 SLR 分析表。
- Move(List
itemset, char symbol): 移动函数,根据当前项目集和符号,找到对应的下一个状态。 - isexist(List
itemset): 判断是否存在相同项目集。 - isexist(SLRNode obj): 判断是否存在相同项目。
- Closure(List
itemset): 求闭包,根据项目集中的项目,找到所有需要添加的项目。 - isFinalsymbol(char symbol): 判断是否是终结符。
- exist(List
list, char symbol): 判断集合中是否存在元素。 - isnexist(List
list, int symbol): 判断集合中是否存在元素。 - CreObj(string str, int i): 在字符串指定位置插入 '.'。
5. 总结
本文详细介绍了 SLR 语法分析表的构造方法,并使用 C# 代码实现 SLR 分析表构建功能。从拓广文法、项目集规范族到活前缀识别自动机,本文清晰讲解了 SLR 分析表的构建过程。
6. 参考资料
- 编译原理 (第四版) - 郑人杰
- 编译原理及实践 - 陈火旺
- SLR Analysis
原文地址: https://www.cveoy.top/t/topic/f1Rh 著作权归作者所有。请勿转载和采集!