LR(0)和SLR(1)分析表构造算法及代码实现
LR(0)和SLR(1)分析表构造算法及代码实现
本文介绍了LR(0)和SLR(1)分析表的构造算法,并提供了C#代码实现。代码包含了LRNode、LRitemsets、DFA、Table等类的定义,以及Closure、LRAnaly、GET_ANA、FirstFollow等函数的实现。
LR(0)分析表构造算法
- 构造增广文法: 在原始文法的开始符号前添加一个新的非终结符,并将新的非终结符作为文法的开始符号。2. 构造项目集规范族: 从增广文法的开始项目开始,不断地应用闭包运算和转移运算,直到得到项目集规范族。3. 构造LR(0)分析表: 根据项目集规范族,构造LR(0)分析表。
SLR(1)分析表构造算法
- 构造增广文法: 与LR(0)相同。2. 计算First集和Follow集: 计算每个非终结符的First集和Follow集。3. 构造项目集规范族: 与LR(0)类似,但在进行闭包运算时,需要考虑展望符。4. 构造SLR(1)分析表: 根据项目集规范族和Follow集,构造SLR(1)分析表。
代码实现C#// LR(0)分析表相关代码
public class LRNode{ public string Left; public string Right; public LRNode(string Left, string Right) { this.Left = Left; this.Right = Right; }}
public class LRitemsets{ public List
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; 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 List
public void LRAnaly(){ // ... 实现LR(0)分析表构造算法 ...}
public Table[][] GET_ANA(){ // ... 获取LR(0)分析表 ...}
// SLR(1)分析表相关代码
public class SLRNode{ public string Left; public string Right; public HashSet
public class SLRitemsets{ public List
public struct DFA{ public int from; public char symbol; public int to; public HashSet
// ... 其他变量和函数定义 ...
public void FirstFollow(){ // ... 计算First集和Follow集 ...}
public List
public void SLRAnaly(){ // ... 实现SLR(1)分析表构造算法 ...}
public Table[][] GET_ANA(){ // ... 获取SLR(1)分析表 ..
原文地址: https://www.cveoy.top/t/topic/f0N5 著作权归作者所有。请勿转载和采集!