Exemplo n.º 1
0
        public BackOGrammar_old() : base(false)
        {
            var lineComment = new CommentTerminal("line_comment", "--", "\n", "\r\n");

            NonGrammarTerminals.Add(lineComment);

            var number         = new NumberLiteral("number");
            var string_literal = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote);
            var Id_simple      = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple");        //covers normal identifiers (abc) and quoted id's ([abc d], "abc d")
            var comma          = ToTerm(",");
            var dot            = ToTerm(".");
            var CREATE         = ToTerm("CREATE");
            var NULL           = ToTerm("NULL");
            var NOT            = ToTerm("NOT");
            //var ADD = ToTerm("ADD");
            //var COLUMN = ToTerm("COLUMN");
            var UPDATE = ToTerm("UPDATE");
            var SET    = ToTerm("SET");
            var DELETE = ToTerm("DELETE");
            var SELECT = ToTerm("SELECT");
            var FROM   = ToTerm("FROM");
            var COUNT  = ToTerm("COUNT");
            var JOIN   = ToTerm("JOIN");
            //var BY = ToTerm("BY");
        }
Exemplo n.º 2
0
 /// <summary>
 /// Constructor for the master grammar class.
 /// </summary>
 protected MasterGrammar() : base(false)
 {
     LanguageFlags = LanguageFlags.NewLineBeforeEOF | LanguageFlags.CreateAst;
     MarkPunctuation("(", ")");
     NonGrammarTerminals.Add(new CommentTerminal("Comment specification", ";", "\r", "\n", Environment.NewLine));
     Root = null;
 }
Exemplo n.º 3
0
        public ASLGrammar()
            : base(true)
        {
            var string_lit = TerminalFactory.CreateCSharpString("string");
            var number     = TerminalFactory.CreateCSharpNumber("number");
            var identifier = TerminalFactory.CreateCSharpIdentifier("identifier");
            var code       = new CustomTerminal("code", MatchCodeTerminal);

            var single_line_comment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimited_comment   = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(single_line_comment);
            NonGrammarTerminals.Add(delimited_comment);

            var state     = new KeyTerm("state", "state");
            var init      = new KeyTerm("init", "init");
            var exit      = new KeyTerm("exit", "exit");
            var update    = new KeyTerm("update", "update");
            var start     = new KeyTerm("start", "start");
            var split     = new KeyTerm("split", "split");
            var reset     = new KeyTerm("reset", "reset");
            var startup   = new KeyTerm("startup", "startup");
            var shutdown  = new KeyTerm("shutdown", "shutdown");
            var isLoading = new KeyTerm("isLoading", "isLoading");
            var gameTime  = new KeyTerm("gameTime", "gameTime");
            var comma     = ToTerm(",", "comma");
            var semi      = ToTerm(";", "semi");

            var root        = new NonTerminal("root");
            var state_def   = new NonTerminal("stateDef");
            var version     = new NonTerminal("version");
            var state_list  = new NonTerminal("stateList");
            var method_list = new NonTerminal("methodList");
            var var_list    = new NonTerminal("varList");
            var var         = new NonTerminal("var");
            var module      = new NonTerminal("module");
            var method      = new NonTerminal("method");
            var offset_list = new NonTerminal("offsetList");
            var offset      = new NonTerminal("offset");
            var method_type = new NonTerminal("methodType");

            root.Rule        = state_list + method_list;
            version.Rule     = (comma + string_lit) | Empty;
            state_def.Rule   = state + "(" + string_lit + version + ")" + "{" + var_list + "}";
            state_list.Rule  = MakeStarRule(state_list, state_def);
            method_list.Rule = MakeStarRule(method_list, method);
            var_list.Rule    = MakeStarRule(var_list, semi, var);
            module.Rule      = (string_lit + comma) | Empty;
            var.Rule         = (identifier + identifier + ":" + module + offset_list) | Empty;
            method.Rule      = (method_type + "{" + code + "}") | Empty;
            offset_list.Rule = MakePlusRule(offset_list, comma, offset);
            offset.Rule      = number;
            method_type.Rule = init | exit | update | start | split | isLoading | gameTime | reset | startup | shutdown;

            Root = root;

            MarkTransient(var_list, method_list, offset, method_type);

            LanguageFlags = LanguageFlags.NewLineBeforeEOF;
        }
Exemplo n.º 4
0
        public XmlGrammar()
            : base(false)
        {
            LanguageFlags = LanguageFlags.CreateAst;
            NonGrammarTerminals.Add(new CommentTerminal("comment", "<%--", "--%>"));

            var element        = Transient("element", null);
            var identifier     = Identifier();
            var attributesList = AttributesList(identifier);
            var xmlText        = new XmlTextTerminal(new List <Terminal> {
                ToTerm(">"), ToTerm("/>")
            },
                                                     (context, node) => node.AstNode = new XmlText {
                Content = node.FindTokenAndGetText()
            });
            var tag          = Tag(identifier, attributesList, element);
            var directive    = Directive(identifier, attributesList);
            var codeFragment = CodeFragment();
            var document     = NonTerminal("document", null, node => new AspNetXmlDocument
            {
                Elements = node.ChildNodes.Select(c => c.AstNode).Cast <ITagContent>().ToList()
            });

            element.Rule  = tag | directive | codeFragment | xmlText;
            document.Rule = MakeStarRule(document, element);
            Root          = document;
        }
Exemplo n.º 5
0
        public JsonGrammar(Domain domain)
            : base(domain)
        {
            B = new BnfTerms(new TerminalFactoryS(this));

            this.Root = B.Object;

            B.Object.Rule =
                B.NUMBER + SetUnparsePriority((astValue, childAstValues) => astValue is int || astValue is double?(int?)1 : null)
                |
                B.STRING
                |
                B.BOOLEAN
                |
                B.Array
                |
                B.NULL + SetUnparsePriority((astValue, childAstValues) => astValue == null ? (int?)1 : null)
                |
                B.OBJECT_BEGIN
                + B.KeyValuePairs.ConvertValue(KeyValuePairsToObject, ObjectToKeyValuePairs)
                + B.OBJECT_END
            ;

            B.KeyValuePairs.Rule =
                B.KeyValuePair.PlusList(B.COMMA)
            ;

            B.KeyValuePair.Rule =
                B.Key.BindTo(B.KeyValuePair, fv => fv.Key)
                + B.COLON
                + B.Value.BindTo(B.KeyValuePair, fv => fv.Value);

            B.Key.Rule =
                B.STRING
            ;

            B.Value.Rule =
                B.Object
            ;

            B.Array.Rule =
                B.ARRAY_BEGIN
                + B.ArrayElements.BindTo(B.Array, metaArray => metaArray.Elements)
                + B.ARRAY_END
            ;

            B.ArrayElements.Rule =
                B.Object.StarListTL(B.COMMA)
            ;

            RegisterBracePair(B.OBJECT_BEGIN, B.OBJECT_END);
            RegisterBracePair(B.ARRAY_BEGIN, B.ARRAY_END);

            // TODO: although JSON does not have comments, we define C-style comments for until we solve parsing and unparsing of comments into JSON data
            CommentTerminal DelimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");
            CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", Environment.NewLine, "\n", "\r");

            NonGrammarTerminals.Add(DelimitedComment);
            NonGrammarTerminals.Add(SingleLineComment);
        }
Exemplo n.º 6
0
        public XmlGrammar()
            : base(false)
        {
            //Terminals
            Terminal comment = new CommentTerminal("comment", "<!--", "-->");

            NonGrammarTerminals.Add(comment);
            StringLiteral stringLiteral          = new StringLiteral("string", "\"", StringOptions.None);
            Terminal      stringContent          = new ToTerminatorTerminal("StringContent", '<');
            KeyTerm       elementOpener          = ToTerm("<");
            KeyTerm       closeElementOpener     = ToTerm("</");
            KeyTerm       elementCloser          = ToTerm(">");
            KeyTerm       openCloseElementCloser = ToTerm("/>");
            KeyTerm       equals       = ToTerm("=");
            KeyTerm       xmlDeclOpen  = ToTerm("<?");
            KeyTerm       xmlDeclClose = ToTerm("?>");

            IdentifierTerminal attributeIdentifier      = new IdentifierTerminal(AttributeIdentifier, ".", ".");
            IdentifierTerminal elementIdentifier        = new IdentifierTerminal(ElementIdentifier, ".-", ".-");
            KeyTerm            xmlDeclarationIdentifier = ToTerm("xml");

            //Non Terminals
            NonTerminal document               = new NonTerminal("document");
            NonTerminal elementStart           = new NonTerminal("ElementStart");
            NonTerminal elementEnd             = new NonTerminal("ElementEnd");
            NonTerminal openCloseElement       = new NonTerminal("OpenCloseElement");
            NonTerminal element                = new NonTerminal("Element");
            NonTerminal requiredElements       = new NonTerminal("RequiredElements");
            NonTerminal innerContent           = new NonTerminal("InnerContent");
            NonTerminal content                = new NonTerminal("Content");
            NonTerminal attribute              = new NonTerminal("Attribute");
            NonTerminal optionalAttribute      = new NonTerminal("OptionalAttribute");
            NonTerminal xmlDeclaration         = new NonTerminal("XmlDeclaration");
            NonTerminal optionalXmlDeclaration = new NonTerminal("OptionalXmlDeclaration");

            //Rules
            this.Root = document;

            innerContent.Rule = element | stringContent;
            content.Rule      = MakeStarRule(content, innerContent);

            attribute.Rule         = attributeIdentifier + equals + stringLiteral;
            optionalAttribute.Rule = MakeStarRule(optionalAttribute, attribute);

            elementStart.Rule     = elementOpener + elementIdentifier + optionalAttribute + elementCloser;
            elementEnd.Rule       = closeElementOpener + elementIdentifier + elementCloser;
            openCloseElement.Rule = elementOpener + elementIdentifier + optionalAttribute + openCloseElementCloser;

            element.Rule          = (elementStart + content + elementEnd) | openCloseElement;
            requiredElements.Rule = MakePlusRule(requiredElements, element);

            xmlDeclaration.Rule         = xmlDeclOpen + xmlDeclarationIdentifier + optionalAttribute + xmlDeclClose;
            optionalXmlDeclaration.Rule = MakeStarRule(optionalXmlDeclaration, xmlDeclaration);

            document.Rule = optionalXmlDeclaration + requiredElements;

            MarkPunctuation(elementOpener, elementCloser, closeElementOpener, openCloseElementCloser, equals, xmlDeclOpen, xmlDeclClose);
            MarkTransient(innerContent);
        }
