private List productions = new List(); // 存储文法产生式 private List symbols = new List(); // 存储文法符号 private List states = new List(); // 存储状态 private List itemsets = new List(); // 存储项目族 private Dictionary<string, List> gotoTable = new Dictionary<string, List>(); // 存储GOTO表 private Dictionary<string, List> actionTable = new Dictionary<string, List>(); // 存储ACTION表 private void button2_Click(object sender, EventArgs e)//判别LR0文法 { // 读取文法产生式 string[] productionsArr = richTextBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); productions.AddRange(productionsArr);

// 获取文法符号
foreach (string production in productions)
{
    string[] parts = production.Split(' ');
    foreach (string part in parts)
    {
        if (!symbols.Contains(part))
        {
            symbols.Add(part);
        }
    }
}

// 初始化状态0
string state0 = "S' -> .S";
itemsets.Add(state0);
states.Add(GetState(itemsets));

BuilditemFamily();

} private void BuilditemFamily() { bool changed = true; while (changed) { changed = false; for (int i = 0; i < itemsets.Count; i++) { List items = itemsets[i].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (string symbol in symbols) { List newItems = new List(); foreach (string item in items) { string[] parts = item.Split(' '); int dotIndex = Array.IndexOf(parts, "."); if (dotIndex != -1 && dotIndex < parts.Length - 1 && parts[dotIndex + 1] == symbol) { string newItem = item.Replace(". ' + symbol, symbol + ' ."); if (!newItems.Contains(newItem)) { newItems.Add(newItem); } } } if (newItems.Count > 0) { string newState = GetState(newItems); if (!states.Contains(newState)) { states.Add(newState); itemsets.Add(newState); changed = true; } int index = states.IndexOf(newState); if (!gotoTable.ContainsKey(i + "," + symbol)) { gotoTable.Add(i + "," + symbol, new List()); } if (!gotoTable[i + "," + symbol].Contains(index.ToString())) { gotoTable[i + "," + symbol].Add(index.ToString()); } } } } } }

LR(0) 分析器:项目族信息生成函数 BuilditemFamily() 代码实现

原文地址: https://www.cveoy.top/t/topic/fZEb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录