// public myMp(myGrammar KCgrammar) : base(new ArrayList() { "q" }, KCgrammar.T, new ArrayList() { }, "q") { this.Gamma = new ArrayList(); this.Z = new Stack(); foreach (string v1 in KCgrammar.V) // магазинные символы { Gamma.Add(v1); } foreach (string t1 in KCgrammar.T) { Gamma.Add(t1); } Q0 = Q[0].ToString(); // начальное состояние Z.Push(KCgrammar.S0); // начальный символ в магазине F = new ArrayList(); // пустое множество заключительных состояний DeltaQSigmaGamma delta = null; foreach (string v1 in KCgrammar.V) { // сопоставление правил с отображениями ArrayList q1 = new ArrayList(); ArrayList z1 = new ArrayList(); foreach (Prule rule in KCgrammar.Prules) { if (rule.leftNoTerm == v1) { Stack zb = new Stack(); ArrayList rr = new ArrayList(rule.rightChain); rr.Reverse(); foreach (string s in rr) { zb.Push(s); } z1.Add(zb); q1.Add(Q0); } } delta = new DeltaQSigmaGamma(Q0, "e", v1, q1, z1); DeltaList.Add(delta); } foreach (string t1 in KCgrammar.T) { Stack e = new Stack(); e.Push("e"); delta = new DeltaQSigmaGamma(Q0, t1, t1, new ArrayList() { Q0 }, new ArrayList() { e }); DeltaList.Add(delta); } }
static string[,] Mtable(myGrammar G) { // построение заданной таблицы string[,] t = new string[G.T.Count + G.V.Count + 2, G.T.Count + 1]; t[0, 3] = "(F+L),1"; t[1, 3] = "(L*),2"; t[1, 0] = "i,3"; t[2, 3] = "F,4"; t[2, 0] = "F,4"; t[3, 0] = "выброс"; t[4, 1] = "выброс"; t[5, 2] = "выброс"; t[6, 3] = "выброс"; t[7, 4] = "выброс"; t[8, 5] = "допуск"; return(t); }
public LLParser(myGrammar grammar) { G = grammar; Table = new DataTable("ManagerTable"); Stack = new Stack <string>(); // Создадим таблицу синтаксического анализа для этой грамматики // Определим структуру таблицы Table.Columns.Add(new DataColumn("VT", typeof(String))); foreach (string termSymbol in G.T) { Table.Columns.Add(new DataColumn(termSymbol, typeof(Prule))); } Table.Columns.Add(new DataColumn("EoI", typeof(Prule))); // Epsilon ComputeFirstSets(grammar); // Вычисляем множество First ComputeFollowSets(grammar); // Вычисляем множество Follow for (int i = 0; i < grammar.V.Count; i++) // Рассмотрим последовательно все нетерминалы { DataRow workRow = Table.NewRow(); workRow["VT"] = (string)grammar.V[i]; List <Prule> rules = getRules((string)grammar.V[i]); // Получим все правила, соответствующие текущему нетерминалу foreach (var rule in rules) { List <string> currFirstSet = First(rule.RightChain.Cast <string>().ToList()); foreach (var firstSymbol in currFirstSet) { if (firstSymbol != "") { // Добавить в таблицу workRow[firstSymbol] = rule; } else { List <string> currFollowSet = Follow(rule.leftNoTerm); foreach (var currFollowSymb in currFollowSet) { string currFollowSymbFix = (currFollowSymb == "") ? "EoI" : currFollowSymb; workRow[currFollowSymbFix] = rule; } } } } Table.Rows.Add(workRow); } }
public void ComputeFirstSets(myGrammar grammar) { for (int i = 0; i < grammar.T.Count; i++) { FirstSet[(string)grammar.T[i]] = new HashSet <string>() { grammar.T[i].ToString() } } ; // FIRST[c] = {c}*/ for (int i = 0; i < grammar.V.Count; i++) { FirstSet[(string)grammar.V[i]] = new HashSet <string>(); //First[x] = empty list } bool changes = true; while (changes) { changes = false; for (int i = 0; i < grammar.Prules.Count; ++i) { // Для каждого правила X-> Y0Y1…Yn Prule currRule = (Prule)(grammar.Prules[i]); string X = currRule.LeftNoTerm; List <string> Y = currRule.rightChain.Cast <string>().ToList(); for (int k = 0; k < Y.Count; k++) { foreach (string currFirstSymb in (HashSet <string>)FirstSet[Y[k]]) { if (((HashSet <string>)FirstSet[X]).Add(currFirstSymb)) //Добавить а в FirstSets[X] { changes = true; } } if (!((HashSet <string>)FirstSet[Y[k]]).Contains("")) { break; } } } } // пока вносятся изменения }
public void ComputeFollowSets(myGrammar grammar) { for (int i = 0; i < grammar.V.Count; i++) { FollowSet[(string)grammar.V[i]] = new HashSet <string>(); } FollowSet[G.S0] = new HashSet <string>() { "" }; bool changes = true; while (changes) { changes = false; for (int i = 0; i < grammar.Prules.Count; ++i) { // Для каждого правила X-> Y0Y1…Yn Prule currRule = (Prule)(grammar.Prules[i]); List <string> rightChain = currRule.RightChain.Cast <string>().ToList(); for (int indexOfSymbol = 0; indexOfSymbol < rightChain.Count; ++indexOfSymbol) { string currSymbol = rightChain[indexOfSymbol]; if (G.T.Contains(currSymbol)) { continue; } if (indexOfSymbol == rightChain.Count - 1) { foreach (string currFollowSymbol in (HashSet <string>)FollowSet[currRule.LeftNoTerm]) { if (((HashSet <string>)FollowSet[rightChain[indexOfSymbol]]).Add(currFollowSymbol)) { changes = true; } } } else { List <string> currFirst = First(rightChain[indexOfSymbol + 1]); bool epsFound = false; foreach (var currFirstSymbol in currFirst) { if (currFirstSymbol != "") { if (((HashSet <string>)FollowSet[rightChain[indexOfSymbol]]).Add(currFirstSymbol)) { changes = true; } } else { epsFound = true; } } if (epsFound) { foreach (string currFollowSymbol in (HashSet <string>)FollowSet[currRule.LeftNoTerm]) { if (((HashSet <string>)FollowSet[rightChain[indexOfSymbol]]).Add(currFollowSymbol)) { changes = true; } } } } } } } }
static void Main() { while (true) { Dialog(); switch (Console.ReadLine()) { case "1": myAutomate ka = new myAutomate(new ArrayList() { "S0", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "qf" }, new ArrayList() { "0", "1", "-", "+", "" }, new ArrayList() { "qf" }, "S0"); ka.AddRule("S0", "1", "A"); ka.AddRule("A", "0", "B"); ka.AddRule("B", "1", "C"); ka.AddRule("C", "0", "D"); ka.AddRule("D", "-", "E"); ka.AddRule("E", "1", "F"); ka.AddRule("F", "+", "G"); ka.AddRule("G", "0", "qf"); ka.AddRule("G", "1", "qf"); Console.WriteLine("Enter line to execute :"); ka.Execute(Console.ReadLine()); break; case "2.1": myAutomate example = new myAutomate(new ArrayList() { "S0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "qf" }, new ArrayList() { "a", "b" }, new ArrayList() { "qf" }, "S0"); example.AddRule("S0", "", "1"); example.AddRule("S0", "", "7"); example.AddRule("1", "", "2"); example.AddRule("1", "", "4"); example.AddRule("2", "a", "3"); example.AddRule("4", "b", "5"); example.AddRule("3", "", "6"); example.AddRule("5", "", "6"); example.AddRule("6", "", "1"); example.AddRule("6", "", "7"); example.AddRule("7", "a", "8"); example.AddRule("8", "b", "9"); example.AddRule("9", "b", "qf"); myAutomate dkaEX = new myAutomate(); dkaEX.BuildDeltaDKAutomate(example); dkaEX.DebugAuto(); Console.WriteLine("Enter line to execute :"); dkaEX.Execute(Console.ReadLine()); break; case "2": myAutomate ndka = new myAutomate(new ArrayList() { "S0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "qf" }, new ArrayList() { "1", "0", "+", "2" }, new ArrayList() { "qf" }, "S0"); ndka.AddRule("S0", "1", "1"); //W1 ndka.AddRule("1", "0", "2"); ndka.AddRule("2", "+", "3"); ndka.AddRule("3", "", "4"); //W2 ndka.AddRule("4", "", "5"); ndka.AddRule("4", "", "7"); ndka.AddRule("4", "", "9"); ndka.AddRule("5", "1", "6"); ndka.AddRule("7", "2", "8"); ndka.AddRule("6", "", "9"); ndka.AddRule("8", "", "9"); ndka.AddRule("9", "", "4"); ndka.AddRule("9", "", "10"); ndka.AddRule("10", "1", "11"); //W3 ndka.AddRule("11", "0", "12"); ndka.AddRule("12", "", "13"); ndka.AddRule("13", "", "9"); ndka.AddRule("13", "", "14"); ndka.AddRule("14", "", "15"); //W4 ndka.AddRule("14", "", "17"); ndka.AddRule("15", "0", "16"); ndka.AddRule("17", "1", "18"); ndka.AddRule("16", "", "19"); ndka.AddRule("18", "", "19"); ndka.AddRule("19", "", "14"); ndka.AddRule("19", "", "20"); ndka.AddRule("20", "", "15"); ndka.AddRule("14", "", "qf"); ndka.AddRule("20", "", "qf"); myAutomate dka = new myAutomate(); dka.BuildDeltaDKAutomate(ndka); dka.DebugAuto(); Console.WriteLine("Enter line to execute :"); dka.Execute(Console.ReadLine()); break; case "3": myGrammar G = new myGrammar(new ArrayList() { "a", "b", "c", "d" }, new ArrayList() { "S", "A", "B", "C", "F" }, "S"); G.AddRule("S", new ArrayList() { "b" }); G.AddRule("S", new ArrayList() { "c", "A", "B" }); G.AddRule("A", new ArrayList() { "A", "b" }); G.AddRule("A", new ArrayList() { "c" }); G.AddRule("B", new ArrayList() { "c", "B" }); G.AddRule("C", new ArrayList() { "C", "a" }); G.AddRule("F", new ArrayList() { "d" }); G.DebugPrules(); myGrammar G1 = G.unUsefulDelete(); G1.DebugPrules(); myGrammar G2 = G1.EpsDelete(); G2.DebugPrules(); myGrammar G3 = G2.ChainRuleDelete(); G3.DebugPrules(); myGrammar G4 = G3.LeftRecursDelete(); G4.DebugPrules(); // G4 - приведенная грамматика break; case "4": //МП - автоматы myGrammar kcGrammar = new myGrammar(new ArrayList() { "i", ":", "*", "(", ")" }, new ArrayList() { "S", "F", "L" }, "S"); kcGrammar.AddRule("S", new ArrayList() { "(", "F", ":", "L", ")" }); kcGrammar.AddRule("F", new ArrayList() { "L", "*" }); kcGrammar.AddRule("F", new ArrayList() { "i" }); kcGrammar.AddRule("L", new ArrayList() { "F" }); Console.Write("Debug KC-Grammar "); kcGrammar.DebugPrules(); myMp MP = new myMp(kcGrammar); Console.Write("Debug Mp "); MP.debugDelta(); Console.WriteLine("\nEnter the line :"); Console.WriteLine(MP.Execute(Console.ReadLine(), 0, 0, MP.Z).ToString()); break; case "5": // LL Разбор myGrammar exemple = new myGrammar(new ArrayList() { "i", "(", ")", "+", "*", "" }, new ArrayList() { "S", "E", "T", "T'", "P" }, "S"); exemple.AddRule("S", new ArrayList() { "T", "E" }); exemple.AddRule("E", new ArrayList() { "+", "T", "E" }); exemple.AddRule("E", new ArrayList() { "" }); exemple.AddRule("T", new ArrayList() { "P", "T'" }); exemple.AddRule("T'", new ArrayList() { "*", "P", "T'" }); exemple.AddRule("T'", new ArrayList() { "" }); exemple.AddRule("P", new ArrayList() { "(", "S", ")" }); exemple.AddRule("P", new ArrayList() { "i" }); LLParser parser = new LLParser(exemple); Console.WriteLine("Введите строку: "); if (parser.Parse(Console.ReadLine())) { Console.WriteLine("Успех. Строка соответствует грамматике."); Console.WriteLine(parser.OutputConfigure); } else { Console.WriteLine("Не успех. Строка не соответствует грамматике."); } break; case "6": ReadGrammar(); Execute(); break; case "6.1": Terminals = "+*i()"; NonTerminals = "STP"; Grammar.Add("S S+T"); Grammar.Add("S T"); Grammar.Add("T T*P"); Grammar.Add("T P"); Grammar.Add("P i"); Grammar.Add("P (S)"); Execute(); break; case "7": //МП - автоматы myMp Mp = new myMp(new ArrayList() { "q0", "q1", "q2", "qf" }, new ArrayList() { "a", "b" }, new ArrayList() { "z0", "a" }, "q0", new ArrayList() { "qf" }); Mp.addDeltaRule("q0", "a", "z0", new ArrayList() { "q1" }, new ArrayList() { "a", "z0" }); Mp.addDeltaRule("q1", "a", "a", new ArrayList() { "q1" }, new ArrayList() { "a", "a" }); Mp.addDeltaRule("q1", "b", "a", new ArrayList() { "q2" }, new ArrayList() { "e" }); Mp.addDeltaRule("q2", "b", "a", new ArrayList() { "q2" }, new ArrayList() { "e" }); Mp.addDeltaRule("q2", "e", "z0", new ArrayList() { "qf" }, new ArrayList() { "e" }); Console.Write("Debug Mp "); Mp.debugDelta(); Console.WriteLine("\nEnter the line :"); Console.WriteLine(Mp.Execute_(Console.ReadLine()).ToString()); break; } } }
static int parsing(string s, int c, myGrammar G) { // алгоритм разбора Stack z = new Stack(); // магазин string eline = null; string zline = null; string qline = null; z.Push("$"); z.Push(s); string[,] table = Mtable(G); // таблица ArrayList outstr = new ArrayList(); // выходная лента int i, j; bool d = false; // допуск for (int k = 0; k < s.Length + 1; k++) { if (c == 0) { return(3); // разбор по шагам } if (k == s.Length) { j = G.T.Count; // символ пустой строки } else { if (!G.T.Contains(s[k].ToString())) { d = false; break; } // не символ алфавита j = G.T.IndexOf(s[k].ToString()); // выбор столбца } if (G.V.Contains(z.Peek())) { i = G.V.IndexOf(z.Peek()); // выбор строки } else if (z.Peek().ToString() == "$") { i = G.T.Count + G.V.Count; } else { i = G.T.IndexOf(z.Peek()) + G.V.Count; } if (k != s.Length + 1) { // вывод на экран eline = ""; zline = ""; qline = ""; for (int m = k; m < s.Length; m++) { eline = eline + (s[m].ToString()); } Stack z1 = new Stack(); while (z.Count != 0) { zline = zline + (z.Peek().ToString()); z1.Push(z.Pop()); } while (z1.Count != 0) { z.Push(z1.Pop()); } foreach (string o in outstr) { qline = qline + o; } } if (table[i, j] == "выброс") { z.Pop(); continue; } // выброс символа else if (table[i, j] == "допуск") { d = true; break; } // допуск строки else if (table[i, j] == null) { d = false; break; } // ошибка else { // запись в магазин и на выходную ленту int zp = table[i, j].IndexOf(','); // разбор ячейки таблицы до запятой z.Pop(); for (int l = zp - 1; l >= 0; l--) { z.Push(table[i, j][l].ToString()); // в магазин } outstr.Add(table[i, j][zp + 1].ToString()); // на ленту k--; } c--; } if (d) { return(1); } else { return(2); } }