Exemplo n.º 7
0
        private void Comments()
        {
            var comment     = new CommentTerminal("multiline_comment", "/*", "*/");
            var lineComment = new CommentTerminal("singleline_comment", "--", "\n", "\r\n");

            NonGrammarTerminals.Add(comment);
            NonGrammarTerminals.Add(lineComment);
        }
        public VASLGrammar() : base(true)
        {
            var code       = new CustomTerminal("code", MatchCodeTerminal);
            var stringLit  = TerminalFactory.CreateCSharpString("string");
            var identifier = TerminalFactory.CreateCSharpIdentifier("identifier");
            var number     = TerminalFactory.CreateCSharpNumber("number");

            number.Options |= NumberOptions.AllowSign;

            var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(delimitedComment);

            // Todo: Aliases

            var init      = new KeyTerm("init", "init");
            var exit      = new KeyTerm("exit", "exit");
            var update    = new KeyTerm("update", "update");
            var start     = new KeyTerm("start", "start");
            var split     = new KeyTerm("split", "split");
            var reset     = new KeyTerm("reset", "reset");
            var startup   = new KeyTerm("startup", "startup");
            var shutdown  = new KeyTerm("shutdown", "shutdown");
            var undoSplit = new KeyTerm("undoSplit", "undoSplit");
            var isLoading = new KeyTerm("isLoading", "isLoading");
            var gameTime  = new KeyTerm("gameTime", "gameTime");
            var comma     = ToTerm(",", "comma");
            var semi      = ToTerm(";", "semi");

            var root       = new NonTerminal("root");
            var version    = new NonTerminal("version");
            var methodList = new NonTerminal("methodList");
            var varList    = new NonTerminal("varList");
            var var        = new NonTerminal("var");
            var method     = new NonTerminal("method");
            var methodType = new NonTerminal("methodType");

            root.Rule       = methodList;
            version.Rule    = (comma + stringLit) | Empty;
            methodList.Rule = MakeStarRule(methodList, method);
            varList.Rule    = MakeStarRule(varList, semi, var);
            method.Rule     = (methodType + "{" + code + "}") | Empty;
            methodType.Rule = init | exit | update | start | split | isLoading | gameTime | reset | startup | shutdown | undoSplit;

            Root = root;

            MarkTransient(varList, methodList, methodType);

            LanguageFlags = LanguageFlags.NewLineBeforeEOF;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates an Irony Grammar
        /// </summary>
        public CRLGrammar() : base(caseSensitive: false)
        {
            //Comentarios
            var singleLineComment = new CommentTerminal("SingleLineComment", "!!", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimitedComment  = new CommentTerminal("DelimitedComment", "<<", ">>");

            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(delimitedComment);

            MarkPunctuation(";", ",", "(", ")", "{", "}", "=", ":");

            InitializeSyntax();
        }
Exemplo n.º 10
0
            public IntegrationTestGrammar()
            {
                var comment = new CommentTerminal("comment", "/*", "*/");

                NonGrammarTerminals.Add(comment);
                var str  = new StringLiteral("str", "'", StringOptions.AllowsLineBreak);
                var stmt = new NonTerminal("stmt")
                {
                    Rule = str | Empty
                };

                Root = stmt;
            }
Exemplo n.º 11
0
        private readonly TerminalSet mSkipTokensInPreview = new TerminalSet();         //used in token preview for conflict resolution

        public JavaGrammar()
        {
            GrammarComments = "NOTE: This grammar does not parse hex floating point literals.";

            var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(delimitedComment);

            MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":", "@");

            InitializeSyntax();
        }
Exemplo n.º 12
0
        public NumericalSchemeGrammar()
        {
            this.GrammarComments = "";

            //Symbols
            var whitespace = new NonTerminal("WhiteSpace", Empty | " " | "\t");
            // Comments
            var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var multiLineComment  = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(multiLineComment);

            //Terminals
            var semicolon    = ToTerm(";", "Semicolon");
            var ofString     = new StringLiteral("String", "\"");
            var ofNumber     = new NumberLiteral("Number", NumberOptions.AllowSign);
            var ofIdentifier = TerminalFactory.CreateCSharpIdentifier("Identifier");
            var ofArrayTerm  = new IdentifierTerminal("SchemeTerm", "(),|*.+-/%^~!&");

            //Non-terminals
            var ofValue = new NonTerminal("Value");

            var ofDictionary               = new NonTerminal("Dictionary");
            var ofDictionaryContent        = new NonTerminal("DictionaryContent");
            var ofDictionaryContentWrapper = new NonTerminal("DictionaryContentWrapper");
            var ofDictEntry = new NonTerminal("DictEntry");

            var ofArrayEntry   = new NonTerminal("ArrayEntry");
            var ofArray        = new NonTerminal("Array");
            var ofArrayWrapper = new NonTerminal("ArrayWrapper");

            //BNF
            ofValue.Rule = ofIdentifier | ofArrayTerm | ofString | ofNumber;

            ofDictEntry.Rule                = ofArrayWrapper | ofDictionary;
            ofDictionaryContent.Rule        = MakeStarRule(ofDictionaryContent, whitespace, ofDictEntry);
            ofDictionaryContentWrapper.Rule = "{" + ofDictionaryContent + "}";
            ofDictionary.Rule               = ofIdentifier + whitespace + ofDictionaryContentWrapper;

            ofArrayEntry.Rule   = ofValue;
            ofArray.Rule        = MakeStarRule(ofArray, whitespace, ofArrayEntry);
            ofArrayWrapper.Rule = ofArray + semicolon;

            //Set grammar root
            this.Root = ofDictionaryContent;
            MarkPunctuation("{", "}");
            MarkTransient(ofValue, ofDictionaryContentWrapper);
        }
        public ASLGrammar()
            : base(true)
        {
            var stringLit         = TerminalFactory.CreateCSharpString("string");
            var number            = TerminalFactory.CreateCSharpNumber("number");
            var identifier        = TerminalFactory.CreateCSharpIdentifier("identifier");
            var code              = new CustomTerminal("code", MatchCodeTerminal);
            var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(delimitedComment);

            var state     = new KeyTerm("state", "state");
            var start     = new KeyTerm("start", "start");
            var split     = new KeyTerm("split", "split");
            var reset     = new KeyTerm("reset", "reset");
            var isLoading = new KeyTerm("isLoading", "isLoading");
            var gameTime  = new KeyTerm("gameTime", "gameTime");
            var comma     = ToTerm(",", "comma");
            var semi      = ToTerm(";", "semi");

            var root       = new NonTerminal("root");
            var stateDef   = new NonTerminal("stateDef");
            var methodList = new NonTerminal("methodList");
            var varList    = new NonTerminal("varList");
            var var        = new NonTerminal("var");
            var method     = new NonTerminal("method");
            var offsetList = new NonTerminal("offsetList");
            var offset     = new NonTerminal("offset");
            var methodType = new NonTerminal("methodType");

            root.Rule       = stateDef + methodList;
            stateDef.Rule   = state + "(" + stringLit + ")" + "{" + varList + "}";
            methodList.Rule = MakeStarRule(methodList, method);
            varList.Rule    = MakeStarRule(varList, semi, var);
            var.Rule        = (identifier + identifier + ":" + stringLit + comma + offsetList) | Empty;
            method.Rule     = (methodType + "{" + code + "}") | Empty;
            offsetList.Rule = MakePlusRule(offsetList, comma, offset);
            offset.Rule     = number;
            methodType.Rule = start | split | isLoading | gameTime | reset;

            this.Root = root;

            MarkTransient(varList, methodList, offset, methodType);

            this.LanguageFlags = LanguageFlags.NewLineBeforeEOF;
        }
Exemplo n.º 14
0
        public Kbtter3QueryGrammar() : base(false)
        {
            //コメント
            var comment = new CommentTerminal("Comment", "/*", "*/");

            NonGrammarTerminals.Add(comment);

            //リテラル
            var number = new NumberLiteral("Number", NumberOptions.AllowSign | NumberOptions.AllowStartEndDot);
            var str    = new StringLiteral("String", "\"");
            var regex  = new RegexLiteral("Regex", '/', '\\');
            var ident  = new IdentifierTerminal("Identifer");

            //非終端
            var Value             = new NonTerminal("Value");
            var Term              = new NonTerminal("Term");
            var Expression        = new NonTerminal("Expression");
            var BinExpression     = new NonTerminal("BinExpression");
            var ParExpression     = new NonTerminal("ParExpression");
            var PostfixExpression = new NonTerminal("PostfixExpression");
            var Operator          = new NonTerminal("Operator");

            //非終端定義
            Value.Rule             = number | str | ident | regex | "null" | "true" | "false";
            Term.Rule              = Value | ParExpression;
            Operator.Rule          = ToTerm("==") | "!=" | ">" | "<" | ">=" | "<=" | "match" | "&&" | "||" | "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | ".";
            BinExpression.Rule     = Expression + Operator + Expression;
            PostfixExpression.Rule = (ToTerm("+") + Term) | ("-" + Term) | ("!" + Term);
            Expression.Rule        = BinExpression | Term | PostfixExpression;
            ParExpression.Rule     = ToTerm("(") + Expression + ")";

            RegisterOperators(10, ".");
            RegisterOperators(9, "*", "/", "%");
            RegisterOperators(8, "+", "-");
            RegisterOperators(7, ">", "<", ">=", "<=", "match");
            RegisterOperators(6, "==", "!=");
            RegisterOperators(5, "&");
            RegisterOperators(4, "^");
            RegisterOperators(3, "|");
            RegisterOperators(2, "&&");
            RegisterOperators(1, "||");

            Root = Expression;
            MarkPunctuation("(", ")");
            MarkTransient(Expression, ParExpression, Value, Operator, Term);
        }
        void InitializeComments()
        {
            ////        comment:
            ////            single_line_comment
            ////            requires_comment
            ////            delimited_comment

            ////        single_line_comment:
            ////            #   input_characters_opt
            ////        input_characters:
            ////            input_character
            ////            input_characters   input_character
            ////        input_character:
            ////            Any Unicode character except a new_line_character
            CommentTerminal comment = new CommentTerminal("comment", "#", "\r", "\n", "\r\n");

            NonGrammarTerminals.Add(comment);
        }
Exemplo n.º 16
0
        public LightGrammar()
        {
            var lineComment = new CommentTerminal("LineComment", "#", "\n", "\r\n");

            NonGrammarTerminals.Add(lineComment);

            ConstructAll();
            SetAllRules();

            MarkPunctuation("[", "]", "(", ")", "{", "}", ":", "=>", ".", "=");

            RegisterOperators(1, "==");
            RegisterOperators(2, "-");
            RegisterOperators(3, "mod");
            RegisterOperators(4, "**");

            this.Root          = TopLevelRoot;
            this.LanguageFlags = LanguageFlags.CreateAst;
        }
Exemplo n.º 17
0
        public analizador()
        {
            var entero            = new RegexBasedTerminal("entero", "[0-9]+");
            IdentifierTerminal id = new IdentifierTerminal("id");
            var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            var delimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");
            var p = new StringLiteral("p", "\"");

            var ENTERO = ToTerm("entero");
            var CADENA = ToTerm("cadena");
            var DOUBLE = ToTerm("double");

            //ENTERO.AstConfig.NodeType = typeof(Arbol);
            //CADENA.AstConfig.NodeType = typeof(Arbol);
            //DOUBLE.AstConfig.NodeType = typeof(Arbol);


            p.AstConfig.NodeType      = typeof(Arbol);
            entero.AstConfig.NodeType = typeof(Arbol);
            id.AstConfig.NodeType     = typeof(Arbol);
            NonTerminal E = new NonTerminal("E", typeof(Arbol));



            E.Rule = E + ToTerm("+") + E
                     | E + ToTerm("-") + E
                     | E + ToTerm("*") + E
                     | E + ToTerm("/") + E
                     | ToTerm("(") + E + ToTerm(")")
                     | entero
                     | id;

            RegisterOperators(1, "+", "-");//ESTABLESEMOS PRESEDENCIA
            RegisterOperators(2, "*", "/");

            this.Root = E;
            NonGrammarTerminals.Add(singleLineComment); // QUITAMOS LOS COMENTARIOS DE LA GRAMATICA
            NonGrammarTerminals.Add(delimitedComment);
            LanguageFlags = LanguageFlags.CreateAst;    //IMPORTANTE PARA CREAR EL ARBOL SIN ESTO NO LO CREARA
        }
Exemplo n.º 18
0
        /// <summary>
        /// 新しいインスタンスを以下略
        /// </summary>
        public Kb10uyConfigGrammar()
            : base()
        {
            var Number       = new NumberLiteral("Number");
            var String       = new StringLiteral("String", "\"", StringOptions.AllowsAllEscapes);
            var CommentLine  = new CommentTerminal("Comment", "#", "\n", "\r");
            var CommentBlock = new CommentTerminal("Comment", "#<", ">");

            //数値設定
            Number.DefaultIntTypes  = new[] { TypeCode.Int32 };
            Number.DefaultFloatType = TypeCode.Double;
            String.EscapeChar       = '\\';
            NonGrammarTerminals.Add(CommentBlock);
            NonGrammarTerminals.Add(CommentLine);

            var Value    = new NonTerminal("Value");
            var Values   = new NonTerminal("Value\'s\'");
            var ValueSet = new NonTerminal("Array");
            var Property = new NonTerminal("Property");
            var Prefix   = new NonTerminal("Prefix");
            var Node     = new NonTerminal("Node");
            var Nodes    = new NonTerminal("Nodes");
            //var PropertySet = new NonTerminal("PropertySet");
            var Group      = new NonTerminal("Group");
            var ConfigRoot = new NonTerminal("Root");

            Value.Rule      = Number | String | ValueSet;
            Values.Rule     = MakeStarRule(Values, ToTerm(","), Value);
            ValueSet.Rule   = ToTerm("[") + Values + "]";
            Prefix.Rule     = ToTerm("Number") | "String" | "Array";
            Property.Rule   = Prefix + ":" + String + "=" + Value + ";";
            Node.Rule       = Property | Group;
            Nodes.Rule      = MakeStarRule(Nodes, Node);
            Group.Rule      = String + ":" + "{" + Nodes + "}";
            ConfigRoot.Rule = MakeStarRule(ConfigRoot, Group);
            Root            = ConfigRoot;

            MarkPunctuation("[", "]", ",", "{", "}", ":", ";", "=");
        }
Exemplo n.º 19
0
        private void SetUpTerminals()
        {
            Comment = new CommentTerminal(nameof(Comment), ";", "\n", "\r");
            NonGrammarTerminals.Add(Comment);

            var ident = new IdentifierTerminal(nameof(Ident), ".$_", ".$_");

            ident.Options = IdOptions.IsNotKeyword;
            Ident         = ident;

            var number = new NumberLiteral(nameof(Number), NumberOptions.AllowUnderscore | NumberOptions.IntOnly | NumberOptions.AllowSign);

            number.AddPrefix("0x", NumberOptions.Hex);
            number.AddPrefix("0b", NumberOptions.Binary);
            number.AddPrefix("0", NumberOptions.Octal);
            Number = number;

            NormalString  = new StringLiteral(nameof(NormalString), "\"", StringOptions.NoEscapes);
            EscapedString = new StringLiteral(nameof(EscapedString), "`", StringOptions.AllowsAllEscapes);
            CharLiteral   = new StringLiteral(nameof(CharLiteral), "'", StringOptions.IsChar | StringOptions.AllowsAllEscapes);
            Separator     = ToTerm(SeparatorToken, nameof(Separator));
        }
Exemplo n.º 20
0
        void InitializeComments()
        {
            ////        comment:
            ////            single_line_comment
            ////            requires_comment
            ////            delimited_comment

            ////        single_line_comment:
            ////            #   input_characters_opt
            ////        input_characters:
            ////            input_character
            ////            input_characters   input_character
            ////        input_character:
            ////            Any Unicode character except a new_line_character
            CommentTerminal comment = new CommentTerminal("comment", "#", "\r", "\n", "\r\n");

            NonGrammarTerminals.Add(comment);

            ////        delimited_comment:
            ////            <#   delimited_comment_text_opt   hashes   >
            ////        delimited_comment_text:
            ////            delimited_comment_section
            ////            delimited_comment_text   delimited_comment_section
            ////        delimited_comment_section:
            ////            >
            ////            hashes_opt   not_greater_than_or_hash
            ////        hashes:
            ////            #
            ////            hashes   #
            ////        not_greater_than_or_hash:
            ////            Any Unicode character except > or #

            CommentTerminal delimited_comment = new CommentTerminal("delimited_comment", "<#", "#>");

            NonGrammarTerminals.Add(delimited_comment);
        }
Exemplo n.º 21
0
        public GramaticaCQL() : base(false)
        {
            CommentTerminal blockComment = new CommentTerminal("block-comment", "/*", "*/");
            CommentTerminal lineComment  = new CommentTerminal("line-comment", "//",
                                                               "\r", "\n", "\u2085", "\u2028", "\u2029");

            NonGrammarTerminals.Add(blockComment);
            NonGrammarTerminals.Add(lineComment);

            /* Reserved Words */
            KeyTerm
                null_      = ToTerm("null"),
                true_      = ToTerm("true"),
                false_     = ToTerm("false"),
                type_      = ToTerm("type"),
                if_        = ToTerm("if"),
                not_       = ToTerm("not"),
                exists_    = ToTerm("exists"),
                int_       = ToTerm("int"),
                double_    = ToTerm("double"),
                string_    = ToTerm("string"),
                boolean_   = ToTerm("boolean"),
                date_      = ToTerm("date"),
                time_      = ToTerm("time"),
                use_       = ToTerm("use"),
                create_    = ToTerm("create"),
                database_  = ToTerm("database"),
                drop_      = ToTerm("drop"),
                table_     = ToTerm("table"),
                counter_   = ToTerm("counter"),
                primary_   = ToTerm("primary"),
                key_       = ToTerm("key"),
                alter_     = ToTerm("alter"),
                add_       = ToTerm("add"),
                truncate_  = ToTerm("truncate"),
                commit_    = ToTerm("commit"),
                rollback_  = ToTerm("rollback"),
                user_      = ToTerm("user"),
                with_      = ToTerm("with"),
                password_  = ToTerm("password"),
                grant_     = ToTerm("grant"),
                on_        = ToTerm("on"),
                revoke_    = ToTerm("revoke"),
                insert_    = ToTerm("insert"),
                into_      = ToTerm("into"),
                values_    = ToTerm("values"),
                update_    = ToTerm("update"),
                set_       = ToTerm("set"),
                where_     = ToTerm("where"),
                delete_    = ToTerm("delete"),
                from_      = ToTerm("from"),
                select_    = ToTerm("select"),
                order_     = ToTerm("order"),
                by_        = ToTerm("by"),
                asc_       = ToTerm("asc"),
                desc_      = ToTerm("desc"),
                limit_     = ToTerm("limit"),
                begin_     = ToTerm("begin"),
                batch_     = ToTerm("batch"),
                apply_     = ToTerm("apply"),
                count_     = ToTerm("count"),
                min_       = ToTerm("min"),
                max_       = ToTerm("max"),
                sum_       = ToTerm("sum"),
                avg_       = ToTerm("avg"),
                in_        = ToTerm("in"),
                else_      = ToTerm("else"),
                switch_    = ToTerm("switch"),
                case_      = ToTerm("case"),
                default_   = ToTerm("default"),
                while_     = ToTerm("while"),
                do_        = ToTerm("do"),
                for_       = ToTerm("for"),
                new_       = ToTerm("new"),
                map_       = ToTerm("map"),
                list_      = ToTerm("list"),
                procedure_ = ToTerm("procedure"),
                call_      = ToTerm("call"),
                break_     = ToTerm("break"),
                continue_  = ToTerm("continue"),
                return_    = ToTerm("return"),
                cursor_    = ToTerm("cursor"),
                is_        = ToTerm("is"),
                each_      = ToTerm("each"),
                open_      = ToTerm("open"),
                close_     = ToTerm("close"),
                log_       = ToTerm("log"),
                throw_     = ToTerm("throw"),
                try_       = ToTerm("try"),
                catch_     = ToTerm("catch"),
                as_        = ToTerm("as");

            MarkReservedWords("null", "true", "false", "type", "if", "not", "exists", "int", "double", "string", "boolean",
                              "date", "time", "use", "create", "database", "drop", "table", "counter", "primary", "key", "alter", "add",
                              "truncate", "commit", "rollback", "user", "with", "password", "grant", "on", "revoke", "insert", "into",
                              "values", "update", "set", "where", "delete", "from", "select", "order", "by", "asc", "desc", "limit",
                              "begin", "batch", "apply", "count", "min", "max", "sum", "avg", "in", "else", "switch", "case", "default",
                              "while", "do", "for", "new", "map", "list", "procedure", "call", "break", "continue", "return", "cursor",
                              "is", "each", "open", "close", "log", "throw", "try", "catch", "as");

            /* Relational operators */
            KeyTerm
                menorigual = ToTerm("<="),
                mayorigual = ToTerm(">="),
                menorque   = ToTerm("<"),
                mayorque   = ToTerm(">"),
                igual      = ToTerm("=="),
                diferente  = ToTerm("!=");

            /* Logic operators */
            KeyTerm
                or  = ToTerm("||"),
                and = ToTerm("&&"),
                xor = ToTerm("^"),
                not = ToTerm("!");

            /* Shift operators */
            KeyTerm
                leftShift  = ToTerm("--"),
                rightShift = ToTerm("++");

            /* Arithmetic Operators*/
            KeyTerm
                mas      = ToTerm("+"),
                menos    = ToTerm("-"),
                por      = ToTerm("*"),
                division = ToTerm("/"),
                modulo   = ToTerm("%"),
                potencia = ToTerm("**");

            /* Symbols*/
            KeyTerm
                equal         = ToTerm("="),
                semicolon     = ToTerm(";"),
                leftPar       = ToTerm("("),
                rightPar      = ToTerm(")"),
                dot           = ToTerm("."),
                comma         = ToTerm(","),
                questionmark  = ToTerm("?"),
                colon         = ToTerm(":"),
                leftCor       = ToTerm("["),
                rightCor      = ToTerm("]"),
                leftLla       = ToTerm("{"),
                rightLla      = ToTerm("}"),
                masEqual      = ToTerm("+="),
                menosEqual    = ToTerm("-="),
                porEqual      = ToTerm("*="),
                divisionEqual = ToTerm("/="),
                menormenor    = ToTerm("<<"),
                mayormayor    = ToTerm(">>");

            MarkPunctuation(";");

            var number = new NumberLiteral("number");
            //var identifier = new IdentifierTerminal("identifier");
            RegexBasedTerminal identifier  = new RegexBasedTerminal("identifier", "([a-zA-ZñÑ]|_)([a-zA-ZñÑ]|[0-9]|_)*");
            RegexBasedTerminal identifier2 = new RegexBasedTerminal("identifier2", "@([a-zA-ZñÑ]|_)([a-zA-ZñÑ]|[0-9]|_)*");
            //RegexBasedTerminal date = new RegexBasedTerminal("date", "\'([0-2][0-9]{3}|[0-9][0-9]{0,2})-([0]?[0-9]|[1][0-2])-([0]?[0-9]|[1-2][0-9]|[3][0-1])\'");
            //RegexBasedTerminal time = new RegexBasedTerminal("time", "\'([0]?[0-9]|[1][0-9]|[2][0-4]):([0]?[0-9]|[1-5][0-9]):([0]?[0-9]|[1-5][0-9])\'");
            RegexBasedTerminal date = new RegexBasedTerminal("date", "\'[0-9]+-[0-9]+-[0-9]+\'");
            RegexBasedTerminal time = new RegexBasedTerminal("time", "\'[0-9]+:[0-9]+:[0-9]+\'");
            var stringliteral       = new StringLiteral("stringliteral", "\"", StringOptions.IsTemplate);

            NonTerminal
                INICIO        = new NonTerminal("INICIO"),
                INSTRUCCIONES = new NonTerminal("INSTRUCCIONES"),
                INSTRUCCION   = new NonTerminal("INSTRUCCION"),

                TYPE            = new NonTerminal("TYPE"),
                TYPE_PRIMITIVE  = new NonTerminal("TYPE_PRIMITIVE"),
                TYPE_COLLECTION = new NonTerminal("TYPE_COLLECTION"),
                TYPEDEF         = new NonTerminal("TYPEDEF"),
                IFNOTEXIST      = new NonTerminal("IFNOTEXIST"),
                IFEXIST         = new NonTerminal("IFEXIST"),
                ATTRIBUTE_LIST  = new NonTerminal("ATTRIBUTE_LIST"),
                ATTRIBUTEREF    = new NonTerminal("ATTRIBUTEREF"),
                ATTRIBUTE       = new NonTerminal("ATTRIBUTE"),

                USE           = new NonTerminal("USE"),
                DATABASEDEF   = new NonTerminal("DATABASEDEF"),
                DROP          = new NonTerminal("DROP"),
                TABLEDEF      = new NonTerminal("TABLEDEF"),
                COLUMN_LIST   = new NonTerminal("COLUMN_LIST"),
                COLUMN        = new NonTerminal("COLUMN"),
                ID_LIST       = new NonTerminal("ID_LIST"),
                TABLEALTER    = new NonTerminal("TABLEALTER"),
                TABLEDROP     = new NonTerminal("TABLEDROP"),
                TABLETRUNCATE = new NonTerminal("TABLETRUNCATE"),

                COMMIT   = new NonTerminal("COMMIT"),
                ROLLBACK = new NonTerminal("ROLLBACK"),

                USERDEF = new NonTerminal("USERDEF"),
                GRANT   = new NonTerminal("GRANT"),
                REVOKE  = new NonTerminal("REVOKE"),

                WHERE      = new NonTerminal("WHERE"),
                INSERT     = new NonTerminal("INSERT"),
                UPDATE     = new NonTerminal("UPDATE"),
                DELETE     = new NonTerminal("DELETE"),
                SELECT     = new NonTerminal("SELECT"),
                SELECT_EXP = new NonTerminal("SELECT_EXP"),
                ORDER_LIST = new NonTerminal("ORDER_LIST"),
                ORDER      = new NonTerminal("ORDER"),
                BATCH      = new NonTerminal("BATCH"),
                DML_LIST   = new NonTerminal("DML_LIST"),
                DML        = new NonTerminal("DML"),

                TARGET_LIST = new NonTerminal("TARGET_LIST"),
                TARGET      = new NonTerminal("TARGET"),

                EXPRESSION_STMT = new NonTerminal("EXPRESSION_STMT"),
                ASSIGNMENT_STMT = new NonTerminal("ASSIGNMENT_STMT"),
                ASSIGNMENTS     = new NonTerminal("ASSIGNMENTS"),
                ASSIGNMENT_CALL = new NonTerminal("ASSIGNMENT_CALL"),
                ASSIGNMENT_LIST = new NonTerminal("ASSIGNMENT_LIST"),

                DECLARATION_STMT          = new NonTerminal("DECLARATION_STMT"),
                AUGMENTED_ASSIGNMENT_STMT = new NonTerminal("AUGMENTED_ASSIGNMENT_STMT"),
            //AUGTARGET = new NonTerminal("AUGTARGET"),
                AUG_OPERATOR = new NonTerminal("AUG_OPERATOR"),

                IF_STMT      = new NonTerminal("IF_STMT"),
                IF_LIST      = new NonTerminal("IF_LIST"),
                SWITCH_STMT  = new NonTerminal("SWITCH_STMT"),
                CASES        = new NonTerminal("CASES"),
                WHILE_STMT   = new NonTerminal("WHILE_STMT"),
                DOWHILE_STMT = new NonTerminal("DOWHILE_STMT"),
                FOR_STMT     = new NonTerminal("FOR_STMT"),
                FOR_INIT     = new NonTerminal("FOR_INIT"),
                FOR_UPDATE   = new NonTerminal("FOR_UPDATE"),

                FUNDEF         = new NonTerminal("FUNDEF"),
                PARAMETER_LIST = new NonTerminal("PARAMETER_LIST"),

                PROCDEF = new NonTerminal("PROCDEF"),

                BREAK_STMT    = new NonTerminal("BREAK_STMT"),
                CONTINUE_STMT = new NonTerminal("CONTINUE_STMT"),
                RETURN_STMT   = new NonTerminal("RETURN_STMT"),

                CURSOR_STMT   = new NonTerminal("CURSOR_STMT"),
                FOREACH_STMT  = new NonTerminal("FOREACH_STMT"),
                OPEN_STMT     = new NonTerminal("OPEN_STMT"),
                CLOSE_STMT    = new NonTerminal("CLOSE_STMT"),
                LOG_STMT      = new NonTerminal("LOG_STMT"),
                THROW_STMT    = new NonTerminal("THROW_STMT"),
                TRYCATCH_STMT = new NonTerminal("TRYCATCH_STMT"),

                BLOQUE     = new NonTerminal("BLOQUE"),
                SENTENCIAS = new NonTerminal("SENTENCIAS"),
                SENTENCIA  = new NonTerminal("SENTENCIA"),

            /*STARRED_EXPRESSION = new NonTerminal("STARRED_EXPRESSION"),
             * STARRED_LIST = new NonTerminal("STARRED_LIST"),
             * STARRED_ITEM = new NonTerminal("STARRED_ITEM"),*/

                AGGREGATION     = new NonTerminal("AGGREGATION"),
                AGGREGATION_FUN = new NonTerminal("AGGREGATION_FUN"),

                EXPRESSION_LIST        = new NonTerminal("EXPRESSION_LIST"),
                EXPRESSION             = new NonTerminal("EXPRESSION"),
                CONDITIONAL_EXPRESSION = new NonTerminal("CONDITIONAL_EXPRESSION"),
                INSTANCE      = new NonTerminal("INSTANCE"),
                OR_EXPR       = new NonTerminal("OR_EXPR"),
                AND_EXPR      = new NonTerminal("AND_EXPR"),
                XOR_EXPR      = new NonTerminal("XOR_EXPR"),
                NOT_EXPR      = new NonTerminal("NOT_EXPR"),
                COMPARISON    = new NonTerminal("COMPARISON"),
                COMPARISON_EQ = new NonTerminal("COMPARISON_EQ"),
                COMP_OPERATOR = new NonTerminal("COMP_OPERATOR"),
                SHIFT_EXPR    = new NonTerminal("SHIFT_EXPR"),
                A_EXPR        = new NonTerminal("A_EXPR"),
                M_EXPR        = new NonTerminal("M_EXPR"),
                U_EXPR        = new NonTerminal("U_EXPR"),
                POWER         = new NonTerminal("POWER"),
                PRIMARY       = new NonTerminal("PRIMARY"),
                ATOM          = new NonTerminal("ATOM"),
                FUNCALL       = new NonTerminal("FUNCALL"),
                CALL          = new NonTerminal("CALL"),
                ACCESS        = new NonTerminal("ACCESS"),
                ENCLOSURE     = new NonTerminal("ENCLOSURE"),
                LITERAL       = new NonTerminal("LITERAL"),
                PARENTH_FORM  = new NonTerminal("PARENTH_FORM"),
                MAP_DISPLAY   = new NonTerminal("MAP_DISPLAY"),
                MAP_LIST      = new NonTerminal("MAP_LIST"),
                LIST_DISPLAY  = new NonTerminal("LIST_DISPLAY"),
                SET_DISPLAY   = new NonTerminal("SET_DISPLAY");

            this.Root = INICIO;

            INICIO.Rule = INSTRUCCIONES;

            INSTRUCCIONES.Rule = MakePlusRule(INSTRUCCIONES, INSTRUCCION);

            INSTRUCCION.Rule = TYPEDEF + semicolon
                               | USE + semicolon
                               | DATABASEDEF + semicolon
                               | DROP + semicolon
                               | TABLEDEF + semicolon
                               | TABLEALTER + semicolon
                               | TABLEDROP + semicolon
                               | TABLETRUNCATE + semicolon
                               | COMMIT + semicolon
                               | ROLLBACK + semicolon
                               | USERDEF + semicolon
                               | GRANT + semicolon
                               | REVOKE + semicolon
                               | INSERT + semicolon
                               | UPDATE + semicolon
                               | DELETE + semicolon
                               | SELECT + semicolon
                               | BATCH + semicolon

                               | EXPRESSION_STMT + semicolon
                               | DECLARATION_STMT + semicolon
                               | ASSIGNMENT_STMT + semicolon
                               | ASSIGNMENT_CALL + semicolon
                               | AUGMENTED_ASSIGNMENT_STMT + semicolon
                               | IF_STMT
                               | SWITCH_STMT
                               | WHILE_STMT
                               | DOWHILE_STMT + semicolon
                               | FOR_STMT

                               | FUNDEF
                               | PROCDEF

                               | BREAK_STMT + semicolon
                               | CONTINUE_STMT + semicolon
                               | RETURN_STMT + semicolon

                               | CURSOR_STMT + semicolon
                               | FOREACH_STMT
                               | OPEN_STMT + semicolon
                               | CLOSE_STMT + semicolon
                               | LOG_STMT + semicolon
                               | THROW_STMT + semicolon
                               | TRYCATCH_STMT;

            //INSTRUCCION.ErrorRule = SyntaxError + semicolon;


            TYPE.Rule = int_ | double_ | string_ | boolean_ | date_ | time_ | identifier | counter_ | map_ | list_ | set_;

            TYPE_PRIMITIVE.Rule = int_ | double_ | string_ | boolean_ | date_ | time_;

            TYPE_COLLECTION.Rule = int_ | double_ | string_ | boolean_ | date_ | time_ | identifier | counter_
                                   | map_ + menorque + TYPE_PRIMITIVE + comma + TYPE_COLLECTION + mayorque
                                   | list_ + menorque + TYPE_COLLECTION + mayorque
                                   | set_ + menorque + TYPE_COLLECTION + mayorque;

            IFNOTEXIST.Rule = if_ + not_ + exists_;

            IFEXIST.Rule = if_ + exists_;

            TYPEDEF.Rule = create_ + type_ + identifier + leftPar + ATTRIBUTE_LIST + rightPar
                           | create_ + type_ + IFNOTEXIST + identifier + leftPar + ATTRIBUTE_LIST + rightPar;

            ATTRIBUTE_LIST.Rule = MakePlusRule(ATTRIBUTE_LIST, comma, ATTRIBUTE);

            ATTRIBUTE.Rule = identifier + TYPE_COLLECTION;

            USE.Rule = use_ + identifier;

            DATABASEDEF.Rule = create_ + database_ + identifier
                               | create_ + database_ + IFNOTEXIST + identifier;

            DROP.Rule = drop_ + database_ + identifier
                        | drop_ + database_ + IFNOTEXIST + identifier;

            TABLEDEF.Rule = create_ + table_ + identifier + leftPar + COLUMN_LIST + rightPar
                            | create_ + table_ + IFNOTEXIST + identifier + leftPar + COLUMN_LIST + rightPar;

            COLUMN_LIST.Rule = MakePlusRule(COLUMN_LIST, comma, COLUMN);

            COLUMN.Rule = identifier + TYPE_COLLECTION
                          | identifier + TYPE_COLLECTION + primary_ + key_
                          | primary_ + key_ + leftPar + ID_LIST + rightPar;

            ID_LIST.Rule = MakePlusRule(ID_LIST, comma, identifier);

            TABLEALTER.Rule = alter_ + table_ + identifier + add_ + ATTRIBUTE_LIST
                              | alter_ + table_ + identifier + drop_ + ID_LIST;

            TABLEDROP.Rule = drop_ + table_ + identifier
                             | drop_ + table_ + IFEXIST + identifier;

            TABLETRUNCATE.Rule = truncate_ + table_ + identifier;


            COMMIT.Rule = commit_;

            ROLLBACK.Rule = rollback_;


            USERDEF.Rule = create_ + user_ + identifier + with_ + password_ + stringliteral;

            GRANT.Rule = grant_ + identifier + on_ + identifier;

            REVOKE.Rule = revoke_ + identifier + on_ + identifier;

            WHERE.Rule = where_ + EXPRESSION
                         | where_ + EXPRESSION + in_ + EXPRESSION_LIST
                         | where_ + EXPRESSION + in_ + leftPar + EXPRESSION_LIST + rightPar;

            INSERT.Rule = insert_ + into_ + identifier + values_ + leftPar + EXPRESSION_LIST + rightPar
                          | insert_ + into_ + identifier + leftPar + ID_LIST + rightPar + values_ + leftPar + EXPRESSION_LIST + rightPar;

            UPDATE.Rule = update_ + identifier + set_ + ASSIGNMENT_LIST
                          | update_ + identifier + set_ + ASSIGNMENT_LIST + WHERE;

            DELETE.Rule = delete_ + from_ + identifier
                          | delete_ + from_ + identifier + WHERE
                          | delete_ + TARGET + from_ + identifier
                          | delete_ + TARGET + from_ + identifier + WHERE;

            SELECT.Rule = select_ + SELECT_EXP + from_ + identifier
                          | select_ + SELECT_EXP + from_ + identifier + WHERE
                          | select_ + SELECT_EXP + from_ + identifier + order_ + by_ + ORDER_LIST
                          | select_ + SELECT_EXP + from_ + identifier + WHERE + order_ + by_ + ORDER_LIST
                          | select_ + SELECT_EXP + from_ + identifier + limit_ + EXPRESSION
                          | select_ + SELECT_EXP + from_ + identifier + WHERE + limit_ + EXPRESSION
                          | select_ + SELECT_EXP + from_ + identifier + order_ + by_ + ORDER_LIST + limit_ + EXPRESSION
                          | select_ + SELECT_EXP + from_ + identifier + WHERE + order_ + by_ + ORDER_LIST + limit_ + EXPRESSION;

            SELECT_EXP.Rule = EXPRESSION_LIST | por;

            ORDER_LIST.Rule = MakePlusRule(ORDER_LIST, comma, ORDER);

            ORDER.Rule = identifier
                         | identifier + asc_
                         | identifier + desc_; //TARGET*

            BATCH.Rule = begin_ + batch_ + DML_LIST + apply_ + batch_;

            DML_LIST.Rule = MakePlusRule(DML_LIST, DML);

            DML.Rule = INSERT + semicolon
                       | UPDATE + semicolon
                       | DELETE + semicolon;

            ////////////////////////////////////////////////////////////////

            BLOQUE.Rule = leftLla + SENTENCIAS + rightLla
                          | leftLla + rightLla;

            SENTENCIAS.Rule = MakePlusRule(SENTENCIAS, SENTENCIA);

            SENTENCIA.Rule = TYPEDEF + semicolon    /****/
                             | USE + semicolon
                             | DATABASEDEF + semicolon
                             | DROP + semicolon
                             | TABLEDEF + semicolon
                             | TABLEALTER + semicolon
                             | TABLEDROP + semicolon
                             | TABLETRUNCATE + semicolon
                             | COMMIT + semicolon
                             | ROLLBACK + semicolon
                             | USERDEF + semicolon
                             | GRANT + semicolon
                             | REVOKE + semicolon
                             | INSERT + semicolon
                             | UPDATE + semicolon
                             | DELETE + semicolon
                             | SELECT + semicolon
                             | BATCH + semicolon

                             | EXPRESSION_STMT + semicolon
                             | DECLARATION_STMT + semicolon
                             | ASSIGNMENT_STMT + semicolon
                             | ASSIGNMENT_CALL + semicolon
                             | AUGMENTED_ASSIGNMENT_STMT + semicolon
                             | IF_STMT
                             | SWITCH_STMT
                             | WHILE_STMT
                             | DOWHILE_STMT + semicolon
                             | FOR_STMT

                             | BREAK_STMT + semicolon
                             | CONTINUE_STMT + semicolon
                             | RETURN_STMT + semicolon

                             | CURSOR_STMT + semicolon
                             | FOREACH_STMT
                             | OPEN_STMT + semicolon
                             | CLOSE_STMT + semicolon
                             | LOG_STMT + semicolon
                             | THROW_STMT + semicolon
                             | TRYCATCH_STMT;

            TARGET_LIST.Rule = MakePlusRule(TARGET_LIST, comma, TARGET);

            TARGET.Rule = identifier     //*
                          | identifier2
                          | ATTRIBUTEREF //*
                          | ACCESS;

            EXPRESSION_STMT.Rule = SHIFT_EXPR + leftShift | SHIFT_EXPR + rightShift | FUNCALL | CALL | ATTRIBUTEREF;

            DECLARATION_STMT.Rule = TYPE + TARGET_LIST
                                    | TYPE + TARGET_LIST + equal + EXPRESSION;

            ASSIGNMENT_STMT.Rule = TARGET + equal + EXPRESSION
                                   | TARGET + equal + CALL;

            ASSIGNMENT_CALL.Rule = TARGET_LIST + equal + CALL;

            ASSIGNMENT_LIST.Rule = MakePlusRule(ASSIGNMENT_LIST, comma, ASSIGNMENTS);

            ASSIGNMENTS.Rule = ASSIGNMENT_STMT | AUGMENTED_ASSIGNMENT_STMT;

            AUGMENTED_ASSIGNMENT_STMT.Rule = TARGET + AUG_OPERATOR + EXPRESSION;

            //AUGTARGET.Rule = identifier | identifier2 | ATTRIBUTEREF; //*

            AUG_OPERATOR.Rule = masEqual | menosEqual | porEqual | divisionEqual;

            IF_STMT.Rule = IF_LIST + else_ + BLOQUE
                           | IF_LIST;

            IF_LIST.Rule = IF_LIST + else_ + if_ + leftPar + EXPRESSION + rightPar + BLOQUE
                           | if_ + leftPar + EXPRESSION + rightPar + BLOQUE;

            SWITCH_STMT.Rule = switch_ + leftPar + EXPRESSION + rightPar + leftLla + CASES + rightLla
                               | switch_ + leftPar + EXPRESSION + rightPar + leftLla + CASES + default_ + colon + BLOQUE + rightLla;

            CASES.Rule = CASES + case_ + EXPRESSION + colon + BLOQUE
                         | case_ + EXPRESSION + colon + BLOQUE;

            WHILE_STMT.Rule = while_ + leftPar + EXPRESSION + rightPar + BLOQUE;

            DOWHILE_STMT.Rule = do_ + BLOQUE + while_ + leftPar + EXPRESSION + rightPar;

            FOR_STMT.Rule = for_ + leftPar + FOR_INIT + semicolon + EXPRESSION + semicolon + FOR_UPDATE + rightPar + BLOQUE;

            FOR_INIT.Rule = DECLARATION_STMT | ASSIGNMENT_STMT;

            FOR_UPDATE.Rule = AUGMENTED_ASSIGNMENT_STMT | ASSIGNMENT_STMT | SHIFT_EXPR + leftShift | SHIFT_EXPR + rightShift;

            FUNDEF.Rule = TYPE + identifier + leftPar + PARAMETER_LIST + rightPar + BLOQUE
                          | TYPE + identifier + leftPar + rightPar + BLOQUE;

            PARAMETER_LIST.Rule = PARAMETER_LIST + comma + TYPE + identifier2
                                  | TYPE + identifier2;

            PROCDEF.Rule = procedure_ + identifier + leftPar + PARAMETER_LIST + rightPar + comma + leftPar + PARAMETER_LIST + rightPar + BLOQUE
                           | procedure_ + identifier + leftPar + rightPar + comma + leftPar + rightPar + BLOQUE
                           | procedure_ + identifier + leftPar + PARAMETER_LIST + rightPar + comma + leftPar + rightPar + BLOQUE
                           | procedure_ + identifier + leftPar + rightPar + comma + leftPar + PARAMETER_LIST + rightPar + BLOQUE;

            BREAK_STMT.Rule = break_;

            CONTINUE_STMT.Rule = continue_;

            RETURN_STMT.Rule = return_
                               | return_ + EXPRESSION_LIST;

            CURSOR_STMT.Rule = cursor_ + identifier2 + is_ + SELECT;

            FOREACH_STMT.Rule = for_ + each_ + leftPar + PARAMETER_LIST + rightPar + in_ + identifier2 + BLOQUE
                                | for_ + each_ + leftPar + rightPar + in_ + identifier2 + BLOQUE;

            OPEN_STMT.Rule = open_ + identifier2;

            CLOSE_STMT.Rule = close_ + identifier2;

            LOG_STMT.Rule = log_ + leftPar + EXPRESSION + rightPar;

            THROW_STMT.Rule = throw_ + new_ + identifier;

            TRYCATCH_STMT.Rule = try_ + BLOQUE + catch_ + leftPar + PARAMETER_LIST + rightPar + BLOQUE
                                 | try_ + BLOQUE + catch_ + leftPar + rightPar + BLOQUE;;

            EXPRESSION_LIST.Rule = MakePlusRule(EXPRESSION_LIST, comma, EXPRESSION);

            EXPRESSION.Rule = CONDITIONAL_EXPRESSION | INSTANCE;

            INSTANCE.Rule = new_ + identifier
                            | new_ + map_ + menorque + TYPE_PRIMITIVE + comma + TYPE_COLLECTION + mayorque
                            | new_ + list_ + menorque + TYPE_COLLECTION + mayorque
                            | new_ + set_ + menorque + TYPE_COLLECTION + mayorque;

            CONDITIONAL_EXPRESSION.Rule = OR_EXPR | OR_EXPR + questionmark + EXPRESSION + colon + EXPRESSION;

            OR_EXPR.Rule = AND_EXPR | OR_EXPR + or + AND_EXPR;

            AND_EXPR.Rule = XOR_EXPR | AND_EXPR + and + XOR_EXPR;

            XOR_EXPR.Rule = COMPARISON_EQ | XOR_EXPR + xor + COMPARISON_EQ;

            COMPARISON_EQ.Rule = COMPARISON | COMPARISON_EQ + igual + COMPARISON
                                 | COMPARISON_EQ + diferente + COMPARISON;

            COMPARISON.Rule = A_EXPR | COMPARISON + COMP_OPERATOR + A_EXPR;

            COMP_OPERATOR.Rule = menorque | mayorque | mayorigual | menorigual;

            A_EXPR.Rule = M_EXPR | A_EXPR + mas + A_EXPR | A_EXPR + menos + M_EXPR;

            M_EXPR.Rule = U_EXPR | M_EXPR + por + U_EXPR | M_EXPR + division + U_EXPR
                          | M_EXPR + modulo + U_EXPR;

            U_EXPR.Rule = NOT_EXPR | POWER | menos + U_EXPR | mas + U_EXPR;

            NOT_EXPR.Rule = not + U_EXPR;

            POWER.Rule = SHIFT_EXPR | SHIFT_EXPR + potencia + U_EXPR;

            SHIFT_EXPR.Rule = PRIMARY | SHIFT_EXPR + leftShift | SHIFT_EXPR + rightShift;

            PRIMARY.Rule = ATOM | ATTRIBUTEREF | AGGREGATION | FUNCALL | ACCESS;

            ATOM.Rule = identifier | identifier2 | LITERAL | ENCLOSURE;

            LITERAL.Rule = number | stringliteral | true_ | false_ | date | time | null_;

            ATTRIBUTEREF.Rule = PRIMARY + dot + identifier
                                | PRIMARY + dot + FUNCALL;

            AGGREGATION.Rule = AGGREGATION_FUN + leftPar + menormenor + SELECT + mayormayor + rightPar;

            AGGREGATION_FUN.Rule = count_ | min_ | max_ | sum_ | avg_;

            ENCLOSURE.Rule = PARENTH_FORM | MAP_DISPLAY | LIST_DISPLAY | SET_DISPLAY;

            PARENTH_FORM.Rule = leftPar + EXPRESSION + rightPar
                                | leftPar + TYPE + rightPar + EXPRESSION;

            MAP_DISPLAY.Rule = leftCor + MAP_LIST + rightCor;

            MAP_LIST.Rule = MAP_LIST + comma + EXPRESSION + colon + EXPRESSION
                            | EXPRESSION + colon + EXPRESSION;

            LIST_DISPLAY.Rule = leftCor + EXPRESSION_LIST + rightCor;

            SET_DISPLAY.Rule = leftLla + EXPRESSION_LIST + rightLla
                               | leftLla + EXPRESSION_LIST + rightLla + as_ + identifier;

            FUNCALL.Rule = identifier + leftPar + rightPar
                           | identifier + leftPar + EXPRESSION_LIST + rightPar;

            CALL.Rule = call_ + identifier + leftPar + rightPar
                        | call_ + identifier + leftPar + EXPRESSION_LIST + rightPar;

            ACCESS.Rule = PRIMARY + leftCor + EXPRESSION + rightCor;
        }
Exemplo n.º 22
0
        public TuringGrammarBroken()
        {
            //Expr -> n | v | Expr BinOp Expr | UnOP Expr | ( Expr )
            //BinOp -> + | - | * | / | **
            //UnOp -> -
            //ExprLine -> Expr EOF
            MarkReservedWords("not=");
            //1. Terminals
            Terminal        num               = new NumberLiteral("number");
            Terminal        iden              = new IdentifierTerminal("identifier");
            Terminal        stringLiteral     = TerminalFactory.CreateCSharpString("stringLiteral");
            CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029");
            CommentTerminal DelimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");

            NonGrammarTerminals.Add(SingleLineComment);
            NonGrammarTerminals.Add(DelimitedComment);

            //2. Non-Terminals
            var expandedIdentifier = new NonTerminal("expandedIndentifier");
            var Expr      = new NonTerminal("expr");
            var BinOp     = new NonTerminal("binOp", "operator");
            var BinExpr   = new NonTerminal("binExpr");
            var unOp      = new NonTerminal("unOp");
            var unExpr    = new NonTerminal("unExpr");
            var ParExpr   = new NonTerminal("parExpr");
            var Statement = new NonTerminal("statement");
            var Program   = new NonTerminal("program");
            var setEqual  = new NonTerminal("setEqual");

            var varType             = new NonTerminal("varType");
            var variableDeclaration = new NonTerminal("variableDeclaration");
            var varOrConst          = new NonTerminal("varOrConst");
            var idenList            = new NonTerminal("identifierList");
            var assignment          = new NonTerminal("assignment");
            var typeSpecifier       = new NonTerminal("typeSpecifier");

            var ifBlock      = new NonTerminal("ifBlock");
            var elseIfBlock  = new NonTerminal("elseIfBlock");
            var optElseBlock = new NonTerminal("optElseBlock");

            var caseBlock  = new NonTerminal("caseBlock");
            var labelBlock = new NonTerminal("labelBlock");

            var functionCall       = new NonTerminal("functionCall");
            var optArgs            = new NonTerminal("optArgs");
            var args               = new NonTerminal("args");
            var functionDefinition = new NonTerminal("functionDefinition");
            var optParams          = new NonTerminal("optParams");
            var parameters         = new NonTerminal("parameters");
            var parameter          = new NonTerminal("parameter");

            var io          = new NonTerminal("io");
            var optSameLine = new NonTerminal("optionalSameLine");

            var loop     = new NonTerminal("loop");
            var forLoop  = new NonTerminal("forLoop");
            var exitLoop = new NonTerminal("exitLoop");

            var and        = new NonTerminal("and");
            var or         = new NonTerminal("or");
            var not        = new NonTerminal("not");
            var result     = new NonTerminal("result");
            var recordList = new NonTerminal("recordList");
            var type       = new NonTerminal("type");
            var memberCall = new NonTerminal("memberCall");
            var range      = new NonTerminal("range");
            var boolean    = new NonTerminal("boolean");
            var ioArgs     = new NonTerminal("ioArgs");
            var newer      = new NonTerminal("new");

            //3. BNF rules
            varType.Rule = ToTerm("int") | "nat" | "string" | "real" | "boolean" | "array" + range + "of" + varType | ToTerm("flexible") + "array" + range + "of" + varType | "record" + recordList + "end" + "record" |
                           "int1" | "int2" | "int4" | "real1" | "real2" | "real4" | "nat1" | "nat2" | "nat4" | ToTerm("char") + "(" + num + ")" | ToTerm("string") + "(" + num + ")" | iden;
            range.Rule         = Expr + ".." + Expr;
            setEqual.Rule      = ToTerm(":=") + Expr;
            typeSpecifier.Rule = ToTerm(":") + varType;
            Expr.Rule          = num | iden | BinExpr | ParExpr | stringLiteral | unExpr | functionCall | memberCall | boolean;
            BinOp.Rule         = ToTerm("-") | "*" | "/" | "**" | "+" | "div" | "mod" | and | or | "=" | ">" | "<" | ">=" | "<=" | "~=" | "not=";
            BinOp.Precedence   = 1;
            unOp.Rule          = not | "-";
            unOp.Precedence    = 2;

            BinExpr.Rule = Expr + BinOp + Expr;
            unExpr.Rule  = unOp + Expr;
            ParExpr.Rule = "(" + Expr + ")";
            boolean.Rule = ToTerm("true") | "false";

            assignment.Rule = expandedIdentifier + setEqual;

            optArgs.Rule = args | Empty;
            args.Rule    = MakePlusRule(args, ToTerm(","), Expr);
            //args.Rule = Expr + "," + args | Expr;
            functionCall.Rule = iden + "(" + optArgs + ")";

            optSameLine.Rule = ToTerm("..") | Empty;
            io.Rule          = ToTerm("put") + args + optSameLine | ToTerm("get") + args | ToTerm("put") + ":" + args + optSameLine | ToTerm("get") + ":" + args | ToTerm("open") + ":" + iden + "," + Expr + "," + ioArgs;
            ioArgs.Rule      = ToTerm("get") | "put" | "write" | "read" | "seek" | "tell" | ioArgs + "," + ioArgs;

            newer.Rule = ToTerm("new") + iden + "," + Expr;

            optParams.Rule          = ToTerm("(") + parameters + ")" | ToTerm("(") + ")" | Empty;
            parameters.Rule         = parameter + "," + parameters | parameter;
            parameter.Rule          = idenList + typeSpecifier | "var" + idenList + typeSpecifier;
            functionDefinition.Rule = "function" + iden + optParams + typeSpecifier + Program + "end" + iden
                                      | "fcn" + iden + optParams + typeSpecifier + Program + "end" + iden
                                      | "procedure" + iden + optParams + Program + "end" + iden
                                      | "proc" + iden + optParams + Program + "end" + iden;

            ifBlock.Rule      = ToTerm("if") + Expr + ToTerm("then") + Program + elseIfBlock + optElseBlock + ToTerm("end") + "if";
            elseIfBlock.Rule  = ToTerm("elsif") + Expr + ToTerm("then") + Program + elseIfBlock | Empty;
            optElseBlock.Rule = ToTerm("else") + Program | Empty;

            caseBlock.Rule  = ToTerm("case") + iden + "of" + labelBlock + "end case";
            labelBlock.Rule = ToTerm("label") + Expr + ":" + Program + labelBlock | ToTerm("label") + ":" + labelBlock | Empty;

            idenList.Rule            = iden + "," + idenList | iden;
            varOrConst.Rule          = ToTerm("var") | "const";
            variableDeclaration.Rule = varOrConst + idenList | varOrConst + idenList + setEqual | varOrConst + idenList + typeSpecifier | varOrConst + idenList + typeSpecifier + setEqual;

            loop.Rule     = "loop" + Program + "end" + "loop";
            forLoop.Rule  = "for" + ("decreasing" | Empty) + iden + ":" + (range | iden) + Program + "end" + "for";
            exitLoop.Rule = ToTerm("exit") | ToTerm("exit") + "when" + Expr;

            and.Rule        = ToTerm("and") | "&";
            or.Rule         = ToTerm("or") | "|";
            not.Rule        = ToTerm("not") | "~" | "!";
            result.Rule     = "result" + Expr | "return" + Expr;
            recordList.Rule = iden + typeSpecifier + recordList | Empty;
            type.Rule       = "type" + iden + typeSpecifier;
            memberCall.Rule = expandedIdentifier + "." + expandedIdentifier;
            //memberCall.Rule = iden + "." + functionCall | iden + "." + iden | iden + "." + memberCall;

            expandedIdentifier.Rule = iden | functionCall | memberCall;
            Statement.Rule          = functionCall | memberCall | iden | variableDeclaration | ifBlock | caseBlock | functionCall | functionDefinition | io | assignment | result | loop | forLoop | type | newer | exitLoop;
            Program.Rule            = Statement + Program | Empty;
            this.Root = Program;

            //4. Set operator precendence and associativity
            RegisterOperators(05, Associativity.Left, "not");
            RegisterOperators(10, Associativity.Left, "=", "not=");
            RegisterOperators(30, Associativity.Left, "+", "-");
            RegisterOperators(40, Associativity.Left, "*", "/", "div", "mod");
            RegisterOperators(50, Associativity.Right, "**");


            //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree
            MarkPunctuation("(", ")", ",");
            RegisterBracePair("(", ")");
            MarkTransient(Expr, BinOp, ParExpr);

            this.LanguageFlags = LanguageFlags.NewLineBeforeEOF;
        }
Exemplo n.º 23
0
        public CilGrammar()
            : base(true)
        {
            LanguageFlags = LanguageFlags.CreateAst;

            // comments

            var SINGLELINECOMMENT = new CommentTerminal("SINGLELINECOMMENT", "//", "\n", "\r\n");

            ConfigureAstNode(SINGLELINECOMMENT);

            NonGrammarTerminals.Add(SINGLELINECOMMENT);

            // lexical tokens

            var HEXBYTE = new RegexBasedTerminal("HEXBYTE", @"[A-F0-9]{2}"); // DOCS: not specified in ECMA grammar

            ConfigureAstNode(HEXBYTE);

            var DOTTEDNAME = CreateNonTerminal("DOTTEDNAME");

            DOTTEDNAME.Rule = _("TODO: DOTTEDNAME");
            ConfigureAstNode(DOTTEDNAME);

            var ID = new IdentifierTerminal("ID");

            ID.AddPrefix("$", IdOptions.None); // DOCS: ECMA page 110
            ConfigureAstNode(ID);

            var QSTRING = new StringLiteral("QSTRING", "\"");

            ConfigureAstNode(QSTRING);

            var SQSTRING = new StringLiteral("SQSTRING", "'");

            ConfigureAstNode(SQSTRING);

            var INT32 = new NumberLiteral("INT32", NumberOptions.AllowSign | NumberOptions.IntOnly);

            INT32.AddPrefix("0x", NumberOptions.Hex);
            INT32.DefaultIntTypes = new TypeCode[] { TypeCode.Int32 };
            ConfigureAstNode(INT32);

            var INT64 = new NumberLiteral("INT64", NumberOptions.AllowSign | NumberOptions.IntOnly);

            INT64.AddPrefix("0x", NumberOptions.Hex);
            INT64.DefaultIntTypes = new TypeCode[] { TypeCode.Int64 };
            ConfigureAstNode(INT64);

            var FLOAT64 = new NumberLiteral("FLOAT64", NumberOptions.AllowStartEndDot | NumberOptions.AllowSign);

            ConfigureAstNode(FLOAT64);

            // non-terminals

            var decls               = CreateNonTerminal("decls");
            var decl                = CreateNonTerminal("decl");
            var compQstring         = CreateNonTerminal("compQstring");
            var languageDecl        = CreateNonTerminal("languageDecl");
            var customAttrDecl      = CreateNonTerminal("customAttrDecl");
            var moduleHead          = CreateNonTerminal("moduleHead");
            var vtfixupDecl         = CreateNonTerminal("vtfixupDecl");
            var vtableDecl          = CreateNonTerminal("vtableDecl");
            var nameSpaceHead       = CreateNonTerminal("nameSpaceHead");
            var classHead           = CreateNonTerminal("classHead");
            var classAttr           = CreateNonTerminal("classAttr");
            var extendsClause       = CreateNonTerminal("extendsClause");
            var implClause          = CreateNonTerminal("implClause");
            var classNames          = CreateNonTerminal("classNames");
            var classDecls          = CreateNonTerminal("classDecls");
            var classDecl           = CreateNonTerminal("classDecl");
            var fieldDecl           = CreateNonTerminal("fieldDecl");
            var atOpt               = CreateNonTerminal("atOpt");
            var initOpt             = CreateNonTerminal("initOpt");
            var repeatOpt           = CreateNonTerminal("repeatOpt");
            var customHead          = CreateNonTerminal("customHead");
            var customHeadWithOwner = CreateNonTerminal("customHeadWithOwner");
            var memberRef           = CreateNonTerminal("memberRef");
            var customType          = CreateNonTerminal("customType");
            var ownerType           = CreateNonTerminal("ownerType");
            var eventHead           = CreateNonTerminal("eventHead");
            var eventDecls          = CreateNonTerminal("eventDecls");
            var propHead            = CreateNonTerminal("propHead");
            var propDecls           = CreateNonTerminal("propDecls");
            var methodHeadPart1     = CreateNonTerminal("methodHeadPart1");
            var methodHead          = CreateNonTerminal("methodHead");
            var methAttr            = CreateNonTerminal("methAttr");
            var pinvAttr            = CreateNonTerminal("pinvAttr");
            var methodName          = CreateNonTerminal("methodName");
            var paramAttr           = CreateNonTerminal("paramAttr");
            var fieldAttr           = CreateNonTerminal("fieldAttr");
            var implAttr            = CreateNonTerminal("implAttr");
            var localsHead          = CreateNonTerminal("localsHead");
            var methodDecl          = CreateNonTerminal("methodDecl");
            var scopeBlock          = CreateNonTerminal("scopeBlock");
            var sehBlock            = CreateNonTerminal("sehBlock");
            var methodDecls         = CreateNonTerminal("methodDecls");
            var dataDecl            = CreateNonTerminal("dataDecl");
            var ddHead              = CreateNonTerminal("ddHead");
            var tls                = CreateNonTerminal("tls");
            var ddBody             = CreateNonTerminal("ddBody");
            var ddItemList         = CreateNonTerminal("ddItemList");
            var ddItemCount        = CreateNonTerminal("ddItemCount");
            var ddItem             = CreateNonTerminal("ddItem");
            var fieldInit          = CreateNonTerminal("fieldInit");
            var bytearrayhead      = CreateNonTerminal("bytearrayhead");
            var bytes              = CreateNonTerminal("bytes");
            var hexbytes           = CreateNonTerminal("hexbytes");
            var instr_r_head       = CreateNonTerminal("instr_r_head");
            var instr_tok_head     = CreateNonTerminal("instr_tok_head");
            var methodSpec         = CreateNonTerminal("methodSpec");
            var instr              = CreateNonTerminal("instr");
            var sigArgs0           = CreateNonTerminal("sigArgs0");
            var sigArgs1           = CreateNonTerminal("sigArgs1");
            var sigArg             = CreateNonTerminal("sigArg");
            var name1              = CreateNonTerminal("name1");
            var className          = CreateNonTerminal("className");
            var slashedName        = CreateNonTerminal("slashedName");
            var typeSpec           = CreateNonTerminal("typeSpec");
            var callConv           = CreateNonTerminal("callConv");
            var callKind           = CreateNonTerminal("callKind");
            var nativeType         = CreateNonTerminal("nativeType");
            var type               = CreateNonTerminal("type");
            var bounds1            = CreateNonTerminal("bounds1");
            var bound              = CreateNonTerminal("bound");
            var labels             = CreateNonTerminal("labels");
            var id                 = CreateNonTerminal("id");
            var int16s             = CreateNonTerminal("int16s");
            var int32              = CreateNonTerminal("int32");
            var int64              = CreateNonTerminal("int64");
            var float64            = CreateNonTerminal("float64");
            var secDecl            = CreateNonTerminal("secDecl");
            var psetHead           = CreateNonTerminal("psetHead");
            var nameValPairs       = CreateNonTerminal("nameValPairs");
            var nameValPair        = CreateNonTerminal("nameValPair");
            var truefalse          = CreateNonTerminal("truefalse");
            var caValue            = CreateNonTerminal("caValue");
            var secAction          = CreateNonTerminal("secAction");
            var extSourceSpec      = CreateNonTerminal("extSourceSpec");
            var fileDecl           = CreateNonTerminal("fileDecl");
            var hashHead           = CreateNonTerminal("hashHead");
            var assemblyHead       = CreateNonTerminal("assemblyHead");
            var asmAttr            = CreateNonTerminal("asmAttr");
            var assemblyDecls      = CreateNonTerminal("assemblyDecls");
            var assemblyDecl       = CreateNonTerminal("assemblyDecl");
            var asmOrRefDecl       = CreateNonTerminal("asmOrRefDecl");
            var publicKeyHead      = CreateNonTerminal("publicKeyHead");
            var publicKeyTokenHead = CreateNonTerminal("publicKeyTokenHead");
            var localeHead         = CreateNonTerminal("localeHead");
            var assemblyRefHead    = CreateNonTerminal("assemblyRefHead");
            var assemblyRefDecls   = CreateNonTerminal("assemblyRefDecls");
            var assemblyRefDecl    = CreateNonTerminal("assemblyRefDecl");
            var comtypeHead        = CreateNonTerminal("comtypeHead");
            var exportHead         = CreateNonTerminal("exportHead");
            var comtypeDecls       = CreateNonTerminal("comtypeDecls");
            var manifestResHead    = CreateNonTerminal("manifestResHead");
            var manresAttr         = CreateNonTerminal("manresAttr");
            var manifestResDecls   = CreateNonTerminal("manifestResDecls");
            var manifestResDecl    = CreateNonTerminal("manifestResDecl");

            // instructions

            var INSTR_NONE     = CreateNonTerminal("INSTR_NONE");
            var INSTR_VAR      = CreateNonTerminal("INSTR_VAR");
            var INSTR_I        = CreateNonTerminal("INSTR_I");
            var INSTR_I8       = CreateNonTerminal("INSTR_I8");
            var INSTR_R        = CreateNonTerminal("INSTR_R");
            var INSTR_BRTARGET = CreateNonTerminal("INSTR_BRTARGET");
            var INSTR_METHOD   = CreateNonTerminal("INSTR_METHOD");
            var INSTR_FIELD    = CreateNonTerminal("INSTR_FIELD");
            var INSTR_TYPE     = CreateNonTerminal("INSTR_TYPE");
            var INSTR_STRING   = CreateNonTerminal("INSTR_STRING");
            var INSTR_SIG      = CreateNonTerminal("INSTR_SIG");
            var INSTR_RVA      = CreateNonTerminal("INSTR_RVA");
            var INSTR_SWITCH   = CreateNonTerminal("INSTR_SWITCH");
            var INSTR_PHI      = CreateNonTerminal("INSTR_PHI");
            var INSTR_TOK      = CreateNonTerminal("INSTR_TOK");

            INSTR_NONE.Rule =
                _("add") |
                ___("add.ovf") |
                ___("add.ovf.un") |
                _("and") |
                _("arglist") |
                _("break") |
                _("ceq") |
                _("cgt") |
                ___("cgt.un") |
                _("ckfinite") |
                _("clt") |
                ___("clt.un") |
                ___("conv.i") |
                ___("conv.i1") |
                ___("conv.i2") |
                ___("conv.i4") |
                ___("conv.i8") |
                ___("conv.ovf.i") |
                ___("conv.ovf.i.un") |
                ___("conv.ovf.i1") |
                ___("conv.ovf.i1.un") |
                ___("conv.ovf.i2") |
                ___("conv.ovf.i2.un") |
                ___("conv.ovf.i4") |
                ___("conv.ovf.i4.un") |
                ___("conv.ovf.i8") |
                ___("conv.ovf.i8.un") |
                ___("conv.ovf.u") |
                ___("conv.ovf.u.un") |
                ___("conv.ovf.u1") |
                ___("conv.ovf.u1.un") |
                ___("conv.ovf.u2") |
                ___("conv.ovf.u2.un") |
                ___("conv.ovf.u4") |
                ___("conv.ovf.u4.un") |
                ___("conv.ovf.u8") |
                ___("conv.ovf.u8.un") |
                ___("conv.r.un") |
                ___("conv.r4") |
                ___("conv.r8") |
                ___("conv.u") |
                ___("conv.u1") |
                ___("conv.u2") |
                ___("conv.u4") |
                ___("conv.u8") |
                _("cpblk") |
                _("div") |
                ___("div.un") |
                _("dup") |
                _("endfault") |
                _("endfilter") |
                _("endfinally") |
                _("initblk") |
                ___("ldarg.0") |
                ___("ldarg.1") |
                ___("ldarg.2") |
                ___("ldarg.3") |
                ___("ldc.i4.0") |
                ___("ldc.i4.1") |
                ___("ldc.i4.2") |
                ___("ldc.i4.3") |
                ___("ldc.i4.4") |
                ___("ldc.i4.5") |
                ___("ldc.i4.6") |
                ___("ldc.i4.7") |
                ___("ldc.i4.8") |
                ___("ldc.i4.M1") |
                ___("ldc.i4.m1") | // DOCS: non present in ECMA grammar
                ___("ldelem.i") |
                ___("ldelem.i1") |
                ___("ldelem.i2") |
                ___("ldelem.i4") |
                ___("ldelem.i8") |
                ___("ldelem.r4") |
                ___("ldelem.r8") |
                ___("ldelem.ref") |
                ___("ldelem.u1") |
                ___("ldelem.u2") |
                ___("ldelem.u4") |
                ___("ldind.i") |
                ___("ldind.i1") |
                ___("ldind.i2") |
                ___("ldind.i4") |
                ___("ldind.i8") |
                ___("ldind.r4") |
                ___("ldind.r8") |
                ___("ldind.ref") |
                ___("ldind.u1") |
                ___("ldind.u2") |
                ___("ldind.u4") |
                _("ldlen") |
                ___("ldloc.0") |
                ___("ldloc.1") |
                ___("ldloc.2") |
                ___("ldloc.3") |
                _("ldnull") |
                _("localloc") |
                _("mul") |
                ___("mul.ovf") |
                ___("mul.ovf.un") |
                _("neg") |
                _("nop") |
                _("not") |
                _("or") |
                _("pop") |
                _("refanytype") |
                _("rem") |
                ___("rem.un") |
                _("ret") |
                _("rethrow") |
                _("shl") |
                _("shr") |
                ___("shr.un") |
                ___("stelem.i") |
                ___("stelem.i1") |
                ___("stelem.i2") |
                ___("stelem.i4") |
                ___("stelem.i8") |
                ___("stelem.r4") |
                ___("stelem.r8") |
                ___("stelem.ref") |
                ___("stind.i") |
                ___("stind.i1") |
                ___("stind.i2") |
                ___("stind.i4") |
                ___("stind.i8") |
                ___("stind.r4") |
                ___("stind.r8") |
                ___("stind.ref") |
                ___("stloc.0") |
                ___("stloc.1") |
                ___("stloc.2") |
                ___("stloc.3") |
                _("sub") |
                ___("sub.ovf") |
                ___("sub.ovf.un") |
                _("tail.") |
                _("throw") |
                _("volatile.") |
                _("xor");

            INSTR_VAR.Rule =
                _("ladrg") |
                ___("ldarg.s") |
                _("ldarga") |
                ___("ldarga.s") |
                _("ldloc") |
                ___("ldloc.s") |
                _("ldloca") |
                ___("ldloca.s") |
                _("starg") |
                ___("starg.s") |
                _("stloc") |
                ___("stloc.s");

            INSTR_I.Rule =
                ___("ldc.i4") |
                ___("ldc.i4.s") |
                _("unaligned.");

            INSTR_I8.Rule =
                ___("ldc.i8");

            INSTR_R.Rule =
                ___("ldc.r4") |
                ___("ldc.r8");

            INSTR_BRTARGET.Rule =
                _("beq") |
                ___("beq.s") |
                _("bge") |
                ___("bge.s") |
                ___("bge.un") |
                ___("bge.un.s") |
                _("bgt") |
                ___("bgt.s") |
                ___("bgt.un") |
                ___("bgt.un.s") |
                _("ble") |
                ___("ble.s") |
                ___("ble.un") |
                ___("ble.un.s") |
                _("blt") |
                ___("blt.s") |
                ___("blt.un") |
                ___("blt.un.s") |
                ___("bne.un") |
                ___("bne.un.s") |
                _("br") |
                ___("br.s") |
                _("brfalse") |
                ___("brfalse.s") |
                _("brtrue") |
                ___("brtrue.s") |
                _("leave") |
                ___("leave.s");

            INSTR_METHOD.Rule =
                _("call") |
                _("callvirt") |
                _("jmp") |
                _("ldftn") |
                _("ldvirtftn") |
                _("newobj");

            INSTR_FIELD.Rule =
                _("ldfld") |
                _("ldflda") |
                _("ldsfld") |
                _("ldsflda") |
                _("stfld") |
                _("stsfld");

            INSTR_TYPE.Rule =
                _("box") |
                _("castclass") |
                _("cpobj") |
                _("initobj") |
                _("isinst") |
                _("ldelem") | // DOCS: non-present in ECMA grammar
                _("ldelema") |
                _("ldobj") |
                _("mkrefany") |
                _("newarr") |
                _("refanyval") |
                _("sizeof") |
                _("stelem") | // DOCS: non-present in ECMA grammar
                _("stobj") |
                _("unbox") |
                ___("unbox.any"); // DOCS: non-present in ECMA grammar

            INSTR_STRING.Rule =
                _("ldstr");

            INSTR_SIG.Rule = _("TODO: INSTR_SIG");

            INSTR_RVA.Rule = _("TODO: INSTR_RVA");

            INSTR_SWITCH.Rule =
                _("switch");

            INSTR_PHI.Rule = _("TODO: INSTR_PHI");

            INSTR_TOK.Rule =
                _("ldtoken");

            // rules

            Root = decls;

            decls.Rule =
                Empty |
                decls + decl;

            decl.Rule =
                classHead + _("{") + classDecls + _("}") |
                nameSpaceHead + _("{") + decls + _("}") |
                methodHead + methodDecls + _("}") |
                fieldDecl |
                dataDecl |
                vtableDecl |
                vtfixupDecl |
                extSourceSpec |
                fileDecl |
                assemblyHead + _("{") + assemblyDecls + _("}") |
                assemblyRefHead + _("{") + assemblyRefDecls + _("}") |
                comtypeHead + _("{") + comtypeDecls + _("}") |
                manifestResHead + _("{") + manifestResDecls + _("}") |
                moduleHead |
                secDecl |
                customAttrDecl |
                _(".subsystem") + int32 |
                _(".corflags") + int32 |
                _(".file") + _("alignment") + int32 |
                _(".imagebase") + int64 |
                languageDecl |
                _(".stackreserve") + int64; // DOCS: not present in ECMA grammar

            compQstring.Rule =
                QSTRING |
                compQstring + _("+") + QSTRING;

            // TODO - languageDecl
            languageDecl.Rule = _("TODO: languageDecl");

            customAttrDecl.Rule =
                _(".custom") + customType |
                _(".custom") + customType + _("=") + compQstring |
                customHead + bytes + _(")") |
                _(".custom") + _("(") + ownerType + _(")") + customType |
                _(".custom") + _("(") + ownerType + _(")") + customType + _("=") + compQstring |
                customHeadWithOwner + bytes + _(")");

            moduleHead.Rule =
                _(".module") |
                _(".module") + name1 |
                _(".module") + _("extern") + name1;

            // TODO - vtfixupDecl
            vtfixupDecl.Rule = _("TODO: vtfixupDecl");

            // TODO - vtableDecl
            vtableDecl.Rule = _("TODO: vtableDecl");

            // TODO - nameSpaceHead
            nameSpaceHead.Rule = _("TODO: nameSpaceHead");

            classHead.Rule =
                _(".class") + classAttr + id + extendsClause + implClause |
                _(".class") + classAttr + name1 + extendsClause + implClause; // DOCS: not present in ECMA grammar

            classAttr.Rule =
                Empty |
                classAttr + _("public") |
                classAttr + _("private") |
                classAttr + _("value") |
                classAttr + _("enum") |
                classAttr + _("interface") |
                classAttr + _("sealed") |
                classAttr + _("abstract") |
                classAttr + _("auto") |
                classAttr + _("sequential") |
                classAttr + _("explicit") |
                classAttr + _("ansi") |
                classAttr + _("unicode") |
                classAttr + _("autochar") |
                classAttr + _("import") |
                classAttr + _("serializable") |
                classAttr + _("nested") + _("public") |
                classAttr + _("nested") + _("private") |
                classAttr + _("nested") + _("family") |
                classAttr + _("nested") + _("assembly") |
                classAttr + _("nested") + _("famandassem") |
                classAttr + _("nested") + _("famorassem") |
                classAttr + _("beforefieldinit") |
                classAttr + _("specialname") |
                classAttr + _("rtspecialname");

            extendsClause.Rule =
                Empty |
                _("extends") + className;

            implClause.Rule =
                Empty |
                _("implements") + classNames;

            classNames.Rule =
                className + _(",") + className |
                className;

            classDecls.Rule =
                Empty |
                classDecls + classDecl;

            classDecl.Rule =
                methodHead + methodDecls + _("}") |
                classHead + _("{") + classDecls + _("}") |
                eventHead + _("{") + eventDecls + _("}") |
                propHead + _("{") + propDecls + _("}") |
                fieldDecl |
                dataDecl |
                secDecl |
                extSourceSpec |
                customAttrDecl |
                _(".size") + int32 |
                _(".pack") + int32 |
                exportHead + _("{") + comtypeDecls + _("}") |
                _(".override") + typeSpec + _("::") + methodName + _("with") + callConv + type + typeSpec + _("::") + methodName + _("(") + sigArgs0 + _(")") |
                languageDecl;

            fieldDecl.Rule =
                _(".field") + repeatOpt + fieldAttr + type + id + atOpt + initOpt;

            atOpt.Rule =
                Empty |
                _("at") + id;

            initOpt.Rule =
                Empty |
                _("=") + fieldInit;

            repeatOpt.Rule =
                Empty |
                _("[") + int32 + _("]");

            customHead.Rule =
                _(".custom") + customType + _("=") + _("(");

            customHeadWithOwner.Rule =
                _(".custom") + _("(") + ownerType + _(")") + customType + _("=") + _("(");

            memberRef.Rule =
                methodSpec + callConv + type + typeSpec + _("::") + methodName + _("(") + sigArgs0 + _(")") |
                methodSpec + callConv + type + methodName + _("(") + sigArgs0 + _(")") |
                _("field") + type + typeSpec + _("::") + id |
                _("field") + type + id;

            customType.Rule =
                callConv + type + typeSpec + _("::") + _(".ctor") + _("(") + sigArgs0 + _(")") |
                callConv + type + _(".ctor") + _("(") + sigArgs0 + _(")");

            ownerType.Rule =
                typeSpec |
                memberRef;

            // TODO - eventHead
            eventHead.Rule = _("TODO: eventHead");

            // TODO - eventDecls
            eventDecls.Rule = _("TODO: eventDecls");

            // TODO - propHead
            propHead.Rule = _("TODO: propHead");

            // TODO - propDecls
            propDecls.Rule = _("TODO: propDecls");

            methodHeadPart1.Rule =
                _(".method");

            methodHead.Rule =
                methodHeadPart1 + methAttr + callConv + paramAttr + type + methodName + _("(") + sigArgs0 + _(")") + implAttr + _("{") |
                methodHeadPart1 + methAttr + callConv + paramAttr + type + _("marshal") + _("(") + nativeType + _(")") + methodName + _("(") + sigArgs0 + _(")") + implAttr + _("{");

            methAttr.Rule =
                Empty |
                methAttr + _("static") |
                methAttr + _("public") |
                methAttr + _("private") |
                methAttr + _("family") |
                methAttr + _("final") |
                methAttr + _("specialname") |
                methAttr + _("virtual") |
                methAttr + _("abstract") |
                methAttr + _("assembly") |
                methAttr + _("famandassem") |
                methAttr + _("famorassem") |
                methAttr + _("privatescope") |
                methAttr + _("hidebysig") |
                methAttr + _("newslot") |
                methAttr + _("rtspecialname") |
                methAttr + _("unmanagedexp") |
                methAttr + _("reqsecobj") |
                methAttr + _("pinvokeimpl") + _("(") + compQstring + _("as") + compQstring + pinvAttr + _(")") |
                methAttr + _("pinvokeimpl") + _("(") + compQstring + pinvAttr + _(")") |
                methAttr + _("pinvokeimpl") + _("(") + pinvAttr + _(")");

            // TODO - pinvAttr
            pinvAttr.Rule = _("TODO: pinvAttr");

            methodName.Rule =
                _(".ctor") |
                _(".cctor") |
                name1;

            fieldAttr.Rule =
                Empty |
                fieldAttr + _("static") |
                fieldAttr + _("public") |
                fieldAttr + _("private") |
                fieldAttr + _("family") |
                fieldAttr + _("initonly") |
                fieldAttr + _("rtspecialname") |
                fieldAttr + _("specialname") |
                fieldAttr + _("pinvokeimpl") + _("(") + compQstring + _("as") + compQstring + pinvAttr + _(")") |
                fieldAttr + _("pinvokeimpl") + _("(") + compQstring + pinvAttr + _(")") |
                fieldAttr + _("pinvokeimpl") + _("(") + pinvAttr + _(")") |
                fieldAttr + _("marshal") + _("(") + nativeType + _(")") |
                fieldAttr + _("assembly") |
                fieldAttr + _("famandassem") |
                fieldAttr + _("famorassem") |
                fieldAttr + _("privatescope") |
                fieldAttr + _("literal") |
                fieldAttr + _("notserialized");

            paramAttr.Rule =
                Empty |
                paramAttr + _("[") + _("in") + _("]") |
                paramAttr + _("[") + _("out") + _("]") |
                paramAttr + _("[") + _("opt") + _("]") |
                paramAttr + _("[") + int32 + _("]");

            implAttr.Rule =
                Empty |
                implAttr + _("native") |
                implAttr + _("cil") |
                implAttr + _("optil") |
                implAttr + _("managed") |
                implAttr + _("unmanaged") |
                implAttr + _("forwardref") |
                implAttr + _("preservesig") |
                implAttr + _("runtime") |
                implAttr + _("internalcall") |
                implAttr + _("synchronized") |
                implAttr + _("noinlining");

            localsHead.Rule =
                _(".locals");

            methodDecl.Rule =
                _(".emitbyte") + int32 |
                sehBlock |
                _(".maxstack") + int32 |
                localsHead + _("(") + sigArgs0 + _(")") |
                localsHead + _("init") + _("(") + sigArgs0 + _(")") |
                _(".entrypoint") |
                _(".zeroinit") |
                dataDecl |
                instr |
                id + _(":") |
                secDecl |
                extSourceSpec |
                languageDecl |
                customAttrDecl |
                _(".export") + _("[") + int32 + _("]") |
                _(".export") + _("[") + int32 + _("]") + _("as") + id |
                _(".vtentry") + int32 + _(":") + int32 |
                _(".override") + typeSpec + _("::") + methodName |
                scopeBlock |
                _(".param") + _("[") + int32 + _("]") + initOpt;

            // TODO - scopeBlock
            scopeBlock.Rule = _("TODO: scopeBlock");

            // TODO - sehBlock
            sehBlock.Rule = _("TODO: sehBlock");

            methodDecls.Rule =
                Empty |
                methodDecls + methodDecl;

            dataDecl.Rule =
                ddHead + ddBody;

            ddHead.Rule =
                _(".data") + tls + id + _("=") |
                _(".data") + tls;

            tls.Rule =
                Empty |
                _("tls") |
                _("cil"); // DOCS: non-present in ECMA grammar

            ddBody.Rule =
                _("{") + ddItemList + _("}") |
                ddItem;

            ddItemList.Rule =
                ddItem + _(",") + ddItemList |
                ddItem;

            ddItemCount.Rule =
                Empty |
                _("[") + int32 + _("]");

            ddItem.Rule =
                _("char") + _("*") + _("(") + compQstring + _(")") |
                _("&") + _("(") + id + _(")") |
                bytearrayhead + bytes + _(")") |
                _("float32") + _("(") + float64 + _(")") + ddItemCount |
                _("float64") + _("(") + float64 + _(")") + ddItemCount |
                _("int64") + _("(") + int64 + _(")") + ddItemCount |
                _("int32") + _("(") + int32 + _(")") + ddItemCount |
                _("int16") + _("(") + int32 + _(")") + ddItemCount |
                _("int8") + _("(") + int32 + _(")") + ddItemCount |
                _("float32") + ddItemCount |
                _("float64") + ddItemCount |
                _("int64") + ddItemCount |
                _("int32") + ddItemCount |
                _("int16") + ddItemCount |
                _("int8") + ddItemCount;

            fieldInit.Rule =
                _("float32") + _("(") + float64 + _(")") |
                _("float64") + _("(") + float64 + _(")") |
                _("float32") + _("(") + int64 + _(")") |
                _("float64") + _("(") + int64 + _(")") |
                _("int64") + _("(") + int64 + _(")") |
                _("int32") + _("(") + int64 + _(")") |
                _("int16") + _("(") + int64 + _(")") |
                _("char") + _("(") + int64 + _(")") |
                _("int8") + _("(") + int64 + _(")") |
                _("uint8") + _("(") + int64 + _(")") | // DOCS: non-present in ECMA grammar
                _("bool") + _("(") + truefalse + _(")") |
                compQstring |
                bytearrayhead + bytes + _(")") |
                _("nullref");

            bytearrayhead.Rule =
                _("bytearray") + _("(");

            bytes.Rule =
                Empty |
                hexbytes;

            hexbytes.Rule =
                HEXBYTE |
                hexbytes + HEXBYTE;

            // TODO - instr_r_head
            instr_r_head.Rule = _("TODO: instr_r_head");

            instr_tok_head.Rule =
                INSTR_TOK;

            // TODO - methodSpec
            methodSpec.Rule = _("TODO: methodSpec");

            instr.Rule =
                INSTR_NONE |
                INSTR_VAR + int32 |
                INSTR_VAR + id |
                INSTR_I + int32 |
                INSTR_I8 + int64 |
                INSTR_R + float64 |
                INSTR_R + int64 |
                instr_r_head + bytes + _(")") |
                INSTR_BRTARGET + int32 |
                INSTR_BRTARGET + id |
                INSTR_METHOD + callConv + type + typeSpec + _("::") + methodName + _("(") + sigArgs0 + _(")") |
                INSTR_METHOD + callConv + type + methodName + _("(") + sigArgs0 + _(")") |
                INSTR_FIELD + type + typeSpec + _("::") + id |
                INSTR_FIELD + type + id |
                INSTR_TYPE + typeSpec |
                INSTR_STRING + compQstring |
                INSTR_STRING + bytearrayhead + bytes + _(")") |
                INSTR_SIG + callConv + type + _("(") + sigArgs0 + _(")") |
                INSTR_RVA + id |
                INSTR_RVA + int32 |
                instr_tok_head + ownerType |
                INSTR_SWITCH + _("(") + labels + _(")") |
                INSTR_PHI + int16s;

            sigArgs0.Rule =
                Empty |
                sigArgs1;

            sigArgs1.Rule =
                sigArg |
                sigArgs1 + _(",") + sigArg;

            sigArg.Rule =
                _("...") |
                paramAttr + type |
                paramAttr + type + id |
                paramAttr + type + _("marshal") + _("(") + nativeType + _(")") |
                paramAttr + type + _("marshal") + _("(") + nativeType + _(")") + id;

            name1.Rule =
                id |
                DOTTEDNAME |
                name1 + _(".") + name1;

            className.Rule =
                _("[") + name1 + _("]") + slashedName |
                _("[") + _(".module") + name1 + _("]") + slashedName |
                slashedName;

            slashedName.Rule =
                name1 |
                slashedName + _("/") + name1;

            typeSpec.Rule =
                className |
                _("[") + name1 + _("]") |
                _("[") + _(".module") + name1 + _("]") |
                type;

            callConv.Rule =
                _("instance") + callConv |
                _("explicit") + callConv |
                callKind;

            callKind.Rule =
                Empty |
                _("default") |
                _("vararg") |
                _("unmanaged") + _("cdecl") |
                _("unmanaged") + _("stdcall") |
                _("unmanaged") + _("thiscall") |
                _("unmanaged") + _("fastcall");

            // TODO - nativeType
            nativeType.Rule = _("TODO: nativeType");

            type.Rule =
                _("class") + className |
                _("object") |
                _("string") |
                _("value") + _("class") + className |
                _("valuetype") + className |
                type + _("[") + _("]") |
                type + ("[") + bounds1 + _("]") |
                type + _("value") + _("[") + int32 + _("]") |
                type + _("&") |
                type + _("*") |
                type + _("pinned") |
                type + _("modreq") + _("(") + className + _(")") |
                type + _("modopt") + _("(") + className + _(")") |
                _("!") + int32 |
                methodSpec + callConv + type + _("*") + _("(") + sigArgs0 + _(")") |
                _("typedref") |
                _("char") |
                _("void") |
                _("bool") |
                _("int8") |
                _("int16") |
                _("int32") |
                _("int64") |
                _("float32") |
                _("float64") |
                _("unsigned") + _("int8") |
                _("unsigned") + _("int16") |
                _("unsigned") + _("int32") |
                _("unsigned") + _("int64") |
                _("native") + _("int") |
                _("native") + _("unsigned") + _("int") |
                _("native") + _("float") |
                _("uint8") |  // DOCS: not present in ECMA grammar
                _("uint16") | // DOCS: not present in ECMA grammar
                _("uint32") | // DOCS: not present in ECMA grammar
                _("uint64");  // DOCS: not present in ECMA grammar

            bounds1.Rule =
                bound |
                bounds1 + _(",") + bound;

            bound.Rule =
                Empty |
                _("...") |
                int32 |
                int32 + _("...") + int32 |
                int32 + _("...");

            labels.Rule =
                Empty |
                id + _(",") + labels |
                int32 + _(",") + labels |
                id |
                int32;

            id.Rule =
                ID |
                SQSTRING;

            // TODO - int16s
            int16s.Rule = _("TODO: int16s");

            int32.Rule =
                INT32;

            int64.Rule =
                INT64;

            float64.Rule =
                FLOAT64 |
                _("float32") + _("(") + int32 + _(")") |
                _("float64") + _("(") + int64 + _(")");

            secDecl.Rule =
                _(".permission") + secAction + typeSpec + _("(") + nameValPairs + _(")") |
                _(".permission") + secAction + typeSpec |
                psetHead + bytes + _(")") |
                _(".permissionset") + secAction + _("=") + _("{") + nameValPairs + _("}"); // DOCS: non-present in ECMA script

            psetHead.Rule =
                _(".permissionset") + secAction + _("=") + _("(");

            nameValPairs.Rule =
                nameValPair |
                nameValPair + _(",") + nameValPairs;

            nameValPair.Rule =
                compQstring + _("=") + caValue |
                className + _("=") + caValue; // DOCS: non-present in ECMA script

            truefalse.Rule =
                _("true") |
                _("false");

            caValue.Rule =
                truefalse |
                int32 |
                _("int32") + ("(") + int32 + _(")") |
                compQstring |
                className + _("(") + _("int8") + _(":") + int32 + _(")") |
                className + _("(") + _("int16") + _(":") + int32 + _(")") |
                className + _("(") + _("int32") + _(":") + int32 + _(")") |
                className + _("(") + int32 + _(")") |
                _("{") + _("property") + _("bool") + SQSTRING + _("=") + _("bool") + _("(") + _("true") + _(")") + _("}"); // DOCS: non-present in ECMA script

            secAction.Rule =
                _("request") |
                _("demand") |
                _("assert") |
                _("deny") |
                _("permitonly") |
                _("linkcheck") |
                _("inheritcheck") |
                _("reqmin") |
                _("reqopt") |
                _("reqrefuse") |
                _("prejitgrant") |
                _("prejitdeny") |
                _("noncasdemand") |
                _("noncaslinkdemand") |
                _("noncasinheritance");

            // TODO - extSourceSpec
            extSourceSpec.Rule = _("TODO: extSourceSpec");

            // TODO - fileDecl
            fileDecl.Rule = _("TODO: fileDecl");

            // TODO - hashHead
            hashHead.Rule = _("TODO: hashHead");

            assemblyHead.Rule =
                _(".assembly") + asmAttr + name1;

            asmAttr.Rule =
                Empty |
                asmAttr + _("noappdomain") |
                asmAttr + _("noprocess") |
                asmAttr + _("nomachine");

            assemblyDecls.Rule =
                Empty |
                assemblyDecls + assemblyDecl;

            assemblyDecl.Rule =
                _(".hash") + _("algorithm") + int32 |
                secDecl |
                asmOrRefDecl;

            asmOrRefDecl.Rule =
                publicKeyHead + bytes + _(")") |
                _(".ver") + int32 + _(":") + int32 + _(":") + int32 + _(":") + int32 |
                _(".locale") + compQstring |
                localeHead + bytes + _(")") |
                customAttrDecl;

            // TODO - publicKeyHead
            publicKeyHead.Rule = _("TODO: publicKeyHead");

            publicKeyTokenHead.Rule =
                _(".publickeytoken") + _("=") + _("(");

            // TODO - localeHead
            localeHead.Rule = _("TODO: localeHead");

            assemblyRefHead.Rule =
                _(".assembly") + _("extern") + name1 |
                _(".assembly") + _("extern") + name1 + _("as") + name1;

            assemblyRefDecls.Rule =
                Empty |
                assemblyRefDecls + assemblyRefDecl;

            assemblyRefDecl.Rule =
                hashHead + bytes + _(")") |
                asmOrRefDecl |
                publicKeyTokenHead + bytes + _(")");

            // TODO - comtypeHead
            comtypeHead.Rule = _("TODO: comtypeHead");

            // TODO - exportHead
            exportHead.Rule = _("TODO: exportHead");

            // TODO - comtypeDecls
            comtypeDecls.Rule = _("TODO: comtypeDecls");

            manifestResHead.Rule =
                _(".mresource") + manresAttr + name1;

            manresAttr.Rule =
                Empty |
                manresAttr + _("public") |
                manresAttr + _("private");

            manifestResDecls.Rule =
                Empty |
                manifestResDecls + manifestResDecl;

            manifestResDecl.Rule =
                _(".file") + name1 + _("at") + int32 |
                _(".assembly") + _("extern") + name1 |
                customAttrDecl;
        }
Exemplo n.º 24
0
        public Gramatica() : base(caseSensitive: false)
        {
            #region ER

            /*NUMERO ENTERO*/
            RegexBasedTerminal numentero = new RegexBasedTerminal("Int", "[0-9]+");

            /*NUMERO DECIMAL*/
            RegexBasedTerminal numdecimal = new RegexBasedTerminal("double", "[0-9]+[.][0-9]+");

            /*IDENTIFICADOR*/
            IdentifierTerminal id = new IdentifierTerminal("id");

            /*STRING*/
            //CommentTerminal cadena = new CommentTerminal("String", "\"", ".", "\"");
            StringLiteral cadena = TerminalFactory.CreateCSharpString("String");
            /*STRING*/
            CommentTerminal importaciones = new CommentTerminal("String", "\"", ".[.].", "\"");

            /*CHAR*/
            StringLiteral caracter = TerminalFactory.CreateCSharpChar("Char");

            CommentTerminal comentarioLinea  = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n");
            CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/");

            #endregion

            //--------------------------------------RESERVADAS------------------------------------------------

            #region Terminal

            //TIPO DATO
            var rint    = ToTerm("Int");
            var rdouble = ToTerm("Double");
            var rstring = ToTerm("String");
            var rchar   = ToTerm("Char");
            var rbool   = ToTerm("Boolean");
            var rvoid   = ToTerm("Void");

            //PALABRAS RESERVADAS
            var importar = ToTerm("Import");
            var retornar = ToTerm("Return");
            var rprint   = ToTerm("Print");
            var rmain    = ToTerm("Main");
            var comparar = ToTerm("CompareTo");
            var rGetUser = ToTerm("GetUser");
            var rbreak   = ToTerm("Break");

            //OPERACIONES ARITMETICAS
            var mas      = ToTerm("+");
            var menos    = ToTerm("-");
            var por      = ToTerm("*");
            var dividir  = ToTerm("/");
            var modulo   = ToTerm("%");
            var potencia = ToTerm("^");

            //OPERACIONES RELACIONALES
            var igual2     = ToTerm("==");
            var diferente  = ToTerm("!=");
            var menor      = ToTerm("<");
            var mayor      = ToTerm(">");
            var menorigual = ToTerm("<=");
            var mayorigual = ToTerm(">=");

            //OPERACIONES LOGICAS
            var rand = ToTerm("&&");
            var ror  = ToTerm("||");
            var rxor = ToTerm("|&");
            var rnot = ToTerm("!");

            //OPERACIONES ESPECIALES
            var incremento = ToTerm("++");
            var decremento = ToTerm("--");
            var masigual   = ToTerm("+=");
            var menosigual = ToTerm("-=");

            //SENTENCIAS
            var rif     = ToTerm("If");
            var relse   = ToTerm("Else");
            var relseif = ToTerm("Else if");
            var rswitch = ToTerm("Switch");
            var rcase   = ToTerm("Case");
            var defecto = ToTerm("Default");
            var rfor    = ToTerm("For");
            var rdo     = ToTerm("Do");
            var rwhile  = ToTerm("While");

            //BOOLEANOS
            var rtrue  = ToTerm("true");
            var rfalse = ToTerm("false");

            //VARIOS
            var igual1    = ToTerm("=");
            var dospuntos = ToTerm(":");
            var coma      = ToTerm(",");
            var fin       = ToTerm(";");
            var apar      = ToTerm("(");
            var cpar      = ToTerm(")");
            var alla      = ToTerm("{");
            var clla      = ToTerm("}");
            var acor      = ToTerm("[");
            var ccor      = ToTerm("]");

            #endregion

            #region No terminales

            NonTerminal INICIO             = new NonTerminal("INICIO");
            NonTerminal IMPORTE            = new NonTerminal("IMPORTE");
            NonTerminal IMPORTES           = new NonTerminal("IMPORTES");
            NonTerminal CUERPO             = new NonTerminal("CUERPO");
            NonTerminal CONTENIDOGENERAL   = new NonTerminal("CONTENIDOGENERAL");
            NonTerminal ASIGNA             = new NonTerminal("ASIGNA");
            NonTerminal DECLARA            = new NonTerminal("DECLARA");
            NonTerminal LISTA_IDS          = new NonTerminal("LISTA_IDS");
            NonTerminal TIPODATO           = new NonTerminal("TIPODATO");
            NonTerminal VALOR              = new NonTerminal("VALOR");
            NonTerminal EXPRESION          = new NonTerminal("EXPRESION");
            NonTerminal METODO             = new NonTerminal("METODO");
            NonTerminal LISTAPARAMETROS    = new NonTerminal("LISTAPARAMETROS");
            NonTerminal CUERPOMETODO       = new NonTerminal("CUERPOMETODO");
            NonTerminal LLAMADAMETODO      = new NonTerminal("LLAMADAMETODO");
            NonTerminal IMPRIMIR           = new NonTerminal("IMPRIMIR");
            NonTerminal PARAMETROSLLAMADOS = new NonTerminal("PARAMETROSLLAMADOS");
            NonTerminal OPCIONAL           = new NonTerminal("OPCIONAL");
            NonTerminal SENTENCIARETURN    = new NonTerminal("SENTENCIARETURN");
            NonTerminal SENTENCIAWHILE     = new NonTerminal("SENTENCIAWHILE");
            NonTerminal SENTENCIADOWHILE   = new NonTerminal("SENTENCIADOWHILE");
            NonTerminal SENTENCIASWITCH    = new NonTerminal("SENTENCIASWITCH");
            NonTerminal CASO            = new NonTerminal("CASO");
            NonTerminal CASOS           = new NonTerminal("CASOS");
            NonTerminal DEFECTO         = new NonTerminal("DEFECTO");
            NonTerminal CONTENIDOSWITCH = new NonTerminal("CONTENIDOSWITCH");
            NonTerminal LISTA_ARRAY     = new NonTerminal(" LISTA_ARRAY");

            NonTerminal CONDICION        = new NonTerminal("CONDICION");
            NonTerminal CONDICIONPRIMA   = new NonTerminal("CONDICIONPRIMA");
            NonTerminal CONDICIONAL      = new NonTerminal("CONDICIONAL");
            NonTerminal LOGICOS          = new NonTerminal("LOGICOS");
            NonTerminal RELACIONAL       = new NonTerminal("RELACIONAL");
            NonTerminal SENTENCIAIF      = new NonTerminal("SENTENCIAIF");
            NonTerminal SENTENCIAIFAUX   = new NonTerminal("SENTENCIAIFAUX");
            NonTerminal SENTPRIMA        = new NonTerminal("SENTPRIMA");
            NonTerminal SENTENCIAELSEIF  = new NonTerminal("SENTENCIAELSEIF");
            NonTerminal SENTENCIA        = new NonTerminal("SENTENCIA");
            NonTerminal SENTENCIAS       = new NonTerminal("SENTENCIAS");
            NonTerminal SENTENCIAFOR     = new NonTerminal("SENTENCIAFOR");
            NonTerminal ASIGNACION_CORTO = new NonTerminal("ASIGNACION_CORTO");
            NonTerminal C = new NonTerminal("C");
            NonTerminal D = new NonTerminal("D");

            NonTerminal OPMATEMATICA  = new NonTerminal("OPMATEMATICA");
            NonTerminal OP            = new NonTerminal("OP");
            NonTerminal E             = new NonTerminal("E");
            NonTerminal L             = new NonTerminal("L");
            NonTerminal R             = new NonTerminal("R");
            NonTerminal INVOCAR       = new NonTerminal("INVOCAR");
            NonTerminal LIST_ATRIBUTO = new NonTerminal("LIST_ATRIBUTO");
            NonTerminal ACCESO_VECTOR = new NonTerminal("ACCESO_VECTOR");
            NonTerminal ATRIBUTO      = new NonTerminal("ATRIBUTO");

            #endregion

            #region Gramatica

            INICIO.Rule = IMPORTES + CUERPO;

            IMPORTES.Rule = IMPORTES + IMPORTE
                            | IMPORTE
                            | Empty;

            IMPORTE.Rule = importar + importaciones + fin;

            CUERPO.Rule = CUERPO + CONTENIDOGENERAL
                          | CONTENIDOGENERAL;

            CONTENIDOGENERAL.Rule = DECLARA
                                    | ASIGNA
                                    | METODO;

            DECLARA.Rule = id + dospuntos + TIPODATO + VALOR
                           | LISTA_IDS + dospuntos + TIPODATO + VALOR
                           | id + dospuntos + TIPODATO + acor + E + ccor + VALOR;

            ASIGNA.Rule = id + igual1 + C + fin
                          | id + igual1 + alla + LISTA_ARRAY + clla + fin
                          | id + acor + E + ccor + igual1 + C + fin
                          | id + acor + E + ccor + igual1 + id + acor + E + ccor + fin;

            VALOR.Rule = igual1 + C + fin
                         | fin
                         | alla + LISTA_ARRAY + clla + fin;

            LISTA_IDS.Rule = LISTA_IDS + coma + id
                             | id;

            LISTA_ARRAY.Rule = LISTA_ARRAY + coma + C
                               | C;

            TIPODATO.Rule = rint
                            | rdouble
                            | rstring
                            | rchar
                            | rbool
                            | rvoid;

            METODO.Rule = id + dospuntos + TIPODATO + apar + LISTAPARAMETROS + cpar + alla + SENTENCIAS + clla
                          | rmain + dospuntos + TIPODATO + apar + LISTAPARAMETROS + cpar + alla + SENTENCIAS + clla;

            LISTAPARAMETROS.Rule = LISTAPARAMETROS + coma + id + dospuntos + TIPODATO
                                   | id + dospuntos + TIPODATO
                                   | Empty;

            SENTENCIAS.Rule = SENTENCIAS + SENTENCIA
                              | SENTENCIA;

            SENTENCIA.Rule = ASIGNA
                             | DECLARA
                             | LLAMADAMETODO + fin
                             | IMPRIMIR
                             | SENTENCIAFOR
                             | SENTENCIAIF
                             | SENTENCIARETURN
                             | SENTENCIAWHILE
                             | SENTENCIADOWHILE
                             | SENTENCIASWITCH
                             | Empty;

            //---------LLAMADA A METODO
            LLAMADAMETODO.Rule = id + apar + PARAMETROSLLAMADOS + cpar
                                 | id + apar + cpar;

            PARAMETROSLLAMADOS.Rule = PARAMETROSLLAMADOS + coma + C
                                      | C;

            //---------PRINT
            IMPRIMIR.Rule = rprint + apar + C + cpar;

            //---------RETURN
            SENTENCIARETURN.Rule = C + fin
                                   | fin;

            //---------FOR
            //falta contenido
            SENTENCIAFOR.Rule = rfor + apar + id + dospuntos + TIPODATO + igual1 + E + fin + C + fin + OP + cpar + alla + SENTENCIAS + clla;

            //---------IF
            SENTENCIAIF.Rule = rif + SENTENCIAIFAUX;

            SENTENCIAIFAUX.Rule      = apar + C + cpar + alla + SENTENCIAS + clla + SENTENCIAELSEIF;
            SENTENCIAIFAUX.ErrorRule = SyntaxError + "}";

            SENTENCIAELSEIF.Rule = relse + SENTPRIMA
                                   | Empty;
            SENTENCIAELSEIF.ErrorRule = SyntaxError + "}";

            SENTPRIMA.Rule = rif + SENTENCIAIFAUX
                             | alla + SENTENCIAS + clla;

            //---------WHILE
            SENTENCIAWHILE.Rule      = rwhile + apar + C + cpar + alla + SENTENCIAS + clla;
            SENTENCIAWHILE.ErrorRule = SyntaxError + "}";

            //---------DO WHILE
            SENTENCIADOWHILE.Rule      = rdo + alla + SENTENCIAS + clla + rwhile + apar + C + cpar + fin;
            SENTENCIADOWHILE.ErrorRule = SyntaxError + ";";

            ///--------SWITCH
            SENTENCIASWITCH.Rule      = rswitch + apar + E + cpar + alla + SENTENCIAS + clla;
            SENTENCIASWITCH.ErrorRule = SyntaxError + "}";

            CONTENIDOSWITCH.Rule = CASOS + DEFECTO
                                   | CASOS
                                   | DEFECTO
                                   | Empty;

            CASOS.Rule = CASOS + CASO
                         | CASO;

            //---FALTA CONTENIDO
            CASO.Rule = rcase + C + dospuntos + SENTENCIAS + rbreak + fin;

            //---FALTA CONTENIDO
            DEFECTO.Rule = defecto + SENTENCIAS + dospuntos;

            //CONDICION
            ASIGNACION_CORTO.Rule = id + OP;

            OP.Rule = incremento | decremento;

            C.Rule = C + L + C
                     | E + R + E
                     | menos + E
                     | E;

            R.Rule = igual2
                     | diferente
                     | menor
                     | mayor
                     | menorigual
                     | mayorigual;

            L.Rule = ror
                     | rand
                     | rxor
                     | rnot;

            E.Rule = E + mas + E
                     | E + menos + E
                     | E + por + E
                     | E + dividir + E
                     | E + modulo + E
                     | E + potencia + E
                     | apar + E + cpar
                     | id
                     | numentero
                     | numdecimal
                     | cadena
                     | caracter
                     | rtrue
                     | rfalse;

            INVOCAR.Rule = id + apar + LIST_ATRIBUTO + cpar
                           | ACCESO_VECTOR;

            LIST_ATRIBUTO.Rule = LIST_ATRIBUTO + coma + ATRIBUTO
                                 | ATRIBUTO
                                 | Empty;

            ATRIBUTO.Rule = E;

            #endregion

            #region PREFERENCIAS
            Root = INICIO;

            NonGrammarTerminals.Add(comentarioLinea);
            NonGrammarTerminals.Add(comentarioBloque);

            MarkPunctuation(";", "(", ")", "{", "}", ":", "=", "[", "]", ",");

            this.RegisterOperators(1, Associativity.Left, mas, menos);
            this.RegisterOperators(2, Associativity.Left, por, dividir, modulo);
            this.RegisterOperators(3, Associativity.Right, potencia);
            this.RegisterOperators(5, igual2, diferente, menor, mayor, menorigual, mayorigual);
            this.RegisterOperators(6, Associativity.Left, ror);
            this.RegisterOperators(7, Associativity.Left, rxor);
            this.RegisterOperators(8, Associativity.Left, rand);
            this.RegisterOperators(9, Associativity.Left, diferente);
            this.RegisterOperators(10, apar, cpar);
            #endregion
        }
Exemplo n.º 25
0
        public ExpressionEvaluatorGrammar()
            : base(false)
        {
            GrammarComments =
                @"Irony expression evaluator. Case-insensitive. Supports big integers, float data types, variables, assignments,
arithmetic operations, augmented assignments (+=, -=), inc/dec (++,--), strings with embedded expressions; 
bool operations &,&&, |, ||; ternary '?:' operator.";
            // 1. Terminals
            var number = new NumberLiteral("number");

            //Let's allow big integers (with unlimited number of digits):
            number.DefaultIntTypes.AddRange(TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt);
            var identifier = new IdentifierTerminal("identifier");
            var comment    = new CommentTerminal("comment", "#", "\n", "\r");

            //comment must be added to NonGrammarTerminals list; it is not used directly in grammar rules,
            // so we add it to this list to let Scanner know that it is also a valid terminal.
            NonGrammarTerminals.Add(comment);
            var comma = ToTerm(",");

            //String literal with embedded expressions  ------------------------------------------------------------------
            var stringLit = new StringLiteral("string", "\"", StringOptions.AllowsAllEscapes | StringOptions.IsTemplate);

            stringLit.AddStartEnd("'", StringOptions.AllowsAllEscapes | StringOptions.IsTemplate);
            stringLit.AstConfig.NodeType = typeof(StringTemplateNode);
            var Expr             = new NonTerminal("Expr");      //declare it here to use in template definition
            var templateSettings = new StringTemplateSettings(); //by default set to Ruby-style settings

            templateSettings.ExpressionRoot = Expr;              //this defines how to evaluate expressions inside template
            SnippetRoots.Add(Expr);
            stringLit.AstConfig.Data = templateSettings;
            //--------------------------------------------------------------------------------------------------------

            // 2. Non-terminals
            var Term           = new NonTerminal("Term");
            var BinExpr        = new NonTerminal("BinExpr", typeof(BinaryOperationNode));
            var ParExpr        = new NonTerminal("ParExpr");
            var UnExpr         = new NonTerminal("UnExpr", typeof(UnaryOperationNode));
            var TernaryIfExpr  = new NonTerminal("TernaryIf", typeof(IfNode));
            var ArgList        = new NonTerminal("ArgList", typeof(ExpressionListNode));
            var FunctionCall   = new NonTerminal("FunctionCall", typeof(FunctionCallNode));
            var MemberAccess   = new NonTerminal("MemberAccess", typeof(MemberAccessNode));
            var IndexedAccess  = new NonTerminal("IndexedAccess", typeof(IndexedAccessNode));
            var ObjectRef      = new NonTerminal("ObjectRef"); // foo, foo.bar or f['bar']
            var UnOp           = new NonTerminal("UnOp");
            var BinOp          = new NonTerminal("BinOp", "operator");
            var PrefixIncDec   = new NonTerminal("PrefixIncDec", typeof(IncDecNode));
            var PostfixIncDec  = new NonTerminal("PostfixIncDec", typeof(IncDecNode));
            var IncDecOp       = new NonTerminal("IncDecOp");
            var AssignmentStmt = new NonTerminal("AssignmentStmt", typeof(AssignmentNode));
            var AssignmentOp   = new NonTerminal("AssignmentOp", "assignment operator");
            var Statement      = new NonTerminal("Statement");
            var Program        = new NonTerminal("Program", typeof(StatementListNode));

            // 3. BNF rules
            Expr.Rule           = Term | UnExpr | BinExpr | PrefixIncDec | PostfixIncDec | TernaryIfExpr;
            Term.Rule           = number | ParExpr | stringLit | FunctionCall | identifier | MemberAccess | IndexedAccess;
            ParExpr.Rule        = "(" + Expr + ")";
            UnExpr.Rule         = UnOp + Term + ReduceHere();
            UnOp.Rule           = ToTerm("+") | "-" | "!";
            BinExpr.Rule        = Expr + BinOp + Expr;
            BinOp.Rule          = ToTerm("+") | "-" | "*" | "/" | "**" | "==" | "<" | "<=" | ">" | ">=" | "!=" | "&&" | "||" | "&" | "|";
            PrefixIncDec.Rule   = IncDecOp + identifier;
            PostfixIncDec.Rule  = identifier + PreferShiftHere() + IncDecOp;
            IncDecOp.Rule       = ToTerm("++") | "--";
            TernaryIfExpr.Rule  = Expr + "?" + Expr + ":" + Expr;
            MemberAccess.Rule   = Expr + PreferShiftHere() + "." + identifier;
            AssignmentStmt.Rule = ObjectRef + AssignmentOp + Expr;
            AssignmentOp.Rule   = ToTerm("=") | "+=" | "-=" | "*=" | "/=";
            Statement.Rule      = AssignmentStmt | Expr | Empty;
            ArgList.Rule        = MakeStarRule(ArgList, comma, Expr);
            FunctionCall.Rule   = Expr + PreferShiftHere() + "(" + ArgList + ")";
            FunctionCall.NodeCaptionTemplate = "call #{0}(...)";
            ObjectRef.Rule     = identifier | MemberAccess | IndexedAccess;
            IndexedAccess.Rule = Expr + PreferShiftHere() + "[" + Expr + "]";

            Program.Rule = MakePlusRule(Program, NewLine, Statement);

            Root = Program;       // Set grammar root

            // 4. Operators precedence
            RegisterOperators(10, "?");
            RegisterOperators(15, "&", "&&", "|", "||");
            RegisterOperators(20, "==", "<", "<=", ">", ">=", "!=");
            RegisterOperators(30, "+", "-");
            RegisterOperators(40, "*", "/");
            RegisterOperators(50, Associativity.Right, "**");
            RegisterOperators(60, "!");
            // For precedence to work, we need to take care of one more thing: BinOp.
            //For BinOp which is or-combination of binary operators, we need to either
            // 1) mark it transient or 2) set flag TermFlags.InheritPrecedence
            // We use first option, making it Transient.

            // 5. Punctuation and transient terms
            MarkPunctuation("(", ")", "?", ":", "[", "]");
            RegisterBracePair("(", ")");
            RegisterBracePair("[", "]");
            MarkTransient(Term, Expr, Statement, BinOp, UnOp, IncDecOp, AssignmentOp, ParExpr, ObjectRef);

            // 7. Syntax error reporting
            MarkNotReported("++", "--");
            AddToNoReportGroup("(", "++", "--");
            AddToNoReportGroup(NewLine);
            AddOperatorReportGroup("operator");
            AddTermsReportGroup("assignment operator", "=", "+=", "-=", "*=", "/=");

            //8. Console
            ConsoleTitle    = "Irony Expression Evaluator";
            ConsoleGreeting =
                @"Irony Expression Evaluator 
  Supports variable assignments, arithmetic operators (+, -, *, /),
    augmented assignments (+=, -=, etc), prefix/postfix operators ++,--, string operations. 
  Supports big integer arithmetics, string operations.
  Supports strings with embedded expressions : ""name: #{name}""
Press Ctrl-C to exit the program at any time.
";
            ConsolePrompt          = "?";
            ConsolePromptMoreInput = "?";

            //9. Language flags.
            // Automatically add NewLine before EOF so that our BNF rules work correctly when there's no final line break in source
            LanguageFlags = LanguageFlags.NewLineBeforeEOF | LanguageFlags.CreateAst | LanguageFlags.SupportsBigInt;
        }
Exemplo n.º 26
0
        public Gramatica() : base(caseSensitive: false)
        {
            #region ER
            StringLiteral      CADENA        = new StringLiteral("cadena", "\"");
            var                ENTERO        = new NumberLiteral("entero");
            var                DECIMAL       = new RegexBasedTerminal("Decimal", "[0-9]+'.'[0-9]+");
            IdentifierTerminal IDENTIFICADOR = new IdentifierTerminal("ID");

            CommentTerminal comentarioLinea  = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n"); //si viene una nueva linea se termina de reconocer el comentario.
            CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/");
            #endregion

            #region Terminales
            var RIMPRIMIRLN = ToTerm("imprimirln");
            var RIMPRIMIR   = ToTerm("imprimir");
            var RNUMERO     = ToTerm("numero");
            var RMIENTRAS   = ToTerm("mientras");
            var RIF         = ToTerm("if");
            var RELSE       = ToTerm("else");
            var PTCOMA      = ToTerm(";");
            var LLAVIZQ     = ToTerm("{");
            var LLAVDER     = ToTerm("}");
            var PARIZQ      = ToTerm("(");
            var PARDER      = ToTerm(")");
            var MAS         = ToTerm("+");
            var MENOS       = ToTerm("-");
            var POR         = ToTerm("*");
            var DIVIDIDO    = ToTerm("/");
            var CONCAT      = ToTerm("&");
            var MENQUE      = ToTerm("<");
            var MAYQUE      = ToTerm(">");
            var IGUAL       = ToTerm("=");

            RegisterOperators(1, CONCAT);
            RegisterOperators(2, MAS, MENOS);
            RegisterOperators(3, POR, DIVIDIDO);

            NonGrammarTerminals.Add(comentarioLinea);
            NonGrammarTerminals.Add(comentarioBloque);

            #endregion

            #region No Terminales
            NonTerminal ini                = new NonTerminal("ini");
            NonTerminal instruccion        = new NonTerminal("instruccion");
            NonTerminal instrucciones      = new NonTerminal("instrucciones");
            NonTerminal expresion_numerica = new NonTerminal("expresion_numerica");
            NonTerminal expresion_cadena   = new NonTerminal("expresion_cadena");
            NonTerminal expresion_logica   = new NonTerminal("expresion_logica");
            #endregion

            #region Gramatica
            ini.Rule = instrucciones;
            ;

            instrucciones.Rule = instrucciones + instruccion
                                 | instruccion;

            instruccion.Rule = RIMPRIMIR + PARIZQ + expresion_cadena + PARDER + PTCOMA
                               | RMIENTRAS + PARIZQ + expresion_logica + PARDER + LLAVIZQ + instrucciones + LLAVDER
                               | RNUMERO + IDENTIFICADOR + PTCOMA
                               | IDENTIFICADOR + IGUAL + expresion_numerica + PTCOMA
                               | RIF + PARIZQ + expresion_logica + PARDER + LLAVIZQ + instrucciones + LLAVDER
                               | RIF + PARIZQ + expresion_logica + PARDER + LLAVIZQ + instrucciones + LLAVDER + RELSE + LLAVIZQ + instrucciones + LLAVDER
                               | RIMPRIMIRLN + PARIZQ + expresion_cadena + PARDER + PTCOMA;

            expresion_numerica.Rule = MENOS + expresion_numerica
                                      | expresion_numerica + MAS + expresion_numerica
                                      | expresion_numerica + MENOS + expresion_numerica
                                      | expresion_numerica + POR + expresion_numerica
                                      | expresion_numerica + DIVIDIDO + expresion_numerica
                                      | PARIZQ + expresion_numerica + PARDER
                                      | ENTERO
                                      | DECIMAL
                                      | IDENTIFICADOR;

            expresion_cadena.Rule = expresion_cadena + CONCAT + expresion_cadena
                                    | CADENA
                                    | expresion_numerica;

            expresion_logica.Rule = expresion_numerica + MAYQUE + expresion_numerica
                                    | expresion_numerica + MENQUE + expresion_numerica;

            #endregion

            #region Preferencias
            this.Root = ini;
            #endregion
        }
Exemplo n.º 27
0
        public gramatica(tablaErrores tabla, String archivo) : base(caseSensitive: false)//Diferencia entre mayusculas y minusculas
        {
            this.tablaErrores  = tabla;
            this.nombreArchivo = archivo;

            #region ER
            //////////////////////////////////////////
            //------------COMENTARIOS-----------------

            CommentTerminal comentariobloque = new CommentTerminal("comentariobloque", "$#", "#$");
            CommentTerminal comentariolinea  = new CommentTerminal("comentariolinea", "$$", "\n", "\r\n");
            /*Se ignoran los terminales solo se reconoce*/
            NonGrammarTerminals.Add(comentariobloque);
            NonGrammarTerminals.Add(comentariolinea);

            //////////////////////////////////////////
            //------------OTROS-----------------
            RegexBasedTerminal valBoolean = new RegexBasedTerminal("valBoolean", "(false|true|verdadero|falso)");

            StringLiteral valCaracter = new StringLiteral("valCaracter", "\'");
            StringLiteral valCadena   = new StringLiteral("valCadena", "\"");
            var           valCadena2  = new StringLiteral("valCadena2", "‘(.)*’");


            //RegexBasedTerminal valNumero = new RegexBasedTerminal("numeroValor", "[0-9]+");
            NumberLiteral valNumero  = new NumberLiteral("valNumero");
            var           valDecimal = new RegexBasedTerminal("valDecimal", "[0-9]+\\.[0-9]+");

            IdentifierTerminal valId = new IdentifierTerminal("valId");

            #endregion

            #region Terminales

            /*
             * =============================
             * Simbolos
             * =============================
             */


            var sMas   = ToTerm("+");
            var sMenos = ToTerm("-");
            var sPor   = ToTerm("*");
            var sDiv   = ToTerm("/");
            var sPot   = ToTerm("^");
            var sMod   = ToTerm("%");

            var sIgualacion     = ToTerm("==");
            var sDiferenciacion = ToTerm("!=");
            var sMenorQue       = ToTerm("<");
            var sMayorQue       = ToTerm(">");
            var sMenorIgualQue  = ToTerm("<=");
            var sMayorIgualQue  = ToTerm(">=");
            var sAnd            = ToTerm("&&");
            var sOr             = ToTerm("||");
            var sNot            = ToTerm("!");


            //
            var sAbreParent   = ToTerm("(");
            var sCierraParent = ToTerm(")");

            var sAbreLlave   = ToTerm("{");
            var sCierraLlave = ToTerm("}");

            var sAbreCorchete   = ToTerm("[");
            var sCierraCorchete = ToTerm("]");
            var sPunto          = ToTerm(".");
            var sComa           = ToTerm(",");
            var sPuntoComa      = ToTerm(";");
            var sArroba         = ToTerm("@");
            var sIgual          = ToTerm("=");

            var sCierraInterrogante = ToTerm("?");
            var sDosPuntos          = ToTerm(":");

            /*
             * =============================
             * Palabras reservadas
             * =============================
             */
            var tImport    = ToTerm("importar");
            var tClase     = ToTerm("clase");
            var tExtender  = ToTerm("extender");
            var tPadre     = ToTerm("padre");
            var tPrincipal = ToTerm("principal");
            var tOverride  = ToTerm("sobrescribir");
            var tNuevo     = ToTerm("nuevo");
            var tNulo      = ToTerm("nulo");
            var tVacio     = ToTerm("vacio");
            var tEste      = ToTerm("este");
            var tImprimir  = ToTerm("imprimir");
            var tRetorno   = ToTerm("retorno");
            var tSi        = ToTerm("si");
            var tSino      = ToTerm("sino");
            var tCaso      = ToTerm("caso");
            var tDe        = ToTerm("de");
            var tDefecto   = ToTerm("defecto");
            var tRomper    = ToTerm("romper");
            var tMientras  = ToTerm("mientras");
            var tContinuar = ToTerm("continuar");
            var tPara      = ToTerm("para");
            var tHacer     = ToTerm("hacer");
            var tRepetir   = ToTerm("repetir");
            var tHasta     = ToTerm("hasta");
            var tMensaje   = ToTerm("mensajes");
            var tSubCad    = ToTerm("subcad");
            var tPosCad    = ToTerm("poscad");
            var tRandom    = ToTerm("random");

            var tPi       = ToTerm("pi");
            var tSqrt     = ToTerm("sqrt");
            var tTangente = ToTerm("tan");
            var tCoseno   = ToTerm("cos");
            var tSeno     = ToTerm("sin");
            var tAbs      = ToTerm("abs");
            var tLog10    = ToTerm("log10");
            var tLog      = ToTerm("log");
            var tPow      = ToTerm("pow");
            var tMax      = ToTerm("max");
            var tMin      = ToTerm("min");
            var tFecha    = ToTerm("fecha");
            var tAhora    = ToTerm("ahora");
            var tHoy      = ToTerm("hoy");
            var tTam      = ToTerm("tam");
            var tSuper    = ToTerm("super");

            var tPagina          = ToTerm("pagina");
            var tTodo            = ToTerm("todo");
            var tCuadriculo      = ToTerm("cuadricula");
            var tNativo          = ToTerm("_nativo");
            var tEscribirArchivo = ToTerm("escribir_archivo");
            var tImagen          = ToTerm("imagen");
            var tVideo           = ToTerm("video");
            var tAudio           = ToTerm("audio");
            var tLen             = ToTerm("_len");
            var tNada            = ToTerm("nada");
            //tipos
            var tEntero     = ToTerm("entero");
            var tCadena     = ToTerm("cadena");
            var tDecimal    = ToTerm("decimal");
            var tBooleano   = ToTerm("booleano");
            var tfecha      = ToTerm("fecha");
            var tHora       = ToTerm("hora");
            var tFechaHora  = ToTerm("fechahora");
            var tPregunta   = ToTerm("pregunta");
            var tFormulario = ToTerm("formulario");
            var tRespuesta  = ToTerm("respuesta");
            var tMostrar    = ToTerm("mostrar");
            var tCalcular   = ToTerm("calcular");
            var tGrupo      = ToTerm("grupo");

            //visibilidad
            var tPublico   = ToTerm("publico");
            var tPrivado   = ToTerm("privado");
            var tProtegido = ToTerm("protegido");


            #endregion
            #region NoTerminales



            NonTerminal S                           = new NonTerminal("S");
            NonTerminal IMPORT                      = new NonTerminal("IMPORT");
            NonTerminal LST_IMPORT                  = new NonTerminal("LST_IMPORT");
            NonTerminal LST_CLASE                   = new NonTerminal("LST_CLASE");
            NonTerminal CLASE                       = new NonTerminal("CLASE");
            NonTerminal TIPO                        = new NonTerminal("TIPO");
            NonTerminal EXTENDER                    = new NonTerminal("EXTENDER");
            NonTerminal VISIBILIDAD                 = new NonTerminal("VISIBILIDAD");
            NonTerminal LST_PARAMETROS              = new NonTerminal("LST_PARAMETROS");
            NonTerminal PARAMETRO                   = new NonTerminal("PARAMETRO");
            NonTerminal LST_VAL                     = new NonTerminal("LST_VAL");
            NonTerminal CP_CLASE                    = new NonTerminal("CP_CLASE");
            NonTerminal CUERPO_CLASE                = new NonTerminal("CUERPO_CLASE");
            NonTerminal METODO                      = new NonTerminal("METODO");
            NonTerminal SOBRESCRITURA               = new NonTerminal("SOBRESCRITURA");
            NonTerminal MAIN                        = new NonTerminal("MAIN");
            NonTerminal CONSTRUCTOR                 = new NonTerminal("CONSTRUCTOR");
            NonTerminal FORMULARIO                  = new NonTerminal("FORMULARIO");
            NonTerminal PROCEDIMIENTOS_FORMULARIO   = new NonTerminal("PROCEDIMIENTOS_FORMULARIO");
            NonTerminal DECLARAR_VARIABLE_GLOBAL    = new NonTerminal("DECLARAR_VARIABLE_GLOBAL");
            NonTerminal DECLARAR_VARIABLE_SINVISIBI = new NonTerminal("DECLARAR_VARIABLE_SINVISIBI");
            NonTerminal VAL                         = new NonTerminal("VAL");
            NonTerminal LST_LLAVES_VAL              = new NonTerminal("LST_LLAVES_VAL");
            NonTerminal LLAVES_VAL_P                = new NonTerminal("LLAVES_VAL_P");
            NonTerminal VAR_ARREGLO                 = new NonTerminal("VAR_ARREGLO");
            NonTerminal LST_CORCHETES               = new NonTerminal("LST_CORCHETES");
            NonTerminal LST_CORCHETES_VAL           = new NonTerminal("LST_CORCHETES_VAL");
            NonTerminal ASIGNAR_VALOR               = new NonTerminal("ASIGNAR_VALOR");
            NonTerminal USAR_VARIABLE               = new NonTerminal("USAR_VARIABLE");
            NonTerminal USAR_VARIABLEP              = new NonTerminal("USAR_VARIABLEP");
            NonTerminal USAR_METODO                 = new NonTerminal("USAR_METODO");
            NonTerminal USAR_METODOP                = new NonTerminal("USAR_METODOP");
            NonTerminal LLAMADA_FORMULARIO          = new NonTerminal("LLAMADA_FORMULARIO");
            NonTerminal LST_ID                      = new NonTerminal("LST_ID");
            NonTerminal LST_CUERPO                  = new NonTerminal("LST_CUERPO");


            NonTerminal CUERPO            = new NonTerminal("CUERPO");
            NonTerminal RETORNO           = new NonTerminal("RETORNO");
            NonTerminal ROMPER            = new NonTerminal("ROMPER");
            NonTerminal CONTINUAR         = new NonTerminal("CONTINUAR");
            NonTerminal SENTENCIAS        = new NonTerminal("SENTENCIAS");
            NonTerminal SI                = new NonTerminal("SI");
            NonTerminal SINO_SI           = new NonTerminal("SINO_SI");
            NonTerminal SINO              = new NonTerminal("SINO");
            NonTerminal SI_SIMPLIFICADO   = new NonTerminal("SI_SIMPLIFICADO");
            NonTerminal CASO              = new NonTerminal("CASO");
            NonTerminal CUERPO_CASE       = new NonTerminal("CUERPO_CASE");
            NonTerminal WHILE             = new NonTerminal("WHILE");
            NonTerminal DOWHILE           = new NonTerminal("DOWHILE");
            NonTerminal REPETIR           = new NonTerminal("REPETIR");
            NonTerminal FOR               = new NonTerminal("FOR");
            NonTerminal FUNCIONES_NATIVAS = new NonTerminal("FUNCIONES_NATIVAS");
            NonTerminal IMPRIMIR          = new NonTerminal("IMPRIMIR");
            NonTerminal MENSAJE           = new NonTerminal("MENSAJE");
            NonTerminal OPE_TIPO          = new NonTerminal("OPE_TIPO");

            NonTerminal OPE_ARITME   = new NonTerminal("OPE_ARITME");
            NonTerminal TO_CADENA    = new NonTerminal("TO_CADENA");
            NonTerminal SUB_CAD      = new NonTerminal("SUB_CAD");
            NonTerminal POS_CAD      = new NonTerminal("POS_CAD");
            NonTerminal TO_BOOLEAN   = new NonTerminal("TO_BOOLEAN");
            NonTerminal TO_ENTERO    = new NonTerminal("TO_ENTERO");
            NonTerminal HOY          = new NonTerminal("HOY");
            NonTerminal AHORA        = new NonTerminal("AHORA");
            NonTerminal TO_FECHA     = new NonTerminal("TO_FECHA");
            NonTerminal TO_HORA      = new NonTerminal("TO_HORA");
            NonTerminal TO_FECHAHORA = new NonTerminal("TO_FECHAHORA");
            NonTerminal TAM          = new NonTerminal("TAM");
            NonTerminal RANDOM       = new NonTerminal("RANDOM");
            NonTerminal MIN          = new NonTerminal("MIN");
            NonTerminal MAX          = new NonTerminal("MAX");
            NonTerminal POTENCIA     = new NonTerminal("POTENCIA");
            NonTerminal LOGARITMO    = new NonTerminal("LOGARITMO");
            NonTerminal LOGARITMO10  = new NonTerminal("LOGARITMO10");
            NonTerminal ABSOLUTO     = new NonTerminal("ABSOLUTO");

            NonTerminal USAR_METO_VAR   = new NonTerminal("USAR_METO_VAR");
            NonTerminal SENO            = new NonTerminal("SENO");
            NonTerminal COSENO          = new NonTerminal("COSENO");
            NonTerminal TANGENTE        = new NonTerminal("TANGENTE");
            NonTerminal RAIZ            = new NonTerminal("RAIZ");
            NonTerminal PI              = new NonTerminal("PI");
            NonTerminal FUNC_MULTIMEDIA = new NonTerminal("FUNC_MULTIMEDIA");
            NonTerminal IMAGEN          = new NonTerminal("IMAGEN");
            NonTerminal AUDIO           = new NonTerminal("AUDIO");
            NonTerminal VIDEO           = new NonTerminal("VIDEO");
            NonTerminal VALOR           = new NonTerminal("VALOR");
            NonTerminal E = new NonTerminal("E");
            NonTerminal F = new NonTerminal("F");


            NonTerminal PAR_CORCHETES_VACIOS = new NonTerminal("PAR_CORCHETES_VACIOS");

            NonTerminal ID_VAR_FUNC = new NonTerminal("ID_VAR_FUNC");
            NonTerminal LST_PUNTOSP = new NonTerminal("LST_PUNTOSP");

            NonTerminal ASIG_VALOR = new NonTerminal("ASIG_VALOR");
            //NonTerminal LST_E = new NonTerminal("LST_E");

            NonTerminal SUPER = new NonTerminal("SUPER");

            NonTerminal CUERPO_PREGUNTA     = new NonTerminal("CUERPO_PREGUNTA");
            NonTerminal LST_CUERPO_PREGUNTA = new NonTerminal("LST_CUERPO_PREGUNTA");
            NonTerminal PREGUNTA            = new NonTerminal("PREGUNTA");
            NonTerminal GRUPO = new NonTerminal("GRUPO");



            NonTerminal PAR_CORCHETES_VAL = new NonTerminal("PAR_CORCHETES_VAL");

            NonTerminal PREGUNTA_NATIVA = new NonTerminal("PREGUNTA_NATIVA");

            NonTerminal ESCRIBIR_ARCHIVO = new NonTerminal("ESCRIBIR_ARCHIVO");

            NonTerminal LEN = new NonTerminal("LEN");

            #endregion

            #region Gramatica


            S.Rule = LST_IMPORT + LST_CLASE
                     | LST_CLASE;


            LST_IMPORT.Rule = MakeStarRule(LST_IMPORT, IMPORT);


            IMPORT.Rule = tImport + sAbreParent + valId + sPunto + valId + sCierraParent + sPuntoComa
                          | SyntaxError;

            LST_CLASE.Rule = MakeStarRule(LST_CLASE, CLASE);

            CLASE.Rule = tClase + valId + EXTENDER + sAbreLlave + CP_CLASE + sCierraLlave
                         | tClase + valId + VISIBILIDAD + EXTENDER + sAbreLlave + CP_CLASE + sCierraLlave;


            TIPO.Rule = tEntero
                        | tCadena
                        | tBooleano
                        | tDecimal
                        | tHora
                        | tfecha
                        | tFechaHora
                        | valId
                                 //  | tPregunta
                                 //  | tFormulario
                                 //  | tRespuesta
                        | tVacio //Para el metodo void, tengo que validar que no lo acepten las variables
            ;

            EXTENDER.Rule = tPadre + valId
                            | Empty;

            VISIBILIDAD.Rule = tPublico
                               | tPrivado
                               | tProtegido;



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Parametros
             |-------------------------------------------------------------------------------------------------------------------
             |
             */
            LST_PARAMETROS.Rule = MakeStarRule(LST_PARAMETROS, sComa, PARAMETRO);

            PARAMETRO.Rule = TIPO + VAR_ARREGLO;

            LST_VAL.Rule = MakeStarRule(LST_VAL, sComa, VALOR);

            //LST_E.Rule = MakePlusRule(LST_E, sComa, E);


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Cuerpo de la clase
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            CP_CLASE.Rule = MakeStarRule(CP_CLASE, CUERPO_CLASE);

            CUERPO_CLASE.Rule = CONSTRUCTOR
                                | DECLARAR_VARIABLE_GLOBAL + sPuntoComa
                                | METODO
                                //| SOBRESCRITURA
                                | MAIN


                                | FORMULARIO
                                | PREGUNTA
                                | GRUPO

                                | SyntaxError;
            ;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Funciones/Metodos
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            METODO.Rule = VISIBILIDAD + TIPO + VAR_ARREGLO + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                          | TIPO + VAR_ARREGLO + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave; //metodo void

            //SOBRESCRITURA.Rule = sArroba + tOverride + METODO;

            MAIN.Rule = tPrincipal + sAbreParent + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;

            CONSTRUCTOR.Rule = valId + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Declarar variable
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            DECLARAR_VARIABLE_GLOBAL.Rule = TIPO + VISIBILIDAD + VAR_ARREGLO + VAL
                                            | TIPO + VISIBILIDAD + VAR_ARREGLO //solo se declaro
                                            | DECLARAR_VARIABLE_SINVISIBI;



            DECLARAR_VARIABLE_SINVISIBI.Rule = TIPO + VAR_ARREGLO + VAL
                                               | TIPO + VAR_ARREGLO;//sin visibilidad y solo declarada



            VAL.Rule = sIgual + VALOR

                       /* | sIgual + tNuevo + valId + sAbreParent + LST_VAL + sCierraParent //aqui tengo que reconocer el-> nuevo opciones()
                        | sIgual + tNuevo + TIPO + LST_CORCHETES_VAL
                        | sIgual + LST_LLAVES_VAL
                        | sIgual + tNulo*/
            ;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Arreglos
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            /*
             |----------------------------------------------
             | Llaves
             */

            LST_LLAVES_VAL.Rule = MakePlusRule(LST_LLAVES_VAL, sComa, LLAVES_VAL_P);



            LLAVES_VAL_P.Rule = sAbreLlave + LST_LLAVES_VAL + sCierraLlave
                                | sAbreLlave + LST_VAL + sCierraLlave;


            /*
             |----------------------------------------------
             | Corchetes
             */


            VAR_ARREGLO.Rule = valId
                               | valId + LST_CORCHETES;

            LST_CORCHETES.Rule = MakePlusRule(LST_CORCHETES, PAR_CORCHETES_VACIOS);

            PAR_CORCHETES_VACIOS.Rule = sAbreCorchete + sCierraCorchete;

            PAR_CORCHETES_VAL.Rule = sAbreCorchete + E + sCierraCorchete;

            //PAR_CORCHETES_VAL.Rule = sAbreCorchete + VALOR + sCierraCorchete;

            LST_CORCHETES_VAL.Rule = MakePlusRule(LST_CORCHETES_VAL, PAR_CORCHETES_VAL);



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Para poder acceder a los metodos o variables
             |-------------------------------------------------------------------------------------------------------------------
             | Me va devolver un metodo () al final
             | Me va devolver un Id al final
             */


            ID_VAR_FUNC.Rule = ID_VAR_FUNC + LST_PUNTOSP

                               //| ID_VAR_FUNC + LST_CORCHETES_VAL // | LST_PUNTOSP //
                               | tEste + sPunto + valId
                               | valId
                               | tEste + sPunto + valId + sAbreParent + LST_VAL + sCierraParent
                               | valId + sAbreParent + LST_VAL + sCierraParent

                               //para hacer uso de corchetes
                               | tEste + sPunto + valId + LST_CORCHETES_VAL
                               | valId + LST_CORCHETES_VAL
                               | tEste + sPunto + valId + sAbreParent + LST_VAL + sCierraParent + LST_CORCHETES_VAL
                               | valId + sAbreParent + LST_VAL + sCierraParent + LST_CORCHETES_VAL;


            LST_PUNTOSP.Rule = sPunto + valId
                               | sPunto + valId + sAbreParent + LST_VAL + sCierraParent

                               //Corchetes
                               | sPunto + valId + LST_CORCHETES_VAL
                               | sPunto + valId + sAbreParent + LST_VAL + sCierraParent + LST_CORCHETES_VAL;



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Asignar valor
             |-------------------------------------------------------------------------------------------------------------------
             | Hay que validar que reciba un id, y no un idFUNC
             */



            ASIG_VALOR.Rule = ID_VAR_FUNC + VAL
                              | ID_VAR_FUNC + sMas + sMas
                              | ID_VAR_FUNC + sMenos + sMenos
                              // | ID_VAR_FUNC + LST_CORCHETES_VAL + VAL
            ;

            #region asgi

            /*
             *
             * USAR_METO_VAR.Rule = USAR_VARIABLEP + USAR_METO_VAR
             | USAR_VARIABLE
             | USAR_METODO;
             |
             |  //ASIGNAR_VALOR.Rule = VAL
             |  //    |
             |  ///    |  ;
             |
             |
             |  //#Usar variable
             |  //USAR_VARIABLE.Rule = tEste + sPunto + USAR_VARIABLEP
             |  //    | USAR_VARIABLEP;
             |
             |  USAR_VARIABLEP.Rule = valId + sPunto
             |      // | valId + LST_CORCHETES_VAL + sPunto
             | valId + sAbreParent + LST_VAL + sCierraParent + sPunto
             |      ;
             |
             |  USAR_VARIABLE.Rule = valId + VAL
             | valId + sMas + sMas
             | valId + sMenos + sMenos
             | valId + LST_CORCHETES_VAL + VAL;
             |
             |  USAR_METODO.Rule = valId + sAbreParent + LST_VAL + sCierraParent;
             */
            //#------------------+
            //# USAR  METODO

            /*
             * USAR_METODO.Rule = tEste + sPunto + USAR_METODOP
             | USAR_VARIABLEP;
             |
             | USAR_VARIABLEP.Rule = valId + sPunto + USAR_VARIABLEP
             | valId + LST_CORCHETES_VAL + sPunto + USAR_VARIABLEP
             | valId + sAbreParent + LST_VAL + sCierraParent + sPunto + USAR_VARIABLEP
             | valId
             | valId + LST_CORCHETES_VAL;
             */
            #endregion

            //LLAMADA_FORMULARIO.Rule = tNuevo + USAR_VARIABLEP; //aqui hay duda we

            //identificador



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Cuerpo
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            LST_CUERPO.Rule = MakeStarRule(LST_CUERPO, CUERPO);
            //| RETORNA
            ;


            CUERPO.Rule = DECLARAR_VARIABLE_SINVISIBI + sPuntoComa
                          | ID_VAR_FUNC + sPuntoComa //hay que validar que sea un metodo y no una variables
                          | ASIG_VALOR + sPuntoComa
                          | Empty
                          | SyntaxError
                          | FUNCIONES_NATIVAS + sPuntoComa
                          | SENTENCIAS
                          | SUPER

                          //| USAR_METODO
                          | ROMPER
                          | CONTINUAR
                          | RETORNO
                          | ESCRIBIR_ARCHIVO
                          //| PROCEDIMIENTOS_FORMULARIO
                          //| FUNC_MULTIMEDIA
                          | FUNC_MULTIMEDIA + sPuntoComa
                          | LLAMADA_FORMULARIO;

            ;



            LLAMADA_FORMULARIO.Rule = tNuevo + valId + sAbreParent + LST_VAL + sCierraParent + sPunto + tPagina + sPuntoComa
                                      | tNuevo + valId + sAbreParent + LST_VAL + sCierraParent + sPunto + tTodo + sPuntoComa
                                      | tNuevo + valId + sAbreParent + LST_VAL + sCierraParent + sPunto + tCuadriculo + sPuntoComa;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | MULTIMEDIA
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            FUNC_MULTIMEDIA.Rule = AUDIO
                                   | VIDEO
                                   | IMAGEN
            ;


            AUDIO.Rule = tAudio + sAbreParent + E + sComa + E + sCierraParent;

            VIDEO.Rule = tVideo + sAbreParent + E + sComa + E + sCierraParent;

            IMAGEN.Rule = tImagen + sAbreParent + E + sComa + E + sCierraParent;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | SUPER
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            SUPER.Rule = tSuper + sAbreParent + LST_VAL + sCierraParent + sPuntoComa;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Sentencias de cotrol
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            RETORNO.Rule = tRetorno + sPuntoComa
                           | tRetorno + VALOR + sPuntoComa;

            ROMPER.Rule = tRomper + sPuntoComa;

            CONTINUAR.Rule = tContinuar + sPuntoComa;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Sentencias
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            SENTENCIAS.Rule = SI
                              // | SI_SIMPLIFICADO
                              | CASO

                              //CICLOS
                              | WHILE
                              | FOR
                              | DOWHILE
                              | REPETIR;

            /*
             * ------------------------------------------
             * SI
             * ------------------------------------------
             *
             */


            SI.Rule = tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                      | tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave + SINO_SI
                      | tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave + SINO;

            SINO_SI.Rule = tSino + tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave + SINO_SI
                           | tSino + tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                           | tSino + tSi + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave + SINO;

            SINO.Rule = tSino + sAbreLlave + LST_CUERPO + sCierraLlave;

            /*
             * ------------------------------------------
             * SI SIMPLIFICADO
             * ------------------------------------------
             */

            SI_SIMPLIFICADO.Rule = VALOR + sCierraInterrogante + E + sDosPuntos + E;

            /*
             * ------------------------------------------
             * CASE
             * ------------------------------------------
             */

            CASO.Rule = tCaso + sAbreParent + E + sCierraParent + tDe + sAbreLlave + CUERPO_CASE + sCierraLlave;

            CUERPO_CASE.Rule = E + sDosPuntos + sAbreLlave + LST_CUERPO + sCierraLlave + CUERPO_CASE
                               | E + sDosPuntos + sAbreLlave + LST_CUERPO + sCierraLlave
                               | tDefecto + sDosPuntos + sAbreLlave + LST_CUERPO + sCierraLlave;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | BUCLES
             |-------------------------------------------------------------------------------------------------------------------
             |
             |
             |
             | /*
             | ------------------------------------------
             * WHILE
             * ------------------------------------------
             */

            WHILE.Rule = tMientras + sAbreParent + E + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;


            /*
             * ------------------------------------------
             * FOR
             * ------------------------------------------
             */

            FOR.Rule = tPara + sAbreParent + DECLARAR_VARIABLE_SINVISIBI + sPuntoComa + E + sPuntoComa + ASIG_VALOR + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                       | tPara + sAbreParent + ASIG_VALOR + sPuntoComa + E + sPuntoComa + ASIG_VALOR + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;



            /*
             * ------------------------------------------
             * DOWHILE
             * ------------------------------------------
             */

            DOWHILE.Rule = tHacer + sAbreLlave + LST_CUERPO + sCierraLlave + tMientras + sAbreParent + E + sCierraParent + sPuntoComa;


            /*
             * ------------------------------------------
             * DOWHILE
             * ------------------------------------------
             */

            REPETIR.Rule = tRepetir + sAbreLlave + LST_CUERPO + sCierraLlave + tHasta + sAbreParent + E + sCierraParent + sPuntoComa;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Funciones Nativas
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            FUNCIONES_NATIVAS.Rule = IMPRIMIR
                                     | MENSAJE
            ;

            IMPRIMIR.Rule = tImprimir + sAbreParent + VALOR + sCierraParent
                            | tImprimir + sAbreParent + sCierraParent;

            MENSAJE.Rule = tMensaje + sAbreParent + E + sCierraParent
                           | tMensaje + sAbreParent + sCierraParent;


            /*
             * ------------------------------------------
             * Internas del lenguaje
             * ------------------------------------------
             */


            PREGUNTA_NATIVA.Rule = tNativo + valId + sAbreParent + LST_VAL + sCierraParent;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Funciones ope Tipo
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            OPE_TIPO.Rule = TO_CADENA
                            | SUB_CAD
                            | POS_CAD
                            | TO_BOOLEAN
                            | TO_ENTERO
                            | HOY
                            | AHORA
                            | TO_FECHA
                            | TO_HORA
                            | TO_FECHAHORA
                            | TAM
                            | RANDOM
                            | MIN
                            | MAX;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Funciones Cadena
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            /*
             * ------------------------------------------
             * CADENA
             * ------------------------------------------
             */


            TO_CADENA.Rule = tCadena + sAbreParent + E + sCierraParent;

            SUB_CAD.Rule = tSubCad + sAbreParent + E + sComa + E + sComa + E + sCierraParent;

            POS_CAD.Rule = tPosCad + sAbreParent + E + sComa + E + sCierraParent;

            /*
             * ------------------------------------------
             * Booleana
             * ------------------------------------------
             */


            TO_BOOLEAN.Rule = tBooleano + sAbreParent + E + sCierraParent;


            /*
             * ------------------------------------------
             * Entera
             * ------------------------------------------
             */


            TO_ENTERO.Rule = tEntero + sAbreParent + E + sCierraParent;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Funciones Date
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            /*
             * ------------------------------------------
             * Hoy
             * ------------------------------------------
             * Retorno: fecha
             */


            HOY.Rule = tHoy + sAbreParent + sCierraParent;


            /*
             * ------------------------------------------
             * Ahora
             * ------------------------------------------
             * Retorno: fechaHora
             */


            AHORA.Rule = tAhora + sAbreParent + sCierraParent;

            /*
             * ------------------------------------------
             * To Fecha
             * ------------------------------------------
             * Retorno: fecha
             */

            TO_FECHA.Rule = tFecha + sAbreParent + E + sCierraParent;

            /*
             * ------------------------------------------
             * To Hora
             * ------------------------------------------
             * Retorno: hora
             */


            TO_HORA.Rule = tHora + sAbreParent + E + sCierraParent;


            /*
             * ------------------------------------------
             * To FechaHora
             * ------------------------------------------
             * Retorno: hora
             */

            TO_FECHAHORA.Rule = tFechaHora + sAbreParent + E + sCierraParent;



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Otras Funciones
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            /*
             * ------------------------------------------
             * OBjeto
             * ------------------------------------------
             * retorno:entero
             */


            TAM.Rule = tTam + sAbreParent + E + sCierraParent;



            /*
             * ------------------------------------------
             * Random
             * ------------------------------------------
             * retorno:entero/decimal/cadena
             */
            RANDOM.Rule = tRandom + sAbreParent + LST_VAL + sCierraParent;
            //| tRandom + sAbreParent + sCierraParent;

            /*
             * ------------------------------------------
             * Minimo
             * ------------------------------------------
             * retorno:entero/decimal
             */
            MIN.Rule = tMin + sAbreParent + LST_VAL + sCierraParent;


            /*
             * ------------------------------------------
             * Maximo
             * ------------------------------------------
             * retorno:entero/decimal
             */
            MAX.Rule = tMax + sAbreParent + LST_VAL + sCierraParent;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Operaciones matematicas
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            OPE_ARITME.Rule = POTENCIA
                              | LOGARITMO
                              | LOGARITMO10
                              | ABSOLUTO
                              | SENO
                              | COSENO
                              | TANGENTE
                              | RAIZ
                              | PI;


            /*
             * ------------------------------------------
             * POTENCIA
             * ------------------------------------------
             * Retorno:decimal
             */

            POTENCIA.Rule = tPow + sAbreParent + E + sComa + E + sCierraParent;

            /*
             * ------------------------------------------
             * LOGARITMO
             * ------------------------------------------
             * Retorno:decimal
             */

            LOGARITMO.Rule = tLog + sAbreParent + E + sCierraParent;

            /*
             * ------------------------------------------
             * LOGARITMO10
             * ------------------------------------------
             * Retorno:decimal
             */

            LOGARITMO10.Rule = tLog10 + sAbreParent + E + sCierraParent;

            /*
             * ------------------------------------------
             * ABSOLUTO
             * ------------------------------------------
             * Retorno:decimal/enter
             */

            ABSOLUTO.Rule = tAbs + sAbreParent + E + sCierraParent;

            /*
             * ------------------------------------------
             * TRIGONOMETRICAS
             * ------------------------------------------
             * Retorno:decimal
             */

            SENO.Rule = tSeno + sAbreParent + E + sCierraParent;

            COSENO.Rule = tCoseno + sAbreParent + E + sCierraParent;

            TANGENTE.Rule = tTangente + sAbreParent + E + sCierraParent;

            /*
             * ------------------------------------------
             * RAIZ
             * ------------------------------------------
             * Retorno:decimal
             */
            RAIZ.Rule = tSqrt + sAbreParent + E + sCierraParent;


            /*
             * ------------------------------------------
             * PI
             * ------------------------------------------
             * Retorno:decimal
             */
            PI.Rule = tPi + sAbreParent + sCierraParent;

            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Formulario
             |-------------------------------------------------------------------------------------------------------------------
             |
             */

            FORMULARIO.Rule = tFormulario + valId + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;

            PREGUNTA.Rule = tPregunta + valId + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO_PREGUNTA + sCierraLlave;

            GRUPO.Rule = tGrupo + valId + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;


            LST_CUERPO_PREGUNTA.Rule = MakeStarRule(LST_CUERPO_PREGUNTA, CUERPO_PREGUNTA);


            CUERPO_PREGUNTA.Rule = DECLARAR_VARIABLE_GLOBAL + sPuntoComa
                                   | METODO
                                   | VISIBILIDAD + tRespuesta + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                                   | VISIBILIDAD + tMostrar + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave
                                   | VISIBILIDAD + tCalcular + sAbreParent + LST_PARAMETROS + sCierraParent + sAbreLlave + LST_CUERPO + sCierraLlave;


            /*
             |-------------------------------------------------------------------------------------------------------------------
             | ESCRIBIR_ARCHIVO
             |-------------------------------------------------------------------------------------------------------------------
             |
             */


            ESCRIBIR_ARCHIVO.Rule = tEscribirArchivo + sAbreParent + LST_VAL + sCierraParent + sPuntoComa;



            /*
             |-------------------------------------------------------------------------------------------------------------------
             | Valor
             |-------------------------------------------------------------------------------------------------------------------
             |
             */



            VALOR.Rule = tNuevo + valId + sAbreParent + LST_VAL + sCierraParent //aqui tengo que reconocer el-> nuevo opciones()
                         | tNuevo + TIPO + LST_CORCHETES_VAL
                         | LST_LLAVES_VAL
                         //| tNulo
                         | PREGUNTA_NATIVA
                         | tEste //para el this solamente
                         | E;



            E.Rule =
                sMenos + E
                //Aritemeticas
                | E + sPot + E
                | E + sDiv + E
                | E + sPor + E
                | E + sMas + E
                | E + sMenos + E
                | E + sMod + E

                //Relacional

                | E + sIgualacion + E
                | E + sDiferenciacion + E
                | E + sMenorQue + E
                | E + sMenorIgualQue + E
                | E + sMayorQue + E
                | E + sMayorIgualQue + E

                //logicos

                | E + sAnd + E
                | E + sOr + E
                | sNot + E



                | sAbreParent + E + sCierraParent

                | ID_VAR_FUNC  //validar que si viene func() tiene que retornar algo obligatoriamente prro
                | valBoolean
                | valCadena
                | valCadena2
                | valCaracter
                | valDecimal
                | valNumero
                | tNulo
                | tNada
                | SI_SIMPLIFICADO
                | OPE_ARITME
                | OPE_TIPO
                | LEN;

            LEN.Rule = tLen + sAbreParent + E + sCierraParent;



            RegisterOperators(1, Associativity.Left, sOr);
            RegisterOperators(2, Associativity.Left, sAnd);
            RegisterOperators(3, Associativity.Left, sNot);
            RegisterOperators(4, Associativity.Left, sMayorQue, sMenorQue, sMayorIgualQue, sMenorIgualQue, sIgualacion, sDiferenciacion);
            RegisterOperators(5, Associativity.Left, sMas, sMenos);
            RegisterOperators(6, Associativity.Left, sPor, sDiv, sMod);
            RegisterOperators(7, Associativity.Left, sPot);


            this.Root = S;
            #endregion
        }
Exemplo n.º 28
0
        public GWBasicGrammar() : base(false)  // BASIC is not case sensitive...
        {
            this.GrammarComments = "This grammar uses one new Irony feature - Scanner-Parser link. Parser helps Scanner to disambiguate " +
                                   "similar but different token types when more than one terminal matches the current input char.\r\n" +
                                   "See comments in GwBasicGrammar.cs file.";

            /*
             * Scanner-Parser link.
             * The grammar defines 3 terminals for numbers: number, lineNumber and fileNumber. All three return decimal
             * digits in GetFirsts() method. So when current input is a digit, the scanner has 3 potential candidate terminals
             * to match the input. However, because each of the 3 terminals can appear in specific "places" in grammar,
             * the parser is able to assist scanner to pick the correct terminal, depending on the current parser state.
             * The disambiguation happens in Scanner.SelectTerminals method. When the terminal list for current input char
             * has more than 1 terminal, the scanner code gets the current parser state from core parser (through compilerContext),
             * and then checks the terminals agains the ExpectedTerms set in the parser state.
             * As you might see in Grammar Explorer, the conflict is resolved successfully.
             */

            //Terminals
            var lineNumber = new NumberLiteral("LINE_NUMBER", NumberOptions.IntOnly);
            var fileNumber = new NumberLiteral("FILE_NUMBER", NumberOptions.IntOnly);

            var number = new NumberLiteral("NUMBER", NumberOptions.AllowStartEndDot);

            //ints that are too long for int32 are converted to int64
            number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 };
            number.AddExponentSymbols("eE", TypeCode.Single);
            number.AddExponentSymbols("dD", TypeCode.Double);
            number.AddSuffix("!", TypeCode.Single);
            number.AddSuffix("#", TypeCode.Double);

            var variable = new IdentifierTerminal("Identifier");

            variable.AddSuffix("$", TypeCode.String);
            variable.AddSuffix("%", TypeCode.Int32);
            variable.AddSuffix("!", TypeCode.Single);
            variable.AddSuffix("#", TypeCode.Double);

            var stringLiteral = new StringLiteral("STRING", "\"", StringOptions.None);
            //Important: do not add comment term to base.NonGrammarTerminals list - we do use this terminal in grammar rules
            var userFunctionName = variable;
            var comment          = new CommentTerminal("Comment", "REM", "\n");
            var short_comment    = new CommentTerminal("ShortComment", "'", "\n");
            var line_cont        = new LineContinuationTerminal("LineContinuation", "_");
            var comma            = ToTerm(",", "comma");
            var colon            = ToTerm(":", "colon");

            var comma_opt = new NonTerminal("comma_opt");

            comma_opt.Rule = Empty | ",";
            var semi_opt = new NonTerminal("semi_opt");

            semi_opt.Rule = Empty | ";";
            var pound_opt = new NonTerminal("pound_opt");

            pound_opt.Rule = Empty | "#";

            // Non-terminals
            var PROGRAM                   = new NonTerminal("PROGRAM");
            var LINE                      = new NonTerminal("LINE");
            var LINE_CONTENT_OPT          = new NonTerminal("LINE_CONTENT_OPT");
            var COMMENT_OPT               = new NonTerminal("COMMENT_OPT");
            var STATEMENT_LIST            = new NonTerminal("STATEMENT_LIST");
            var STATEMENT                 = new NonTerminal("STATEMENT");
            var PRINT_STMT                = new NonTerminal("PRINT_STMT");
            var PRINT_LIST                = new NonTerminal("PRINT_LIST");
            var PRINT_ARG                 = new NonTerminal("PRINT_ARG");
            var OPEN_STMT                 = new NonTerminal("OPEN_STMT");
            var OPEN_STMT_MODE            = new NonTerminal("OPEN_STMT_MODE");
            var OPEN_STMT_ACCESS          = new NonTerminal("OPEN_STMT_ACCESS");
            var CLOSE_STMT                = new NonTerminal("CLOSE_STMT");
            var INPUT_STMT                = new NonTerminal("INPUT_STMT");
            var VARIABLES                 = new NonTerminal("VARIABLES");
            var IF_STMT                   = new NonTerminal("IF_STMT");
            var THEN_CLAUSE               = new NonTerminal("THEN_CLAUSE");
            var ELSE_CLAUSE_OPT           = new NonTerminal("ELSE_CLAUSE_OPT"); //, typeof(AstNode));
            var EXPR                      = new NonTerminal("EXPRESSION");
            var EXPR_LIST                 = new NonTerminal("EXPRESSION_LIST");
            var BINARY_OP                 = new NonTerminal("BINARY_OP", "operator");
            var BINARY_EXPR               = new NonTerminal("BINARY_EXPR");
            var UNARY_EXPR                = new NonTerminal("UNARY_EXPR");
            var SIGN                      = new NonTerminal("SIGN");
            var ASSIGN_STMT               = new NonTerminal("ASSIGN_STMT");
            var FOR_STMT                  = new NonTerminal("FOR_STMT");
            var STEP_OPT                  = new NonTerminal("STEP_OPT");
            var NEXT_STMT                 = new NonTerminal("NEXT_STMT");
            var LOCATE_STMT               = new NonTerminal("LOCATE_STMT");
            var WHILE_STMT                = new NonTerminal("WHILE_STMT");
            var WEND_STMT                 = new NonTerminal("WEND_STMT");
            var SWAP_STMT                 = new NonTerminal("SWAP_STMT");
            var FUN_CALL                  = new NonTerminal("FUN_CALL");
            var VARIABLE_OR_FUNCTION_EXPR = new NonTerminal("VARIABLE_OR_FUNCTION_EXPR");
            var ARG_LIST                  = new NonTerminal("ARG_LIST");
            var LINE_INPUT_STMT           = new NonTerminal("LINE_INPUT_STMT");
            var LINE_INPUT_POUND_STMT     = new NonTerminal("LINE_INPUT_POUND_STMT");
            var END_STMT                  = new NonTerminal("END_STMT");
            var CLS_STMT                  = new NonTerminal("CLS_STMT");
            var CLEAR_STMT                = new NonTerminal("CLEAR_STMT");
            var DIM_STMT                  = new NonTerminal("DIM_STMT");
            var DEF_FN_STMT               = new NonTerminal("DEF_FN_STMT");
            var GOTO_STMT                 = new NonTerminal("GOTO_STMT");
            var GOSUB_STMT                = new NonTerminal("GOSUB_STMT");
            var RETURN_STMT               = new NonTerminal("RETURN_STMT");
            var ON_STMT                   = new NonTerminal("ON_STMT");
            var LINE_NUMBERS              = new NonTerminal("LINE_NUMBERS");
            var RANDOMIZE_STMT            = new NonTerminal("RANDOMIZE_STMT");

            // set the PROGRAM to be the root node of BASIC programs.
            this.Root = PROGRAM;

            // BNF Rules
            PROGRAM.Rule = MakePlusRule(PROGRAM, LINE);

            // A line can be an empty line, or it's a number followed by a statement list ended by a new-line.
            LINE.Rule = NewLine | lineNumber + LINE_CONTENT_OPT + COMMENT_OPT + NewLine | SyntaxError + NewLine;
            LINE.NodeCaptionTemplate = "Line #{0}";

            // A statement list is 1 or more statements separated by the ':' character
            LINE_CONTENT_OPT.Rule = Empty | IF_STMT | STATEMENT_LIST;
            STATEMENT_LIST.Rule   = MakePlusRule(STATEMENT_LIST, colon, STATEMENT);
            COMMENT_OPT.Rule      = short_comment | comment | Empty;

            // A statement can be one of a number of types
            STATEMENT.Rule = ASSIGN_STMT | PRINT_STMT | INPUT_STMT | OPEN_STMT | CLOSE_STMT
                             | LINE_INPUT_POUND_STMT | LINE_INPUT_STMT
                             | LOCATE_STMT | CLS_STMT
                             | END_STMT | CLEAR_STMT | DIM_STMT | DEF_FN_STMT
                             | SWAP_STMT | RANDOMIZE_STMT
                             | GOSUB_STMT | RETURN_STMT | GOTO_STMT | ON_STMT
                             | FOR_STMT | NEXT_STMT | WHILE_STMT | WEND_STMT;

            // The different statements are defined here
            PRINT_STMT.Rule = "print" + PRINT_LIST;
            PRINT_LIST.Rule = MakeStarRule(PRINT_LIST, null, PRINT_ARG);
            PRINT_ARG.Rule  = EXPR + semi_opt;
            INPUT_STMT.Rule = "input" + semi_opt + stringLiteral + ";" + VARIABLES;
            OPEN_STMT.Rule  = "open" + EXPR + (Empty | "for" + OPEN_STMT_MODE) +
                              (Empty | "access" + OPEN_STMT_ACCESS) + "as" + pound_opt + fileNumber;
            OPEN_STMT_ACCESS.Rule      = "read" + (Empty | "write") | "write";
            OPEN_STMT_MODE.Rule        = ToTerm("o") | "i" | "a" | "output" | "input" | "append";
            CLOSE_STMT.Rule            = "close" + pound_opt + fileNumber;
            LINE_INPUT_STMT.Rule       = ToTerm("line") + "input" + semi_opt + stringLiteral + ";" + VARIABLE_OR_FUNCTION_EXPR;
            LINE_INPUT_POUND_STMT.Rule = ToTerm("line") + "input" + ToTerm("#") + fileNumber + comma + VARIABLE_OR_FUNCTION_EXPR;
            DIM_STMT.Rule    = "dim" + VARIABLES;
            DEF_FN_STMT.Rule = "def" + userFunctionName + (Empty | "(" + ARG_LIST + ")") + "=" + EXPR;
            VARIABLES.Rule   = VARIABLE_OR_FUNCTION_EXPR | VARIABLE_OR_FUNCTION_EXPR + "," + VARIABLES;

            IF_STMT.Rule     = "if" + EXPR + THEN_CLAUSE + ELSE_CLAUSE_OPT;
            THEN_CLAUSE.Rule = "then" + STATEMENT_LIST | GOTO_STMT;

            //Inject PreferShift hint here to explicitly set shift as preferred action. Suppresses warning message about conflict.
            ELSE_CLAUSE_OPT.Rule = Empty | PreferShiftHere() + "else" + STATEMENT_LIST;

            GOTO_STMT.Rule      = "goto" + lineNumber;
            GOSUB_STMT.Rule     = "gosub" + lineNumber;
            RETURN_STMT.Rule    = "return";
            ON_STMT.Rule        = "on" + EXPR + (ToTerm("goto") | "gosub") + LINE_NUMBERS;
            LINE_NUMBERS.Rule   = MakePlusRule(LINE_NUMBERS, comma, lineNumber);
            ASSIGN_STMT.Rule    = VARIABLE_OR_FUNCTION_EXPR + "=" + EXPR;
            LOCATE_STMT.Rule    = "locate" + EXPR + comma + EXPR;
            SWAP_STMT.Rule      = "swap" + EXPR + comma + EXPR;
            END_STMT.Rule       = "end";
            CLS_STMT.Rule       = "cls";
            CLEAR_STMT.Rule     = ToTerm("clear") + comma + (Empty | number) + (Empty | comma + number) | "clear" + number | "clear";
            RANDOMIZE_STMT.Rule = "randomize" + EXPR;

            // An expression is a number, or a variable, a string, or the result of a binary comparison.
            EXPR.Rule = number | variable | FUN_CALL | stringLiteral | BINARY_EXPR
                        | "(" + EXPR + ")" | UNARY_EXPR;
            BINARY_EXPR.Rule = EXPR + BINARY_OP + EXPR;
            UNARY_EXPR.Rule  = SIGN + EXPR;
            SIGN.Rule        = ToTerm("-") | "+";

            //Inject PreferShift hint here to explicitly set shift as preferred action. Suppresses warning message about conflict.
            //The conflict arises from PRINT statement, when there may be ambigous interpretations for expression like
            //  PRINT F (X) -- either function call or identifier followed by expression
            FUN_CALL.Rule = variable + PreferShiftHere() + "(" + ARG_LIST + ")";
            VARIABLE_OR_FUNCTION_EXPR.Rule = variable | FUN_CALL;

            BINARY_OP.Rule = ToTerm("+") | "^" | "-" | "*" | "/" | "=" | "<=" | ">=" | "<" | ">" | "<>" | "and" | "or";
            //let's do operator precedence right here
            RegisterOperators(60, "^");
            RegisterOperators(50, "*", "/");
            RegisterOperators(40, "+", "-");
            RegisterOperators(30, "=", "<=", ">=", "<", ">", "<>");
            RegisterOperators(20, "and", "or");

            EXPR_LIST.Rule = MakeStarRule(EXPR_LIST, EXPR);

            FOR_STMT.Rule   = "for" + ASSIGN_STMT + "to" + EXPR + STEP_OPT;
            STEP_OPT.Rule   = Empty | "step" + EXPR;
            NEXT_STMT.Rule  = "next" + VARIABLES | "next";
            WHILE_STMT.Rule = "while" + EXPR;
            WEND_STMT.Rule  = "wend";

            //TODO: check number of arguments for particular function in node constructor
            ARG_LIST.Rule = MakePlusRule(ARG_LIST, comma, EXPR);


            //Punctuation and Transient elements
            MarkPunctuation("(", ")", ",");
            MarkTransient(EXPR, STATEMENT, LINE_CONTENT_OPT, VARIABLE_OR_FUNCTION_EXPR, COMMENT_OPT);
            NonGrammarTerminals.Add(line_cont);

            this.LanguageFlags = LanguageFlags.NewLineBeforeEOF;

            lineNumber.ValidateToken += identifier_ValidateToken;
        }
        public Gramatica() : base(caseSensitive: true)
        {
            //Prueba

            #region er
            StringLiteral      CADENA = new StringLiteral("cadena", "\"");
            RegexBasedTerminal letras = new RegexBasedTerminal("letras", "[(a-z)*(A-Z)*(0-9)*]+");
            var ENTERO  = new RegexBasedTerminal("Entero", "[0-9]+");
            var DECIMAL = new RegexBasedTerminal("Decimal", "[0-9]+[.]+[0-9]+");
            IdentifierTerminal IDENTIFICADOR = new IdentifierTerminal("ID");

            //CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/", "/");

            CommentTerminal comentarioLinea  = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            CommentTerminal comentarioBloque = new CommentTerminal("DelimitedComment", "/*", "*/");
            //var whiteSpace = new
            NonGrammarTerminals.Add(comentarioLinea);
            NonGrammarTerminals.Add(comentarioBloque);
            #endregion

            #region KeyWords de Puntuacion
            KeyTerm dosPuntos     = ToTerm(":", "dosPuntos");
            KeyTerm puntoComa     = ToTerm(";", "puntoComa");
            KeyTerm punto         = ToTerm(".", "punto");
            KeyTerm coma          = ToTerm(",", "coma");
            KeyTerm parentesisIzq = ToTerm("(", "parentesisIzq");
            KeyTerm parentesisDer = ToTerm(")", "parentesisDer");
            KeyTerm llaveIzq      = ToTerm("{", "llaveIzq");
            KeyTerm llaveDer      = ToTerm("}", "llaveDer");
            #endregion

            #region KeyWords Operadores, Comparadores, nombre variables,
            KeyTerm plus       = ToTerm("+", "plus");
            KeyTerm minus      = ToTerm("-", "minus");
            KeyTerm por        = ToTerm("*", "por");
            KeyTerm div        = ToTerm("/", "div");
            KeyTerm plusPlus   = ToTerm("++", "plusPlus");
            KeyTerm minusMinus = ToTerm("--", "menosMenos");

            //Comparadores
            KeyTerm mayorQue   = ToTerm(">", "mayorQue");
            KeyTerm menorQue   = ToTerm("<", "menorQue");
            KeyTerm igual      = ToTerm("=", "igual");
            KeyTerm mayorIgual = ToTerm(">=", "mayorIgual");
            KeyTerm menorIgual = ToTerm("<=", "menorIgual");
            KeyTerm diferente  = ToTerm("!=", "diferente");
            KeyTerm igualIgual = ToTerm("==", "igualIgual");

            //Variables
            KeyTerm varInt     = ToTerm("int");
            KeyTerm varFloat   = ToTerm("float");
            KeyTerm varString  = ToTerm("string");
            KeyTerm varBoolean = ToTerm("bool");

            //Ciclos y condicionales
            KeyTerm condIf    = ToTerm("if");
            KeyTerm condElif  = ToTerm("elif");
            KeyTerm condElse  = ToTerm("else");
            KeyTerm kwBreack  = ToTerm("break");
            KeyTerm kwCase    = ToTerm("case");
            KeyTerm kwClass   = ToTerm("class");
            KeyTerm kwTry     = ToTerm("Try");
            KeyTerm kwCatch   = ToTerm("Catch");
            KeyTerm kwWhile   = ToTerm("while");
            KeyTerm kwDowhile = ToTerm("do while");
            KeyTerm kwFor     = ToTerm("for");
            KeyTerm kwPublic  = ToTerm("public");
            KeyTerm kwThrow   = ToTerm("Throw");
            KeyTerm kwVoid    = ToTerm("Void");
            KeyTerm kwSwitch  = ToTerm("Switch");
            KeyTerm kwTrue    = ToTerm("true");
            KeyTerm kwFalse   = ToTerm("false");
            #endregion

            #region Terminales
            NonTerminal ini                = new NonTerminal("ini");
            NonTerminal instruccion        = new NonTerminal("instruccion");
            NonTerminal instrucciones      = new NonTerminal("instrucciones");
            NonTerminal expresion_numerica = new NonTerminal("expresion_numerica");
            NonTerminal expresion_cadena   = new NonTerminal("expresion_cadena");
            NonTerminal expresion_logica   = new NonTerminal("expresion_logica");

            //No terminales para declarar variables
            NonTerminal declararVar = new NonTerminal("decVar");
            NonTerminal decInt      = new NonTerminal("decInt");
            NonTerminal decFloat    = new NonTerminal("decFloat");
            NonTerminal decString   = new NonTerminal("decString");
            NonTerminal decBool     = new NonTerminal("decBool");

            var entradaID = new NonTerminal("entradaID");


            #endregion

            #region No terminales
            #endregion

            #region Gramatica
            ini.Rule = instrucciones;


            //Declarar varibles
            declararVar.Rule = decInt | decFloat | decString | decBool | declararVar;

            decInt.Rule    = varInt + entradaID + igual + ENTERO + puntoComa;
            decFloat.Rule  = (varFloat + entradaID + igual + DECIMAL + puntoComa);
            decString.Rule = (varString + entradaID + igual + (CADENA) + puntoComa);
            decBool.Rule   = (varBoolean + entradaID + igual + (kwTrue | kwFalse) + puntoComa);

            entradaID.Rule = MakePlusRule(entradaID, ToTerm(","), IDENTIFICADOR);


            #endregion


            #region Jesus IF

            //----------------------IF------------------

            //En estos if solo se podran hacer 2 condiciones maximo por ejemplo if(a==2 && b=false){}
            //No terminales para condicional if
            NonTerminal condicionIF         = new NonTerminal("condicionIF");
            NonTerminal condicionIFELSE     = new NonTerminal("condicionIFELSE");
            NonTerminal condicionalIFELSEIF = new NonTerminal("condicionIFELSEIF");
            NonTerminal condicionELSE       = new NonTerminal("condicionELSE");
            NonTerminal condicionELSEIF     = new NonTerminal("condicionELSEIF");
            NonTerminal expComparacion      = new NonTerminal("expComparacion");
            NonTerminal nuevaCondicion      = new NonTerminal("nuevaCondicion");
            NonTerminal nuevaCondicion2     = new NonTerminal("nuevaCondicion2");
            NonTerminal compIgualDiferente  = new NonTerminal("compIgualDiferente");
            NonTerminal compMayorMenor      = new NonTerminal("comMayorMenor");
            NonTerminal compMayorMenorIgual = new NonTerminal("comMayorMenor");
            NonTerminal compBool            = new NonTerminal("comBool");

            KeyTerm signoOR  = ToTerm("|");
            KeyTerm signoAND = ToTerm("&&");

            //Nota: El Ciclo if que se presenta se modificara para poder poner mas codigo dentro del ciclo if

            //Declarar un if
            condicionIF.Rule        = condIf + parentesisIzq + (expComparacion | (expComparacion + nuevaCondicion)) + parentesisDer + llaveIzq + llaveDer;
            expComparacion.Rule     = (parentesisIzq + (compIgualDiferente | compMayorMenor | compMayorMenorIgual | compBool) + parentesisDer) | (compIgualDiferente | compMayorMenor | compMayorMenorIgual | compBool);
            compIgualDiferente.Rule = ((DECIMAL + igualIgual + DECIMAL) | (ENTERO + igualIgual + ENTERO) | (entradaID + igualIgual + (ENTERO | DECIMAL | CADENA))) |
                                      ((DECIMAL + diferente + DECIMAL) | (ENTERO + diferente + ENTERO) | (entradaID + diferente + (ENTERO | DECIMAL | CADENA)));
            compMayorMenor.Rule = ((DECIMAL + mayorQue + DECIMAL) | (ENTERO + mayorQue + ENTERO) | (entradaID + mayorQue + (ENTERO | DECIMAL | CADENA))) |
                                  ((DECIMAL + menorQue + DECIMAL) | (ENTERO + menorQue + ENTERO) | (entradaID + menorQue + (ENTERO | DECIMAL | CADENA)));
            compMayorMenorIgual.Rule = ((DECIMAL + mayorIgual + DECIMAL) | (ENTERO + mayorIgual + ENTERO) | (entradaID + mayorIgual + (ENTERO | DECIMAL | CADENA))) |
                                       ((DECIMAL + menorIgual + DECIMAL) | (ENTERO + menorIgual + ENTERO) | (entradaID + menorIgual + (ENTERO | DECIMAL | CADENA)));
            compBool.Rule        = entradaID + igual + (kwTrue | kwFalse);
            nuevaCondicion.Rule  = ((signoAND | signoOR) + expComparacion) | ((signoAND | signoOR) + expComparacion + nuevaCondicion2);
            nuevaCondicion2.Rule = nuevaCondicion;

            //Declarar un if else
            condicionIFELSE.Rule = condicionIF + condicionELSE;
            condicionELSE.Rule   = condElse + llaveIzq + llaveDer;

            //Declarar un if else if
            condicionalIFELSEIF.Rule = condicionIF + condicionELSEIF;
            condicionELSEIF.Rule     = condElse + (condicionIF | condicionELSE | condicionalIFELSEIF);

            #endregion

            #region ADRI SWITCH
            NonTerminal condicionSwitch = new NonTerminal("condicionSwitch");
            NonTerminal switchOpcion    = new NonTerminal("switchOpcion");
            NonTerminal opcionCase      = new NonTerminal("opcionCase");
            NonTerminal opcionDefault   = new NonTerminal("opcionDefault");
            //poner con las keyterm
            KeyTerm kwDefault = ToTerm("default");
            opcionDefault.Rule   = kwDefault + dosPuntos + kwBreack + puntoComa;
            opcionCase.Rule      = kwCase + switchOpcion + dosPuntos + kwBreack + puntoComa + (opcionCase | opcionDefault);
            switchOpcion.Rule    = DECIMAL | ENTERO | CADENA | entradaID;
            condicionSwitch.Rule = kwSwitch + parentesisIzq + switchOpcion + parentesisDer + llaveIzq
                                   + opcionCase + llaveDer; //cierre de Switch
            #endregion

            #region Jesus Imprimir
            //-----------------------Print

            KeyTerm kwConsole = ToTerm("Console");
            KeyTerm kwWrite   = ToTerm("Write");
            KeyTerm kwWriteLn = ToTerm("WriteLine");

            NonTerminal imprimir        = new NonTerminal("imprimir");
            NonTerminal imprimirWrite   = new NonTerminal("imprimirWrite");
            NonTerminal imprimirWriteLn = new NonTerminal("imprimirWriteLn");
            NonTerminal textoOVariable  = new NonTerminal("textoOVariable");

            imprimir.Rule        = kwConsole + punto + (imprimirWrite | imprimirWriteLn) + puntoComa;
            imprimirWrite.Rule   = kwWrite + parentesisIzq + textoOVariable + parentesisDer;
            imprimirWriteLn.Rule = kwWriteLn + parentesisIzq + textoOVariable + parentesisDer;
            textoOVariable.Rule  = (CADENA | entradaID) | ((CADENA | entradaID) + plus + textoOVariable);
            #endregion

            #region Jesus Operaciones
            //-------------------------Operaciones

            NonTerminal operaciones       = new NonTerminal("operaciones");
            NonTerminal opeSuma           = new NonTerminal("opeSuma");
            NonTerminal opeResta          = new NonTerminal("opeResta");
            NonTerminal opeMultiplicacion = new NonTerminal("opeMultiplicacion");
            NonTerminal opeDivision       = new NonTerminal("opeDivision");
            NonTerminal opeCompuesta      = new NonTerminal("opeCompuesta");
            NonTerminal datoEntradaOpe    = new NonTerminal("datoEntradaOpe");

            operaciones.Rule       = ((opeSuma | opeResta | opeMultiplicacion | opeDivision) + puntoComa) | (opeCompuesta + puntoComa);
            opeSuma.Rule           = datoEntradaOpe | (datoEntradaOpe + plus + opeSuma) | (parentesisIzq + opeSuma + parentesisDer) | (plus + datoEntradaOpe);
            opeResta.Rule          = datoEntradaOpe | (datoEntradaOpe + minus + opeResta) | (parentesisIzq + opeResta + parentesisDer) | (minus + datoEntradaOpe);
            opeMultiplicacion.Rule = datoEntradaOpe | (datoEntradaOpe + por + opeMultiplicacion) | (parentesisIzq + opeMultiplicacion + parentesisDer) | (por + datoEntradaOpe) | (parentesisIzq + opeMultiplicacion + parentesisDer);
            opeDivision.Rule       = datoEntradaOpe | (datoEntradaOpe + div + opeDivision) | (parentesisIzq + opeDivision + parentesisDer) | (div + datoEntradaOpe);
            opeCompuesta.Rule      = (opeSuma | opeResta | opeMultiplicacion | opeDivision) | ((opeSuma | opeResta | opeMultiplicacion | opeDivision) + opeCompuesta);
            datoEntradaOpe.Rule    = (ENTERO | DECIMAL | entradaID) | (parentesisIzq + datoEntradaOpe + parentesisDer) | (parentesisIzq + (opeSuma | opeResta | opeMultiplicacion | opeDivision) + parentesisDer);


            #endregion

            #region Jesus funciones y clases
            //------------------funciones de clases
            NonTerminal nameSpace = new NonTerminal("nameSpace");
            NonTerminal ntClass   = new NonTerminal("ntClass");
            NonTerminal ntMain    = new NonTerminal("ntMain");
            NonTerminal ntPublic  = new NonTerminal("ntPublic");

            nameSpace.Rule = "namespace" + entradaID + llaveIzq + ntClass + llaveDer;
            ntClass.Rule   = kwClass + entradaID + llaveIzq + (ntPublic | ntMain) + llaveDer;
            ntMain.Rule    = "static void Main" + parentesisIzq + varString + "[] args" + parentesisDer + llaveIzq + llaveDer;
            ntPublic.Rule  = kwPublic + entradaID + "()" + llaveIzq + llaveDer;
            #endregion

            #region Preferencias
            #endregion
        }
