private void PrintBasicResult() { initView(); for (int i = 0; i < grammer.GrammerRuleSet.Count; i++) { ListViewItem item = proListView.Items.Add((i + 1).ToString()); GrammerRule grammerRule = grammer.GrammerRuleSet[i]; item.SubItems.Add(grammerRule.ToString()); } for (int i = 0; i < grammer.VertexNonterminalSet.Count; i++) { ListViewItem item = nonterminalListView.Items.Add((i + 1).ToString()); item.SubItems.Add(grammer.VertexNonterminalSet[i].ToString()); } for (int i = 0; i < grammer.VertexTerminatorSet.Count; i++) { ListViewItem item = this.terminalListView.Items.Add((i + 1).ToString()); item.SubItems.Add(grammer.VertexTerminatorSet[i].ToString()); } foreach (var first in grammer.First) { ListViewItem item = this.FirstListView.Items.Add(String.Format("{0}", first.Key)); string str = "{ "; foreach (var v in first.Value) { str += v.ToString() + ","; } str = str.Remove(str.Length - 1) + " }"; item.SubItems.Add(str); } }
public PythonGrammer() { Rules = new GrammerRule[] { new GrammerRule(TokenType.Comment, new Regex("^(#.*)")), // Comment new GrammerRule(TokenType.WhiteSpace, new Regex("^\\s")), // Whitespace //new GrammerRule(TokenType.Operator, new Regex("^(and|or|not|is)\\b")), // Word Operator new GrammerRule(TokenType.Operator, new Regex("^[\\+\\-\\*/%&|\\^~<>!]")), // Single Char Operator new GrammerRule(TokenType.Operator, new Regex("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))")), // Double Char Operator new GrammerRule(TokenType.Delimiter, new Regex("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]")), // Single Delimiter new GrammerRule(TokenType.Delimiter, new Regex("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))")), // Double Char Operator new GrammerRule(TokenType.Delimiter, new Regex("^((//=)|(>>=)|(<<=)|(\\*\\*=))")), // Triple Delimiter new GrammerRule(TokenType.Identifier, new Regex("^[_A-Za-z][_A-Za-z0-9]*")), // Identifier new GrammerRule(TokenType.String, new Regex("^((\"\"\"(.*)\"\"\")|('''(.)*'''))", RegexOptions.IgnoreCase | RegexOptions.Multiline)), new GrammerRule(TokenType.String, new Regex("^((@'(?:[^']|'')*'|'(?:\\.|[^\\']|)*('|\\b))|(@\"(?:[^\"]|\"\")*\"|\"(?:\\.|[^\\\"])*(\"|\\b)))", RegexOptions.IgnoreCase | RegexOptions.Singleline)), // String Marker }; Keywords = new string[] { "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in", "print", "and", "or", "not" }; Builtins = new string[] { "ArithmeticError", "AssertionError", "AttributeError", "BaseException", "BufferError", "BytesWarning", "DeprecationWarning", "EOFError", "Ellipsis", "EnvironmentError", "Exception", "False", "FloatingPointError", "FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning", "IndentationError", "IndexError", "KeyError", "KeyboardInterrupt", "LookupError", "MemoryError", "NameError", "None", "NotImplemented", "NotImplementedError", "OSError", "OverflowError", "PendingDeprecationWarning", "ReferenceError", "RuntimeError", "RuntimeWarning", "StandardError", "StopIteration", "SyntaxError", "SyntaxWarning", "SystemError", "SystemExit", "TabError", "True", "TypeError", "UnboundLocalError", "UnicodeDecodeError", "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError", "UnicodeWarning", "UserWarning", "ValueError", "Warning", "WindowsError", "ZeroDivisionError", "_", "__debug__", "__doc__", "__import__", "__name__", "__package__", "abs", "all", "any", "apply", "basestring", "bin", "bool", "buffer", "bytearray", "bytes", "callable", "chr", "classmethod", "cmp", "coerce", "complex", "copyright", "credits", "delattr", "dict", "divmod", "enumerate", "filter", "float", "format", "frozenset", "getattr", "hasattr", "hash", "hex", "id", "int", "intern", "isinstance", "issubclass", "iter", "len", "license", "list", "long", "map", "max", "memoryview", "min", "next", "object", "oct", "ord", "pow", "print", "property", "range", "raw_input", "reduce", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "unichr", "unicode", "xrange", "zip" }; }
public ProductionManager(string grammerContext, string[] deriver = null) { this.VertexNonterminalSet = new List <VertexNonterminal>(); this.VertexTerminatorSet = new List <VertexTerminator>(); this.GrammerRuleSet = new List <GrammerRule>(); List <String> textLines = grammerContext.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (textLines.Count == 0) { throw new IllegalGrammerException("语法为空"); } if (deriver == null) { deriver = new String[] { "->", "→" } } ; foreach (var textLine in textLines) { int iComment = textLines.IndexOf("//"); string realTextLine = iComment >= 0 ? textLine.Substring(0, iComment) : textLine; if (string.IsNullOrWhiteSpace(realTextLine)) { continue; } string[] ruleArray = realTextLine.Split(deriver, StringSplitOptions.RemoveEmptyEntries); if (ruleArray == null) { throw new IllegalGrammerException("无法分析的产生式"); } string strLeft = ruleArray[0]; string[] strRights = ruleArray[1].Split('|'); if (strLeft.Length != 1 || strLeft.ToUpper() != strLeft) { throw new IllegalGrammerException("推导符左边应该为一个大写字母作为非终结符"); } VertexNonterminal ruleLeft = this.AddVertexNonterminal(strLeft[0]); foreach (string strRight in strRights) { List <Vertex> ruleRight = new List <Vertex>(); foreach (char charVertex in strRight) { if ('A' <= charVertex && charVertex <= 'Z') { ruleRight.Add(this.AddVertexNonterminal(charVertex)); } else { ruleRight.Add(this.AddVertexTerminator(charVertex)); } } GrammerRule newRule = new GrammerRule(ruleLeft, ruleRight); newRule.IsAcceptRule = false; this.GrammerRuleSet.Add(newRule); } } if (this.GrammerRuleSet.Count == 0) { throw new IllegalGrammerException("语法为空"); } this.VertexTerminatorSet.Add(VertexTerminator.End); this.GrammerRuleSet[0].IsAcceptRule = true; }