public void CreateRecognizeTable() { foreach (NonTerminal nonterminal in LoadedNonTerminals) { foreach (Terminal terminal in LoadedTerminals) { List <Rule> rules = LoadedRules.Where(x => x.LeftPart.Name == nonterminal.Name).ToList(); foreach (Rule rule in rules) { if (CanGoFromNonTerminalToTerminal(nonterminal, terminal, rule)) { Cell cell = new Cell(rule, nonterminal, terminal); RecognizeTable.Add(cell); } } } } IEnumerable <Cell> cells = RecognizeTable.Where(x => x.Rule.RightPart[0].Name == "null"); List <Cell> removes = new List <Cell>(); foreach (Cell cell in cells) { if (RecognizeTable.Any(x => x.NonTerminal.Name == cell.NonTerminal.Name && x.Terminal.Name == cell.Terminal.Name && x.Rule.RightPart[0].Name != "null")) { removes.Add(cell); } } foreach (Cell cell in removes) { RecognizeTable.Remove(cell); } }
private bool CanGoFromNonTerminalToTerminal(NonTerminal nonTerminal, Terminal terminal, Rule rule) { if (nonTerminal.Name == rule.LeftPart.Name) { int i = 0; while (!(rule.RightPart[i] is Terminal) && !(rule.RightPart[i] is NonTerminal)) { i++; } if (rule.RightPart[i] is NonTerminal) { List <Rule> rules = LoadedRules.Where(x => x.LeftPart.Name == rule.RightPart[i].Name).ToList(); foreach (Rule rule_it in rules) { if (CanGoFromNonTerminalToTerminal(rule.RightPart[0] as NonTerminal, terminal, rule_it)) { return(true); } } return(false); } else if (rule.RightPart[i] is Terminal) { return(rule.RightPart[i].Name == terminal.Name || rule.RightPart[0].Name == "null"); } } else { throw new Exception("This rule does not correct for this non terminals"); } return(false); }
public void Load(string filepath) { IList <string> text = new List <string>(); using (StreamReader sr = new StreamReader(filepath)) { while (!sr.EndOfStream) { text.Add(sr.ReadLine()); } } if (text.Count > 0) { for (int i = 0; i < text.Count; i++) { Rule newRule = ParseString(text[i], i); LoadedNonTerminals.Add(newRule.LeftPart); foreach (IState state in newRule.RightPart) { if (state is NonTerminal) { LoadedNonTerminals.Add(state as NonTerminal); } else if (state is Terminal) { LoadedTerminals.Add(state as Terminal); } } LoadedRules.Add(newRule); } LoadedNonTerminals = LoadedNonTerminals.DistinctBy(x => x.Name).ToList(); LoadedTerminals = LoadedTerminals.DistinctBy(x => x.Name).ToList(); //CreateRecognizeTable(); } else { throw new Exception("Empty file"); } }