Exemplo n.º 30
0
        public ScriptdotnetGrammar(bool expressionGrammar)
        {
            #region 1. Terminals
            NumberLiteral      n = TerminalFactory.CreateCSharpNumber("number");
            IdentifierTerminal v = CreateScriptNetIdentifier("Identifier");
            Terminal           s = CreateScriptNetString("string");

            Terminal @is       = Symbol("is");
            Terminal dot       = Symbol(".", "dot");
            Terminal less      = Symbol("<");
            Terminal greater   = Symbol(">");
            Terminal arrow     = Symbol("->");
            Terminal LSb       = Symbol("[");
            Terminal RSb       = Symbol("]");
            Terminal LCb       = Symbol("(");
            Terminal RCb       = Symbol(")");
            Terminal RFb       = Symbol("}");
            Terminal LFb       = Symbol("{");
            Terminal LMb       = Symbol("<!");
            Terminal RMb       = Symbol("!>");
            Terminal LGb       = Symbol("<|");
            Terminal RGb       = Symbol("|>");
            Terminal comma     = Symbol(",");
            Terminal semicolon = Symbol(";");
            Terminal colon     = Symbol(":");
            #endregion

            #region 2. Non-terminals
            #region 2.1 Expressions
            NonTerminal Expr            = new NonTerminal("Expr", typeof(ScriptExpr));
            NonTerminal ConstExpr       = new NonTerminal("ConstExpr", typeof(ScriptConstExpr));
            NonTerminal BinExpr         = new NonTerminal("BinExpr", typeof(ScriptBinExpr));
            NonTerminal UnaryExpr       = new NonTerminal("UnaryExpr", typeof(ScriptUnaryExpr));
            NonTerminal AssignExpr      = new NonTerminal("AssignExpr", typeof(ScriptAssignExpr));
            NonTerminal TypeConvertExpr = new NonTerminal("TypeConvertExpr", typeof(ScriptTypeConvertExpr));
            NonTerminal IsExpr          = new NonTerminal("IsExpr", typeof(ScriptIsExpr));
            NonTerminal MetaExpr        = new NonTerminal("MetaExpr", typeof(ScriptMetaExpr));
            NonTerminal FuncDefExpr     = new NonTerminal("FuncDefExpr", typeof(ScriptFunctionDefinition)); //typeof(ScriptFunctionDefExpression));

            NonTerminal TypeExpr        = new NonTerminal("TypeExpr", typeof(ScriptTypeExpr));
            NonTerminal TypeConstructor = new NonTerminal("TypeConstructor", typeof(ScriptTypeConstructor));
            NonTerminal FunctionCall    = new NonTerminal("FunctionCall", typeof(ScriptFunctionCall));
            NonTerminal ArrayResolution = new NonTerminal("ArrayResolution", typeof(ScriptArrayResolution));

            NonTerminal BinOp = new NonTerminal("BinOp");
            NonTerminal LUnOp = new NonTerminal("LUnOp");
            NonTerminal RUnOp = new NonTerminal("RUnOp");

            NonTerminal ArrayConstructor   = new NonTerminal("ArrayConstructor", typeof(ScriptArrayConstructor));
            NonTerminal MObjectConstructor = new NonTerminal("MObjectConstructor", typeof(ScriptMObject));
            NonTerminal MObjectPart        = new NonTerminal("MObjectPart", typeof(ScriptMObjectPart));
            NonTerminal MObjectParts       = new NonTerminal("MObjectPart", typeof(ScriptAst));

            NonTerminal TypeList = new NonTerminal("TypeList", typeof(ScriptTypeExprList));
            #endregion

            #region 2.2 QualifiedName
            //Expression List:  expr1, expr2, expr3, ..
            NonTerminal ExprList = new NonTerminal("ExprList", typeof(ScriptExprList));

            //A name in form: a.b.c().d[1,2].e ....
            NonTerminal NewStmt         = new NonTerminal("NewStmt", typeof(ScriptNewStmt));
            NonTerminal NewArrStmt      = new NonTerminal("NewArrStmt", typeof(ScriptNewArrStmt));
            NonTerminal QualifiedName   = new NonTerminal("QualifiedName", typeof(ScriptQualifiedName));
            NonTerminal GenericsPostfix = new NonTerminal("GenericsPostfix", typeof(ScriptGenericsPostfix));

            NonTerminal GlobalList = new NonTerminal("GlobalList", typeof(ScriptGlobalList));
            #endregion

            #region 2.3 Statement
            NonTerminal Condition = new NonTerminal("Condition", typeof(ScriptCondition));
            NonTerminal Statement = new NonTerminal("Statement", typeof(ScriptStatement));

            NonTerminal IfStatement              = new NonTerminal("IfStatement", typeof(ScriptIfStatement));
            NonTerminal WhileStatement           = new NonTerminal("WhileStatement", typeof(ScriptWhileStatement));
            NonTerminal ForStatement             = new NonTerminal("ForStatement", typeof(ScriptForStatement));
            NonTerminal ForEachStatement         = new NonTerminal("ForEachStatement", typeof(ScriptForEachStatement));
            NonTerminal OptionalExpression       = new NonTerminal("OptionalExpression", typeof(ScriptExpr));
            NonTerminal SwitchStatement          = new NonTerminal("SwitchStatement", typeof(ScriptStatement));
            NonTerminal SwitchStatements         = new NonTerminal("SwitchStatements", typeof(ScriptSwitchStatement));
            NonTerminal SwitchCaseStatement      = new NonTerminal("SwitchCaseStatement", typeof(ScriptSwitchCaseStatement));
            NonTerminal SwitchDefaultStatement   = new NonTerminal("SwitchDefaultStatement", typeof(ScriptSwitchDefaultStatement));
            NonTerminal UsingStatement           = new NonTerminal("UsingStatement", typeof(ScriptUsingStatement));
            NonTerminal TryCatchFinallyStatement = new NonTerminal("TryCatchFinallyStatement", typeof(ScriptTryCatchFinallyStatement));
            NonTerminal FlowControlStatement     = new NonTerminal("FlowControl", typeof(ScriptFlowControlStatement));
            NonTerminal ExprStatement            = new NonTerminal("ExprStatement", typeof(ScriptStatement));

            //Block
            NonTerminal BlockStatement = new NonTerminal("BlockStatement", typeof(ScriptStatement));
            NonTerminal Statements     = new NonTerminal("Statements(Compound)", typeof(ScriptCompoundStatement));
            #endregion

            #region 2.4 Program and Functions
            NonTerminal Prog          = new NonTerminal("Prog", typeof(ScriptProg));
            NonTerminal Element       = new NonTerminal("Element", typeof(ScriptAst));
            NonTerminal Elements      = new NonTerminal("Elements", typeof(ScriptElements));
            NonTerminal FuncDef       = new NonTerminal("FuncDef", typeof(ScriptFunctionDefinition));
            NonTerminal FuncContract  = new NonTerminal("FuncContract", typeof(ScriptFuncContract));
            NonTerminal ParameterList = new NonTerminal("ParamaterList", typeof(ScriptFuncParameters));

            NonTerminal FuncContractPre  = new NonTerminal("Pre Conditions", typeof(ScriptFuncContractPre));
            NonTerminal FuncContractPost = new NonTerminal("Post Conditions", typeof(ScriptFuncContractPost));
            NonTerminal FuncContractInv  = new NonTerminal("Invariant Conditions", typeof(ScriptFuncContractInv));
            #endregion

            #endregion

            #region 3. BNF rules
            #region 3.1 Expressions
            ConstExpr.Rule = Symbol("true")
                             | "false"
                             | "null"
                             | s
                             | n;

            BinExpr.Rule = Expr + BinOp + Expr
                           | IsExpr;

            UnaryExpr.Rule = LUnOp + Expr;

            IsExpr.Rule = Expr + @is + TypeExpr;

            TypeConvertExpr.Rule = LCb + Expr + RCb + Expr.Q();

            AssignExpr.Rule = QualifiedName + "=" + Expr
                              | QualifiedName + "++"
                              | QualifiedName + "--"
                              | QualifiedName + ":=" + Expr
                              | QualifiedName + "+=" + Expr
                              | QualifiedName + "-=" + Expr;

            //TODO: MetaFeatures;
            // <[    ] + > because of conflict a[1]>2
            MetaExpr.Rule = LMb + Elements + RMb;

            GlobalList.Rule = "global" + LCb + ParameterList + RCb;

            FuncDefExpr.Rule = "function" + LCb + ParameterList + RCb
                               + GlobalList.Q()
                               + FuncContract.Q()
                               + BlockStatement;

            Expr.Rule = ConstExpr
                        | BinExpr
                        | UnaryExpr
                        | QualifiedName
                        | AssignExpr
                        | NewStmt
                        | FuncDefExpr
                        | NewArrStmt
                        | ArrayConstructor
                        | MObjectConstructor
                        | TypeConvertExpr
                        | MetaExpr
            ;

            NewStmt.Rule    = "new" + TypeConstructor;
            NewArrStmt.Rule = "new" + TypeExpr + ArrayResolution;
            BinOp.Rule      = Symbol("+") | "-" | "*" | "/" | "%" | "^" | "&" | "|"
                              | "&&" | "||" | "==" | "!=" | greater | less
                              | ">=" | "<=";

            LUnOp.Rule = Symbol("~") | "-" | "!" | "$";

            ArrayConstructor.Rule = LSb + ExprList + RSb;

            MObjectPart.Rule        = v + arrow + Expr;
            MObjectParts.Rule       = MakePlusRule(MObjectParts, comma, MObjectPart);
            MObjectConstructor.Rule = LSb + MObjectParts + RSb;

            OptionalExpression.Rule = Expr.Q();
            #endregion

            #region 3.2 QualifiedName
            TypeExpr.Rule = //MakePlusRule(TypeExpr, dot, v);
                            v + GenericsPostfix.Q()
                            | TypeExpr + dot + (v + GenericsPostfix.Q());

            GenericsPostfix.Rule = LGb + TypeList + RGb;
            FunctionCall.Rule    = LCb + ExprList.Q() + RCb;
            ArrayResolution.Rule = LSb + ExprList + RSb;

            QualifiedName.Rule = v + (GenericsPostfix | ArrayResolution | FunctionCall).Star()
                                 | QualifiedName + dot + v + (GenericsPostfix | ArrayResolution | FunctionCall).Star();

            ExprList.Rule        = MakePlusRule(ExprList, comma, Expr);
            TypeList.Rule        = MakePlusRule(TypeList, comma, TypeExpr);
            TypeConstructor.Rule = TypeExpr + FunctionCall;
            #endregion

            #region 3.3 Statement
            Condition.Rule                = LCb + Expr + RCb;
            IfStatement.Rule              = "if" + Condition + Statement + ("else" + Statement).Q();
            WhileStatement.Rule           = "while" + Condition + Statement;
            ForStatement.Rule             = "for" + LCb + OptionalExpression + semicolon + OptionalExpression + semicolon + OptionalExpression + RCb + Statement;
            ForEachStatement.Rule         = "foreach" + LCb + v + "in" + Expr + RCb + Statement;
            UsingStatement.Rule           = "using" + LCb + Expr + RCb + BlockStatement;
            TryCatchFinallyStatement.Rule = "try" + BlockStatement + "catch" + LCb + v + RCb + BlockStatement + "finally" + BlockStatement;
            SwitchStatement.Rule          = "switch" + LCb + Expr + RCb + LFb + SwitchStatements + RFb;
            ExprStatement.Rule            = Expr + semicolon;
            FlowControlStatement.Rule     = "break" + semicolon
                                            | "continue" + semicolon
                                            | "return" + Expr + semicolon
                                            | "throw" + Expr + semicolon;

            Statement.Rule = semicolon
                             | IfStatement              //1. If
                             | WhileStatement           //2. While
                             | ForStatement             //3. For
                             | ForEachStatement         //4. ForEach
                             | UsingStatement           //5. Using
                             | SwitchStatement          //6. Switch
                             | BlockStatement           //7. Block
                             | TryCatchFinallyStatement //8. TryCatch
                             | ExprStatement            //9. Expr
                             | FlowControlStatement;    //10. FlowControl

            Statements.SetOption(TermOptions.IsList);
            Statements.Rule     = Statements + Statement | Empty;
            BlockStatement.Rule = LFb + Statements + RFb;

            SwitchStatements.Rule       = SwitchCaseStatement.Star() + SwitchDefaultStatement.Q();
            SwitchCaseStatement.Rule    = Symbol("case") + Expr + colon + Statements;
            SwitchDefaultStatement.Rule = "default" + colon + Statements;
            #endregion

            #region 3.4 Prog
            FuncContract.Rule = LSb +
                                FuncContractPre + semicolon +
                                FuncContractPost + semicolon +
                                FuncContractInv + semicolon +
                                RSb;
            FuncContractPre.Rule  = "pre" + LCb + ExprList.Q() + RCb;
            FuncContractPost.Rule = "post" + LCb + ExprList.Q() + RCb;
            FuncContractInv.Rule  = "invariant" + LCb + ExprList.Q() + RCb;

            ParameterList.Rule = MakeStarRule(ParameterList, comma, v);
            FuncDef.Rule       = "function" + v + LCb + ParameterList + RCb
                                 + GlobalList.Q()
                                 + FuncContract.Q()
                                 + BlockStatement;

            Element.Rule = Statement | FuncDef;
            Elements.SetOption(TermOptions.IsList);
            Elements.Rule = Elements + Element | Empty;

            Prog.Rule = Elements + Eof;

            Terminal Comment = new CommentTerminal("Comment", "/*", "*/");
            NonGrammarTerminals.Add(Comment);
            Terminal LineComment = new CommentTerminal("LineComment", "//", "\n");
            NonGrammarTerminals.Add(LineComment);

            #endregion
            #endregion

            #region 4. Set starting symbol
            if (!expressionGrammar)
            {
                Root = Prog; // Set grammar root
            }
            else
            {
                Root = Expr;
            }
            #endregion

            #region 5. Operators precedence
            RegisterOperators(1, "=", "+=", "-=", ":=");
            RegisterOperators(2, "|", "||");
            RegisterOperators(3, "&", "&&");
            RegisterOperators(4, "==", "!=", ">", "<", ">=", "<=");
            RegisterOperators(5, "is");
            RegisterOperators(6, "+", "-");
            RegisterOperators(7, "*", "/", "%");
            RegisterOperators(8, Associativity.Right, "^");
            RegisterOperators(9, "~", "!", "$", "++", "--");
            RegisterOperators(10, ".");

            //RegisterOperators(10, Associativity.Right, ".",",", ")", "(", "]", "[", "{", "}");
            //RegisterOperators(11, Associativity.Right, "else");
            #endregion

            #region 6. Punctuation symbols
            RegisterPunctuation("(", ")", "[", "]", "{", "}", ",", ";");
            #endregion
        }