Esempio n. 1
0
        public Calculadora() : base(caseSensitive: true)
        {
            var mas      = ToTerm("+");
            var menos    = ToTerm("-");
            var por      = ToTerm("*");
            var division = ToTerm("/");
            var potencia = ToTerm("^");

            /*---no terminal----*/
            var INICIO = new NonTerminal("INICIO");
            var EXPRE  = new NonTerminal("EXPRE");

            /*------------numero----*/
            NumberLiteral numero = TerminalFactory.CreateCSharpNumber("numero");

            this.Root = INICIO;


            INICIO.Rule = EXPRE;


            EXPRE.Rule = EXPRE + mas + EXPRE
                         | EXPRE + menos + EXPRE
                         | EXPRE + por + EXPRE
                         | EXPRE + division + EXPRE
                         | EXPRE + potencia + EXPRE
                         | numero;


            this.RegisterOperators(1, Associativity.Left, mas, menos);

            this.RegisterOperators(2, Associativity.Left, por, division);

            this.RegisterOperators(2, Associativity.Left, potencia);
        }
Esempio n. 2
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;
        }
Esempio n. 3
0
        public ExpressionEvaluatorGrammar()
            : base(false)
        { //false means case insensitive
            //Non-Terminal Node
            var program        = new NonTerminal("program", typeof(ProgramNode));
            var expression     = new NonTerminal("expression", typeof(ExpressionNode));
            var binaryOperator = new NonTerminal("binaryOperator", typeof(BinaryOperatorNode));


            //Identifier for Number and Variable
            var number = TerminalFactory.CreateCSharpNumber("number");

            number.AstConfig.NodeType = typeof(MyNumber);

            var Id        = new NonTerminal("Id");
            var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple");

            Id.AstConfig.NodeType = typeof(MyVariable);

            var stringLiteral = new StringLiteral("string", "\'", StringOptions.None);


            Id.Rule = MakePlusRule(Id, Id_simple);

            this.Root = program;
            //Expression
            program.Rule = expression;

            expression.Rule = number | Id | stringLiteral
                              | expression + binaryOperator + expression
                              | "(" + expression + ")";


            binaryOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "%"                                       //arithmetic
                                  | "&" | "|" | "^"                                                         //bit
                                  | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>"               // comparator
                                  | "AND" | "OR" | "CONTAINS" | ToTerm("NOT") + "CONTAINS" | ToTerm("NOT"); //others

            //Operators precedence
            RegisterOperators(10, "*", "/", "%");
            RegisterOperators(9, "+", "-");
            RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>");
            RegisterOperators(7, "^", "&", "|");
            RegisterOperators(6, "NOT");
            RegisterOperators(5, "AND");
            RegisterOperators(4, "OR", "CONTAINS");


            this.LanguageFlags = LanguageFlags.CreateAst;

            this.MarkPunctuation("(", ")");
        }
        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;
        }
        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;
        }
Esempio n. 6
0
        //Examples:
        //GAPoT biversor using terms form:
        //  -1.3<>, 1.2<1,2>, -4.6<3,4>
        public GaPoTNumBiversorConstructorGrammar()
            : base(caseSensitive: true)
        {
            // 1. Terminals
            var number = TerminalFactory.CreateCSharpNumber("number");

            number.Options = NumberOptions.AllowSign;

            var comma1 = ToTerm(",");

            // 2. Non-terminals
            var biversor      = new NonTerminal("biversor");
            var biversorTerm  = new NonTerminal("biversorTerm");
            var biversorTerm0 = new NonTerminal("biversorTerm0");
            var biversorTerm2 = new NonTerminal("biversorTerm2");

            biversorTerm0.Rule = number + "<" + ">";
            biversorTerm2.Rule = number + "<" + number + comma1 + number + ">";
            biversorTerm.Rule  = biversorTerm0 | biversorTerm2;
            biversor.Rule      = MakePlusRule(biversor, comma1, biversorTerm);

            // Set grammar root
            Root = biversor;

            // 5. Punctuation and transient terms
            MarkPunctuation("<", ">", ",");
            RegisterBracePair("<", ">");
            MarkTransient(biversorTerm);

            // 7. Syntax error reporting
            AddToNoReportGroup("<");
            AddToNoReportGroup(NewLine);

            //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;
        }
Esempio n. 7
0
        public SparkGrammar()
            : base(true)
        {
            var program   = new NonTerminal("Program");
            var statement = new NonTerminal("Statement");

            var assignStmt  = new NonTerminal("AssignStatement");
            var commandStmt = new NonTerminal("CommandStatement");

            var assignRHS     = new NonTerminal("AssignRHS");
            var createLayer   = new NonTerminal("CreateLayer");
            var createNetwork = new NonTerminal("CreateNetwork");
            var createTrainer = new NonTerminal("CreateTrainer");
            var runNetwork    = new NonTerminal("RunNetwork");
            var loadFile      = new NonTerminal("LoadFile");
            var convertData   = new NonTerminal("ConvertData");
            var findError     = new NonTerminal("FindError");

            var basicNetwork    = new NonTerminal("BasicNetwork");
            var advancedNetwork = new NonTerminal("AdvancedNetwork");

            var matrixLoadType = new NonTerminal("MatrixLoadType");

            var convertToVector  = new NonTerminal("ConvertToVector");
            var convertToIndices = new NonTerminal("ConvertToIndices");

            var supportedFileTypes = new NonTerminal("SupportedFileTypes");

            var printStatement = new NonTerminal("PrintStatement");
            var trainStatement = new NonTerminal("TrainStatement");
            var saveStatement  = new NonTerminal("SaveStatement");

            var kvPair     = new NonTerminal("KeyValuePair");
            var identifier = TerminalFactory.CreateCSharpIdentifier("Identifier");
            var number     = TerminalFactory.CreateCSharpNumber("Number");
            var str        = TerminalFactory.CreateCSharpString("string");


            program.Rule = statement + ";" | statement + ";" + program;

            statement.Rule = assignStmt | commandStmt;

            assignStmt.Rule = identifier + "=" + assignRHS;

            assignRHS.Rule = createLayer
                             | createNetwork
                             | createTrainer
                             | runNetwork
                             | loadFile
                             | convertData
                             | findError;

            createLayer.Rule = ToTerm("layer") + "with" + kvPair;

            createNetwork.Rule = basicNetwork
                                 | advancedNetwork;

            basicNetwork.Rule = identifier + "->" + identifier;

            advancedNetwork.Rule = createNetwork + "->" + identifier;

            runNetwork.Rule = ToTerm("run") + identifier + "on" + identifier;

            loadFile.Rule = ToTerm("load") + str + "as" + matrixLoadType
                            | ToTerm("load") + supportedFileTypes + str + "as" + matrixLoadType;

            matrixLoadType.Rule = ToTerm("row") + "major"
                                  | ToTerm("row") + "major" + "with" + "headers"
                                  | ToTerm("column") + "major";

            createTrainer.Rule = ToTerm("trainer") + "of" + "type" + identifier + "with" + kvPair;

            kvPair.Rule = identifier + "=" + (number | identifier)
                          | identifier + "=" + (number | identifier) + "," + kvPair;

            convertData.Rule = convertToVector
                               | convertToIndices;

            convertToVector.Rule = ToTerm("convert") + identifier + "to" + "class" + "vector"
                                   | ToTerm("convert") + identifier + "to" + "class" + "vector" + "of" + "size" + "=" + number;

            convertToIndices.Rule = ToTerm("convert") + identifier + "to" + "class" + "indices";

            findError.Rule = ToTerm("count") + "mismatches" + "between" + identifier + "and" + identifier
                             | ToTerm("get") + "mismatches" + "between" + identifier + "and" + identifier;

            commandStmt.Rule = printStatement
                               | trainStatement
                               | saveStatement;

            printStatement.Rule = ToTerm("print") + identifier;

            trainStatement.Rule = ToTerm("train") + identifier + "with" + identifier + "on"
                                  + "inputs" + identifier + "and" + "targets" + identifier;

            saveStatement.Rule = ToTerm("save") + identifier + "to" + str
                                 | ToTerm("save") + identifier + "as" + supportedFileTypes + "to" + str;

            supportedFileTypes.Rule = ToTerm("csv") | "tsv" | "ssv";

            MarkPunctuation("layer", "run", "train", "trainer",
                            "on", "and", "inputs", "targets", "major",
                            "load", "save", "print", "type", "indices",
                            "convert", "class", "vector", "of",
                            "mismatches", "between", "size", "as",
                            "to", "with", "of", "as", ";", ",",
                            "=", "->");

            this.Root = program;
        }
Esempio n. 8
0
        public JavaStubGrammar()
        {
            CommentTerminal single_line_comment = new CommentTerminal("SingleLineComment", "//", "\r", "\n");
            CommentTerminal delimited_comment   = new CommentTerminal("DelimitedComment", "/*", "*/");

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

            IdentifierTerminal identifier = new IdentifierTerminal("identifier");

            KeyTerm keyword_package      = Keyword("package");
            KeyTerm keyword_import       = Keyword("import");
            KeyTerm keyword_public       = Keyword("public");
            KeyTerm keyword_protected    = Keyword("protected");
            KeyTerm keyword_static       = Keyword("static");
            KeyTerm keyword_final        = Keyword("final");
            KeyTerm keyword_abstract     = Keyword("abstract");
            KeyTerm keyword_synchronized = Keyword("synchronized");
            KeyTerm keyword_default      = Keyword("default");
            KeyTerm keyword_native       = Keyword("native");
            KeyTerm keyword_volatile     = Keyword("volatile");
            KeyTerm keyword_transient    = Keyword("transient");
            KeyTerm keyword_enum         = Keyword("enum");
            KeyTerm keyword_class        = Keyword("class");
            KeyTerm keyword_interface    = Keyword("interface");
            KeyTerm keyword_at_interface = Keyword("@interface");
            KeyTerm keyword_extends      = Keyword("extends");
            KeyTerm keyword_implements   = Keyword("implements");
            KeyTerm keyword_throw        = Keyword("throw");
            KeyTerm keyword_throws       = Keyword("throws");
            KeyTerm keyword_null         = Keyword("null");
            KeyTerm keyword_super        = Keyword("super");
            KeyTerm keyword_true         = Keyword("true");
            KeyTerm keyword_false        = Keyword("false");
            KeyTerm keyword_new          = Keyword("new");

            var compile_unit                         = DefaultNonTerminal("compile_unit");
            var opt_package_decl                     = DefaultNonTerminal("opt_package_declaration");
            var package_decl                         = DefaultNonTerminal("package_declaration");
            var imports                              = DefaultNonTerminal("imports");
            var import                               = DefaultNonTerminal("import");
            var type_decls                           = DefaultNonTerminal("type_decls");
            var type_decl                            = DefaultNonTerminal("type_decl");
            var enum_decl                            = DefaultNonTerminal("enum_decl");
            var enum_body                            = DefaultNonTerminal("enum_body");
            var class_decl                           = DefaultNonTerminal("class_decl");
            var opt_generic_arg_decl                 = DefaultNonTerminal("opt_generic_arg_decl");
            var opt_extends_decl                     = DefaultNonTerminal("opt_extends_decl");
            var opt_implements_decl                  = DefaultNonTerminal("opt_implements_decl");
            var implements_decl                      = DefaultNonTerminal("implements_decl");
            var interface_decl                       = DefaultNonTerminal("interface_decl");
            var iface_or_at_iface                    = DefaultNonTerminal("iface_or_at_iface");
            var type_body                            = DefaultNonTerminal("type_body");
            var type_members                         = DefaultNonTerminal("type_members");
            var type_member                          = DefaultNonTerminal("type_member");
            var nested_type_decl                     = DefaultNonTerminal("nested_type_decl");
            var ctor_decl                            = DefaultNonTerminal("ctor_decl");
            var method_decl                          = DefaultNonTerminal("method_decl");
            var field_decl                           = DefaultNonTerminal("field_decl");
            var opt_field_assignment                 = DefaultNonTerminal("opt_field_assignment");
            var static_ctor_decl                     = DefaultNonTerminal("static_ctor_decl");
            var enum_members_decl                    = DefaultNonTerminal("enum_members_decl");
            var enum_member_initializers             = DefaultNonTerminal("enum_member_initializers");
            var enum_member_initializer              = DefaultNonTerminal("enum_member_initializer");
            var opt_enum_braces                      = DefaultNonTerminal("opt_enum_braces");
            var opt_final_field_assign               = DefaultNonTerminal("opt_final_field_assign");
            var final_field_assign                   = DefaultNonTerminal("final_field_assign");
            var terminate_decl_or_body               = DefaultNonTerminal("terminate_decl_or_body");
            var assignments                          = DefaultNonTerminal("assignments");
            var assignment                           = DefaultNonTerminal("assignment");
            var assign_expr                          = DefaultNonTerminal("assign_expr");
            var rvalue_expressions                   = DefaultNonTerminal("rvalue_expressions");
            var rvalue_expression                    = DefaultNonTerminal("rvalue_expression");
            var array_literal                        = DefaultNonTerminal("array_literal");
            var annotations                          = DefaultNonTerminal("annotations");
            var annotation                           = DefaultNonTerminal("annotation");
            var opt_annotation_args                  = DefaultNonTerminal("opt_annotation_args");
            var annotation_value_assignments         = DefaultNonTerminal("annotation_value_assignments");
            var annot_assign_expr                    = DefaultNonTerminal("annot_assign_expr");
            var modifiers_then_opt_generic_arg       = DefaultNonTerminal("modifiers_then_opt_generic_arg");
            var modifier_or_generic_arg              = DefaultNonTerminal("modifier_or_generic_arg");
            var modifiers                            = DefaultNonTerminal("modifiers");
            var modifier                             = DefaultNonTerminal("modifier");
            var argument_decls                       = DefaultNonTerminal("argument_decls");
            var argument_decl                        = DefaultNonTerminal("argument_decl");
            var comma_separated_types                = DefaultNonTerminal("comma_separated_types");
            var throws_decl                          = DefaultNonTerminal("throws_decl");
            var opt_throws_decl                      = DefaultNonTerminal("opt_throws_decl");
            var type_name                            = DefaultNonTerminal("type_name");
            var dotted_identifier                    = DefaultNonTerminal("dotted_identifier");
            var array_type                           = DefaultNonTerminal("array_type");
            var vararg_type                          = DefaultNonTerminal("vararg_type");
            var generic_type                         = DefaultNonTerminal("generic_type");
            var generic_definition_arguments         = DefaultNonTerminal("generic_definition_arguments");
            var generic_definition_argument          = DefaultNonTerminal("generic_definition_argument");
            var generic_definition_constraints       = DefaultNonTerminal("generic_definition_constraints");
            var generic_definition_arguments_spec    = DefaultNonTerminal("generic_definition_arguments_spec");
            var generic_instance_arguments_spec      = DefaultNonTerminal("generic_instance_arguments_spec");
            var generic_instance_arguments           = DefaultNonTerminal("generic_instance_arguments");
            var generic_instance_argument            = DefaultNonTerminal("generic_instance_argument");
            var generic_instance_identifier_or_q     = DefaultNonTerminal("generic_instance_identifier_or_q");
            var generic_instance_constraints         = DefaultNonTerminal("generic_instance_constraints");
            var generic_instance_constraints_extends = DefaultNonTerminal("generic_instance_constraints_extends");
            var generic_instance_constraints_super   = DefaultNonTerminal("generic_instance_constraints_super");
            var generic_instance_constraint_types    = DefaultNonTerminal("generic_instance_constraint_types");
            var impl_expressions                     = DefaultNonTerminal("impl_expressions");
            var impl_expression                      = DefaultNonTerminal("impl_expression");
            var call_super                           = DefaultNonTerminal("call_super");
            var super_args                           = DefaultNonTerminal("super_args");
            var default_value_expr                   = DefaultNonTerminal("default_value_expr");
            var default_value_casted                 = DefaultNonTerminal("default_value_casted");
            var default_value_literal                = DefaultNonTerminal("default_value_literal");
            var new_array                            = DefaultNonTerminal("new_array");
            var runtime_exception                    = DefaultNonTerminal("runtime_exception");
            var numeric_terminal                     = TerminalFactory.CreateCSharpNumber("numeric_value_literal");

            numeric_terminal.AddPrefix("-", NumberOptions.AllowSign);
            numeric_terminal.AddPrefix("+", NumberOptions.AllowSign);
            //numeric_terminal.AddSuffix ("f");
            numeric_terminal.AddSuffix("L");
            var numeric_literal = DefaultNonTerminal("numeric_literal");
            var string_literal  = TerminalFactory.CreateCSharpString("string_literal");
            var value_literal   = DefaultNonTerminal("value_literal");
            var identifier_wild = DefaultNonTerminal("identifier_wild");

            // <construction_rules>

            compile_unit.Rule     = opt_package_decl + imports + type_decls;
            opt_package_decl.Rule = package_decl | Empty;
            package_decl.Rule     = keyword_package + dotted_identifier + ";";
            imports.Rule          = MakeStarRule(imports, import);
            import.Rule           = keyword_import + dotted_identifier + ";";
            type_decls.Rule       = MakeStarRule(type_decls, type_decl);

            type_decl.Rule = class_decl | interface_decl | enum_decl;
            // FIXME: those modifiers_then_opt_generic_arg should be actually just modifiers... see modifiers_then_opt_generic_arg.Rule below.
            enum_decl.Rule         = annotations + modifiers_then_opt_generic_arg + keyword_enum + identifier + opt_implements_decl + "{" + enum_body + "}";
            enum_body.Rule         = Empty | enum_members_decl + type_members;
            class_decl.Rule        = annotations + modifiers_then_opt_generic_arg + keyword_class + identifier + opt_generic_arg_decl + opt_extends_decl + opt_implements_decl + type_body;
            interface_decl.Rule    = annotations + modifiers_then_opt_generic_arg + iface_or_at_iface + identifier + opt_generic_arg_decl + opt_extends_decl + opt_implements_decl + type_body;
            iface_or_at_iface.Rule = keyword_interface | keyword_at_interface;

            opt_generic_arg_decl.Rule         = Empty | "<" + generic_definition_arguments + ">";
            opt_extends_decl.Rule             = Empty | keyword_extends + implements_decl; // when it is used with an interface, it can be more than one...
            opt_implements_decl.Rule          = Empty | keyword_implements + implements_decl;
            implements_decl.Rule              = MakePlusRule(implements_decl, ToTerm(","), type_name);
            type_body.Rule                    = T("{") + type_members + T("}");
            annotations.Rule                  = MakeStarRule(annotations, annotation);
            annotation.Rule                   = T("@") + dotted_identifier + opt_annotation_args;
            opt_annotation_args.Rule          = Empty | T("(") + annotation_value_assignments + T(")");
            annotation_value_assignments.Rule = rvalue_expression | MakeStarRule(annotation_value_assignments, ToTerm(","), annot_assign_expr);
            annot_assign_expr.Rule            = assign_expr | T("{") + rvalue_expressions + T("}");

            // HACK: I believe this is an Irony bug that adding opt_generic_arg_decl here results in shift-reduce conflict, but it's too complicated to investigate the actual issue.
            // As a workaround I add generic arguments as part of this "modifier" so that it can be safely added to a generic method declaration.
            modifiers_then_opt_generic_arg.Rule = MakeStarRule(modifiers_then_opt_generic_arg, modifier_or_generic_arg);
            modifiers.Rule = MakeStarRule(modifiers, modifier);
            modifier_or_generic_arg.Rule = modifier | generic_definition_arguments_spec;
            modifier.Rule = keyword_public | keyword_protected | keyword_final | keyword_abstract | keyword_synchronized | keyword_default | keyword_native | keyword_volatile | keyword_transient | keyword_static;

            type_members.Rule             = MakeStarRule(type_members, type_member);
            type_member.Rule              = nested_type_decl | ctor_decl | method_decl | field_decl | static_ctor_decl;
            nested_type_decl.Rule         = type_decl;
            enum_members_decl.Rule        = enum_member_initializers + ";";
            enum_member_initializers.Rule = MakeStarRule(enum_member_initializers, ToTerm(","), enum_member_initializer);
            enum_member_initializer.Rule  = annotations + identifier + opt_enum_braces;
            opt_enum_braces.Rule          = Empty | "(" + ")";
            static_ctor_decl.Rule         = annotations + keyword_static + "{" + assignments + "}";
            assignments.Rule              = MakeStarRule(assignments, assignment);
            assignment.Rule         = assign_expr + ";";
            assign_expr.Rule        = identifier + "=" + rvalue_expression;
            rvalue_expressions.Rule = MakeStarRule(rvalue_expressions, ToTerm(","), rvalue_expression);
            rvalue_expression.Rule  = value_literal | new_array | type_name | identifier | array_literal | annotation;
            array_literal.Rule      = "{" + rvalue_expressions + "}";

            field_decl.Rule             = annotations + modifiers_then_opt_generic_arg + type_name + identifier + opt_field_assignment + ";" + opt_final_field_assign;
            opt_field_assignment.Rule   = Empty | "=" + rvalue_expression;
            opt_final_field_assign.Rule = Empty | "{" + assign_expr + ";" + "}";
            terminate_decl_or_body.Rule = ";" | ("{" + impl_expressions + "}") | (keyword_default + default_value_literal + ";");

            ctor_decl.Rule = annotations + modifiers_then_opt_generic_arg + identifier + "(" + argument_decls + ")" + opt_throws_decl + terminate_decl_or_body;             // these Empties can make the structure common to method_decl.

            method_decl.Rule = annotations + modifiers_then_opt_generic_arg + /*opt_generic_arg_decl*/ type_name + identifier + "(" + argument_decls + ")" + opt_throws_decl + terminate_decl_or_body;

            impl_expressions.Rule      = MakeStarRule(impl_expressions, impl_expression);
            impl_expression.Rule       = call_super | runtime_exception | assign_expr;
            call_super.Rule            = keyword_super + "(" + super_args + ")" + ";";
            super_args.Rule            = MakeStarRule(super_args, ToTerm(","), default_value_expr);
            default_value_expr.Rule    = keyword_null | default_value_casted | default_value_literal;
            default_value_casted.Rule  = "(" + type_name + ")" + default_value_expr;
            default_value_literal.Rule = numeric_terminal | "\"\"" | "{" + "}" | keyword_true | keyword_false;
            runtime_exception.Rule     = keyword_throw + keyword_new + identifier + "(\"Stub!\"" + ")" + ";";
            new_array.Rule             = keyword_new + dotted_identifier + "[" + numeric_literal + "]";

            argument_decls.Rule = annotations | MakeStarRule(argument_decls, ToTerm(","), argument_decl);

            argument_decl.Rule = annotations + type_name + identifier;

            throws_decl.Rule           = keyword_throws + comma_separated_types;
            comma_separated_types.Rule = MakeStarRule(comma_separated_types, ToTerm(","), type_name);
            opt_throws_decl.Rule       = Empty | throws_decl;

            type_name.Rule = dotted_identifier | array_type | vararg_type | generic_type;

            vararg_type.Rule = type_name + T("...");
            array_type.Rule  = type_name + ("[") + T("]");

            generic_definition_arguments_spec.Rule = "<" + generic_definition_arguments + ">";
            generic_type.Rule = dotted_identifier + generic_instance_arguments_spec;
            generic_instance_arguments_spec.Rule      = "<" + generic_instance_arguments + ">";
            generic_definition_arguments.Rule         = MakePlusRule(generic_definition_arguments, ToTerm(","), generic_definition_argument);
            generic_definition_argument.Rule          = identifier + generic_definition_constraints;
            generic_definition_constraints.Rule       = Empty | generic_instance_constraints_extends | generic_instance_constraints_super;
            generic_instance_arguments.Rule           = MakePlusRule(generic_instance_arguments, ToTerm(","), generic_instance_argument);
            generic_instance_argument.Rule            = generic_instance_identifier_or_q + generic_instance_constraints;
            generic_instance_identifier_or_q.Rule     = type_name | T("?");
            generic_instance_constraints.Rule         = Empty | generic_instance_constraints_extends | generic_instance_constraints_super;
            generic_instance_constraints_extends.Rule = keyword_extends + generic_instance_constraint_types;
            generic_instance_constraints_super.Rule   = keyword_super + generic_instance_constraint_types;
            generic_instance_constraint_types.Rule    = MakePlusRule(generic_instance_constraint_types, ToTerm("&"), type_name);

            dotted_identifier.Rule = MakePlusRule(dotted_identifier, ToTerm("."), identifier_wild);

            numeric_literal.Rule  = numeric_terminal;
            numeric_literal.Rule |= "(" + numeric_literal + "/" + numeric_literal + ")";
            value_literal.Rule    = string_literal | numeric_literal | keyword_null;
            identifier_wild.Rule  = identifier | "*";

            // Define AST node creators

            Func <string, string> stripGenerics = s => s.IndexOf('<') > 0 ? s.Substring(0, s.IndexOf('<')) : s;

            single_line_comment.AstConfig.NodeCreator = DoNothing;
            delimited_comment.AstConfig.NodeCreator   = DoNothing;
            identifier.AstConfig.NodeCreator          = (ctx, node) => node.AstNode = node.Token.ValueString;
            compile_unit.AstConfig.NodeCreator        = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new JavaPackage(null)
                {
                    Name = (string)node.ChildNodes [0].AstNode, Types = ((IEnumerable <JavaType>)node.ChildNodes [2].AstNode).ToList()
                };
            };
            opt_package_decl.AstConfig.NodeCreator     = SelectSingleChild;
            package_decl.AstConfig.NodeCreator         = SelectChildValueAt(1);
            imports.AstConfig.NodeCreator              = CreateArrayCreator <object> ();
            import.AstConfig.NodeCreator               = SelectChildValueAt(1);
            type_decls.AstConfig.NodeCreator           = CreateArrayCreator <JavaType> ();
            type_decl.AstConfig.NodeCreator            = SelectSingleChild;
            opt_generic_arg_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode;
            };
            opt_extends_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode;
            };
            opt_implements_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode;
            };
            implements_decl.AstConfig.NodeCreator = CreateArrayCreator <string> ();
            Action <ParseTreeNode, JavaType> fillType = (node, type) => {
                var  modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode;
                var  mods      = modsOrTps.OfType <string> ();
                bool isEnum    = node.ChildNodes [2].AstNode as string == "enum";
                type.Abstract      |= mods.Contains("abstract");
                type.Static        |= mods.Contains("static");
                type.Final         |= mods.Contains("final");
                type.Visibility     = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? "";
                type.Name           = (string)node.ChildNodes [3].AstNode;
                type.Deprecated     = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated";
                type.TypeParameters = isEnum ? null : (JavaTypeParameters)node.ChildNodes [4].AstNode;
                type.Members        = (IList <JavaMember>)node.ChildNodes [isEnum ? 6 : 7].AstNode;
            };

            enum_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var type = new JavaClass(null)
                {
                    Extends = "java.lang.Enum", Final = true
                };
                var methods = new JavaMember [] {
                    new JavaMethod(null)
                    {
                        Deprecated = "not deprecated",
                        Name       = "valueOf",
                        // Return needs to be filled later, with full package name.
                        Static     = true,
                        Visibility = "public",
                        Parameters = new JavaParameter [] { new JavaParameter(null)
                                                            {
                                                                Name = "name", Type = "java.lang.String"
                                                            } },
                    },
                    new JavaMethod(null)
                    {
                        Deprecated = "not deprecated",
                        Name       = "values",
                        // Return needs to be filled later, with full package name.
                        Static     = true,
                        Visibility = "public",
                        Parameters = new JavaParameter [0],
                    }
                };
                fillType(node, type);
                node.AstNode = type;
            };
            class_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var exts  = ((IEnumerable <string>)node.ChildNodes [5].AstNode) ?? Enumerable.Empty <string> ();
                var impls = ((IEnumerable <string>)node.ChildNodes [6].AstNode) ?? Enumerable.Empty <string> ();
                var ext   = exts.FirstOrDefault() ?? "java.lang.Object";
                var type  = new JavaClass(null)
                {
                    Extends        = stripGenerics(ext),
                    ExtendsGeneric = ext,
                    Implements     = impls.Select(s => new JavaImplements {
                        Name = stripGenerics(s), NameGeneric = s
                    }).ToArray(),
                };
                fillType(node, type);
                node.AstNode = type;
            };
            interface_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                bool annot = node.ChildNodes [2].AstNode as string == "@interface";
                var  exts  = ((IEnumerable <string>)node.ChildNodes [5].AstNode) ?? Enumerable.Empty <string> ();
                var  impls = ((IEnumerable <string>)node.ChildNodes [6].AstNode) ?? Enumerable.Empty <string> ();
                var  type  = new JavaInterface(null)
                {
                    Implements = exts.Concat(impls).Select(s => new JavaImplements {
                        Name = stripGenerics(s), NameGeneric = s
                    }).ToList(),
                };
                if (annot)
                {
                    type.Implements.Add(new JavaImplements {
                        Name = "java.lang.annotation.Annotation", NameGeneric = "java.lang.annotation.Annotation"
                    });
                }
                fillType(node, type);
                node.AstNode = type;
            };
            iface_or_at_iface.AstConfig.NodeCreator = SelectSingleChild;
            type_body.AstConfig.NodeCreator         = SelectChildValueAt(1);
            type_members.AstConfig.NodeCreator      = CreateArrayCreator <JavaMember> ();
            type_member.AstConfig.NodeCreator       = SelectSingleChild;
            nested_type_decl.AstConfig.NodeCreator  = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new JavaNestedType(null)
                {
                    Type = (JavaType)node.ChildNodes [0].AstNode
                };
            };
            Action <ParseTreeNode, JavaMethodBase> fillMethodBase = (node, method) => {
                bool ctor      = node.ChildNodes.Count == 8;
                var  modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode;
                var  mods      = modsOrTps.OfType <string> ();
                method.Static            = mods.Contains("static");
                method.Visibility        = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? "";
                method.Name              = (string)node.ChildNodes [ctor ? 2 : 3].AstNode;
                method.Parameters        = ((IEnumerable <JavaParameter>)node.ChildNodes [ctor ? 4 : 5].AstNode).ToArray();
                method.ExtendedSynthetic = mods.Contains("synthetic");
                // HACK: Exception "name" can be inconsistent for nested types, and this nested type detection is hacky.
                Func <string, string> stripPackage = s => {
                    var packageTokens = s.Split('.').TakeWhile(t => !t.Any(c => Char.IsUpper(c)));
                    return(s.Substring(Enumerable.Sum(packageTokens.Select(t => t.Length)) + packageTokens.Count()));
                };
                method.Exceptions = ((IEnumerable <string>)node.ChildNodes [ctor ? 6 : 7].AstNode)
                                    ?.Select(s => new JavaException {
                    Type = s, Name = stripPackage(s)
                })
                                    ?.ToArray();
                method.Deprecated     = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated";
                method.Final          = mods.Contains("final");
                method.TypeParameters = modsOrTps.OfType <JavaTypeParameters> ().FirstOrDefault();
            };

            ctor_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var annots    = node.ChildNodes [0].AstNode;
                var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode;
                var mods      = modsOrTps.OfType <string> ();
                var ctor      = new JavaConstructor(null);
                fillMethodBase(node, ctor);
                node.AstNode = ctor;
            };
            method_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var annots    = node.ChildNodes [0].AstNode;
                var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode;
                var mods      = modsOrTps.OfType <string> ();
                var method    = new JavaMethod(null)
                {
                    Return            = (string)node.ChildNodes [2].AstNode,
                    Abstract          = mods.Contains("abstract"),
                    Native            = mods.Contains("native"),
                    Synchronized      = mods.Contains("synchronized"),
                    ExtendedSynthetic = mods.Contains("synthetic"),
                };
                fillMethodBase(node, method);
                node.AstNode = method;
            };
            field_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var annots    = node.ChildNodes [0].AstNode;
                var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode;
                var mods      = modsOrTps.OfType <string> ();
                var value     = node.ChildNodes [4].AstNode?.ToString();
                var type      = (string)node.ChildNodes [2].AstNode;
                node.AstNode = new JavaField(null)
                {
                    Static      = mods.Contains("static"),
                    Visibility  = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? "",
                    Type        = stripGenerics(type),
                    TypeGeneric = type,
                    Name        = (string)node.ChildNodes [3].AstNode,
                    Deprecated  = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated",
                    Value       = value == "null" ? null : value,               // null will not be explicitly written.
                    Volatile    = mods.Contains("volatile"),
                    Final       = mods.Contains("final"),
                    Transient   = mods.Contains("transient"),
                };
            };
            opt_field_assignment.AstConfig.NodeCreator   = (ctx, node) => node.AstNode = node.ChildNodes.Count > 0 ? node.ChildNodes [1].AstNode : null;
            opt_final_field_assign.AstConfig.NodeCreator = (ctx, node) => node.AstNode = node.ChildNodes.Count > 0 ? node.ChildNodes [1].AstNode : null;
            static_ctor_decl.AstConfig.NodeCreator       = DoNothing;       // static constructors are ignorable.
            enum_body.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                var ml = new List <JavaMember> ();
                foreach (var c in node.ChildNodes)
                {
                    ml.AddRange((IEnumerable <JavaMember>)c.AstNode);
                }
                node.AstNode = ml;
            };
            enum_members_decl.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                if (node.ChildNodes.Count > 0)
                {
                    node.AstNode = ((IEnumerable <string>)node.ChildNodes [0].AstNode)
                                   .Select(s => new JavaField(null)
                    {
                        Name       = s,
                        Final      = true,
                        Deprecated = "not deprecated",
                        Static     = true,
                        // Type needs to be filled later, with full package name.
                        Visibility = "public"
                    });
                }
            };
            enum_member_initializers.AstConfig.NodeCreator = CreateArrayCreator <string> ();
            enum_member_initializer.AstConfig.NodeCreator  = SelectChildValueAt(1);
            opt_enum_braces.AstConfig.NodeCreator          = DoNothing;
            terminate_decl_or_body.AstConfig.NodeCreator   = DoNothing;           // method/ctor body doesn't matter.
            assignments.AstConfig.NodeCreator = CreateArrayCreator <object> ();
            assignment.AstConfig.NodeCreator  = SelectChildValueAt(0);
            assign_expr.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new KeyValuePair <string, string?> ((string)node.ChildNodes [0].AstNode, node.ChildNodes [2].AstNode?.ToString());
            };
            rvalue_expressions.AstConfig.NodeCreator = CreateArrayCreator <object> ();
            rvalue_expression.AstConfig.NodeCreator  = SelectSingleChild;
            array_literal.AstConfig.NodeCreator      = CreateStringFlattener();
            annotations.AstConfig.NodeCreator        = CreateArrayCreator <string> ();
            annotation.AstConfig.NodeCreator         = (ctx, node) => {
                ProcessChildren(ctx, node.ChildNodes [1]);                  // we only care about name.
                node.AstNode = node.ChildNodes [1].AstNode;
            };
            opt_annotation_args.AstConfig.NodeCreator            = DoNothing;
            annotation_value_assignments.AstConfig.NodeCreator   = DoNothing;
            annot_assign_expr.AstConfig.NodeCreator              = DoNothing;
            modifiers_then_opt_generic_arg.AstConfig.NodeCreator = CreateArrayCreator <object> ();
            modifier_or_generic_arg.AstConfig.NodeCreator        = SelectSingleChild;
            modifiers.AstConfig.NodeCreator      = CreateArrayCreator <string> ();
            modifier.AstConfig.NodeCreator       = CreateStringFlattener();
            argument_decls.AstConfig.NodeCreator = CreateArrayCreator <JavaParameter> ();
            argument_decl.AstConfig.NodeCreator  = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new JavaParameter(null)
                {
                    Type = (string)node.ChildNodes [1].AstNode, Name = (string)node.ChildNodes [2].AstNode
                };
            };
            opt_throws_decl.AstConfig.NodeCreator       = SelectSingleChild;
            throws_decl.AstConfig.NodeCreator           = SelectChildValueAt(1);
            comma_separated_types.AstConfig.NodeCreator = CreateArrayCreator <string> ();
            type_name.AstConfig.NodeCreator             = SelectSingleChild;
            dotted_identifier.AstConfig.NodeCreator     = CreateStringFlattener(".");
            array_type.AstConfig.NodeCreator            = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = node.ChildNodes [0].AstNode + "[]";
            };
            vararg_type.AstConfig.NodeCreator  = CreateStringFlattener();
            generic_type.AstConfig.NodeCreator = CreateStringFlattener();
            generic_definition_arguments_spec.AstConfig.NodeCreator = SelectChildValueAt(1);
            generic_instance_arguments_spec.AstConfig.NodeCreator   = (ctx, node) => {
                // It is distinct from generic type parameters definition.
                ProcessChildren(ctx, node);
                node.AstNode = "<" + string.Join(", ", (IEnumerable <string>)node.ChildNodes [1].AstNode) + ">";
            };
            generic_definition_arguments.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new JavaTypeParameters((JavaMethod?)null)
                {
                    TypeParameters = node.ChildNodes.Select(c => c.AstNode).Cast <JavaTypeParameter> ().ToList()
                };
            };
            generic_definition_argument.AstConfig.NodeCreator = (ctx, node) => {
                ProcessChildren(ctx, node);
                node.AstNode = new JavaTypeParameter(null)
                {
                    Name = (string)node.ChildNodes [0].AstNode,
                    GenericConstraints = (JavaGenericConstraints)node.ChildNodes [1].AstNode
                };
            };
            generic_definition_constraints.AstConfig.NodeCreator   = SelectSingleChild;
            generic_instance_arguments.AstConfig.NodeCreator       = CreateArrayCreator <string> ();
            generic_instance_argument.AstConfig.NodeCreator        = CreateStringFlattener();
            generic_instance_identifier_or_q.AstConfig.NodeCreator = SelectSingleChild;
            generic_instance_constraints.AstConfig.NodeCreator     = (ctx, node) => {
                ProcessChildren(ctx, node);
                var c = (JavaGenericConstraints?)node.ChildNodes.FirstOrDefault()?.AstNode;
                if (c != null)
                {
                    node.AstNode = " " + c.BoundsType + " " + string.Join(" & ", c.GenericConstraints.Select(cc => cc.Type));
                }
            };
            AstNodeCreator createGenericConstaints = (ctx, node) => {
                ProcessChildren(ctx, node);
                var cl = ((IEnumerable <string>)node.ChildNodes [1].AstNode).Select(s => new JavaGenericConstraint {
                    Type = s
                });
                node.AstNode = new JavaGenericConstraints()
                {
                    BoundsType         = (string)node.ChildNodes [0].AstNode,
                    GenericConstraints = cl.Any() ? cl.ToArray() : null,
                };
            };

            generic_instance_constraints_extends.AstConfig.NodeCreator = createGenericConstaints;
            generic_instance_constraints_super.AstConfig.NodeCreator   = createGenericConstaints;
            generic_instance_constraint_types.AstConfig.NodeCreator    = CreateArrayCreator <string> ();
            impl_expressions.AstConfig.NodeCreator = CreateArrayCreator <object> ();
            impl_expression.AstConfig.NodeCreator  = SelectSingleChild;
            // each expression item is not seriously processed.
            // They are insignificant except for consts, and for consts they are just string values.
            call_super.AstConfig.NodeCreator            = CreateStringFlattener();
            super_args.AstConfig.NodeCreator            = CreateStringFlattener();
            default_value_expr.AstConfig.NodeCreator    = CreateStringFlattener();
            default_value_casted.AstConfig.NodeCreator  = CreateStringFlattener();
            default_value_literal.AstConfig.NodeCreator = CreateStringFlattener();
            new_array.AstConfig.NodeCreator             = DoNothing;
            runtime_exception.AstConfig.NodeCreator     = CreateStringFlattener();
            Func <string, string, string> stripTail = (s, t) => s.EndsWith(t, StringComparison.Ordinal) ? s.Substring(0, s.Length - t.Length) : s;

            numeric_terminal.AstConfig.NodeCreator = (ctx, node) => node.AstNode = stripTail(stripTail(node.Token.Text, "L"), "f");
            numeric_literal.AstConfig.NodeCreator  = CreateStringFlattener();
            string_literal.AstConfig.NodeCreator   = (ctx, node) => node.AstNode = '"' + node.Token.ValueString + '"';
            value_literal.AstConfig.NodeCreator    = SelectSingleChild;
            identifier_wild.AstConfig.NodeCreator  = SelectSingleChild;

            this.Root = compile_unit;
        }
Esempio n. 9
0
        public SqlGrammar()
            : base(false)
        { //SQL is case insensitive
            //Terminals
            var comment     = new CommentTerminal("comment", "/*", "*/");
            var lineComment = new CommentTerminal("line_comment", "--", "\n", "\r\n");

            NonGrammarTerminals.Add(comment);
            NonGrammarTerminals.Add(lineComment);
            var number = TerminalFactory.CreateCSharpNumber("number");

            number.Options = NumberOptions.AllowSign;
            var string_literal = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote);

            string_literal.AddStartEnd("N'", "'", StringOptions.AllowsDoubledQuote | StringOptions.AllowsLineBreak);
            var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple"); //covers normal identifiers (abc) and quoted id's ([abc d], "abc d")

            Id_simple.AddPrefix("@@", IdOptions.NameIncludesPrefix);
            Id_simple.AddPrefix("@", IdOptions.NameIncludesPrefix);

            var comma        = ToTerm(",");
            var dot          = ToTerm(".");
            var equals       = ToTerm("=");
            var plus         = ToTerm("+");
            var CREATE       = ToTerm("CREATE");
            var NULL         = ToTerm("NULL");
            var NOT          = ToTerm("NOT");
            var UNIQUE       = ToTerm("UNIQUE");
            var WITH         = ToTerm("WITH");
            var TABLE        = ToTerm("TABLE");
            var VIEW         = ToTerm("VIEW");
            var DATABASE     = ToTerm("DATABASE");
            var ALTER        = ToTerm("ALTER");
            var ADD          = ToTerm("ADD");
            var COLUMN       = ToTerm("COLUMN");
            var DROP         = ToTerm("DROP");
            var CONSTRAINT   = ToTerm("CONSTRAINT");
            var INDEX        = ToTerm("INDEX");
            var CLUSTERED    = ToTerm("CLUSTERED");
            var NONCLUSTERED = ToTerm("NONCLUSTERED");
            var ON           = ToTerm("ON");
            var KEY          = ToTerm("KEY");
            var PRIMARY      = ToTerm("PRIMARY");
            var INSERT       = ToTerm("INSERT");
            var INTO         = ToTerm("INTO");
            var UPDATE       = ToTerm("UPDATE");
            var SET          = ToTerm("SET");
            var VALUES       = ToTerm("VALUES");
            var DELETE       = ToTerm("DELETE");
            var SELECT       = ToTerm("SELECT");
            var FROM         = ToTerm("FROM");
            var AS           = ToTerm("AS");
            var COUNT        = ToTerm("COUNT");
            var JOIN         = ToTerm("JOIN");
            var BY           = ToTerm("BY");
            var DEFAULT      = ToTerm("DEFAULT");
            var CHECK        = ToTerm("CHECK");
            var REPLICATION  = ToTerm("REPLICATION");
            var FOR          = ToTerm("FOR");
            var COLLATE      = ToTerm("COLLATE");
            var IDENTITY     = ToTerm("IDENTITY");
            var TEXTIMAGE_ON = ToTerm("TEXTIMAGE_ON");
            var IF           = ToTerm("IF");
            var ELSE         = ToTerm("ELSE");
            var BEGIN        = ToTerm("BEGIN");
            var END          = ToTerm("END");
            var GO           = ToTerm("GO");
            var PRINT        = ToTerm("PRINT");
            var IS           = ToTerm("IS");
            var USE          = ToTerm("USE");
            var EXEC         = ToTerm("EXEC");
            var NOCHECK      = ToTerm("NOCHECK");
            var CASCADE      = ToTerm("CASCADE");
            var TYPE         = ToTerm("TYPE");
            var PROCEDURE    = ToTerm("PROCEDURE");
            var DECLARE      = ToTerm("DECLARE");
            var TRY          = ToTerm("TRY");
            var CATCH        = ToTerm("CATCH");
            var CAST         = ToTerm("CAST");
            var AND          = ToTerm("AND");
            var OR           = ToTerm("OR");
            var GRANT        = ToTerm("GRANT");
            var UNION        = ToTerm("UNION");
            var ALL          = ToTerm("ALL");
            var CASE         = ToTerm("CASE");
            var WHEN         = ToTerm("WHEN");
            var THEN         = ToTerm("THEN");
            var RETURN       = ToTerm("RETURN");
            var COMMIT       = ToTerm("COMMIT");
            var TRAN         = ToTerm("TRAN");
            var TRANSACTION  = ToTerm("TRANSACTION");
            var TOP          = ToTerm("TOP");
            var MERGE        = ToTerm("MERGE");
            var USING        = ToTerm("USING");
            var MATCHED      = ToTerm("MATCHED");
            var TARGET       = ToTerm("TARGET");
            var TRUNCATE     = ToTerm("TRUNCATE");
            var ROLLBACK     = ToTerm("ROLLBACK");
            var STATISTICS   = ToTerm("STATISTICS");
            var ROLE         = ToTerm("ROLE");
            var WHILE        = ToTerm("WHILE");
            var BREAK        = ToTerm("BREAK");
            var REBUILD      = ToTerm("REBUILD");
            var CHECKPOINT   = ToTerm("CHECKPOINT");
            var HASH         = ToTerm("HASH");
            var OUTPUT       = ToTerm("OUTPUT");

            //Non-terminals
            var Id                     = new NonTerminal("Id");
            var IdWithAliasOpt         = new NonTerminal("IdWithAliasOpt");
            var stmt                   = new NonTerminal("stmt");
            var createTableStmt        = new NonTerminal("createTableStmt");
            var createIndexStmt        = new NonTerminal("createIndexStmt");
            var createViewStmt         = new NonTerminal("createViewStmt");
            var createTypeStmt         = new NonTerminal("createTypeStmt");
            var createProcedureStmt    = new NonTerminal("createProcedureStmt");
            var variableDefLists       = new NonTerminal("variableDefLists");
            var variableDefList        = new NonTerminal("variableDefList");
            var variableDef            = new NonTerminal("variableDef");
            var outputOpt              = new NonTerminal("outputOpt");
            var primaryKeyOpt          = new NonTerminal("primaryKeyOpt");
            var alterStmt              = new NonTerminal("alterStmt");
            var dropTableStmt          = new NonTerminal("dropTableStmt");
            var dropIndexStmt          = new NonTerminal("dropIndexStmt");
            var dropViewStmt           = new NonTerminal("dropViewStmt");
            var dropProcedureStmt      = new NonTerminal("dropProcedureStmt");
            var selectStmt             = new NonTerminal("selectStmt");
            var insertStmt             = new NonTerminal("insertStmt");
            var updateStmt             = new NonTerminal("updateStmt");
            var deleteStmt             = new NonTerminal("deleteStmt");
            var ifStmt                 = new NonTerminal("ifStmt");
            var elseStmt               = new NonTerminal("elseStmt");
            var fieldDef               = new NonTerminal("fieldDef");
            var fieldDefList           = new NonTerminal("fieldDefList");
            var nullSpecOpt            = new NonTerminal("nullSpecOpt");
            var typeName               = new NonTerminal("typeName");
            var constraintListOpt      = new NonTerminal("constraintListOpt");
            var constraintDef          = new NonTerminal("constraintDef");
            var indexContraintDef      = new NonTerminal("indexContraintDef");
            var constraintTypeOpt      = new NonTerminal("constraintTypeOptOpt");
            var defaultValueOpt        = new NonTerminal("defaultValueOpt");
            var idlist                 = new NonTerminal("idlist");
            var idOrExpression         = new NonTerminal("idOrExpression");
            var idOrExpressionList     = new NonTerminal("idOrExpressionList");
            var idlistForSelect        = new NonTerminal("idlistForSelect");
            var idlistParOpt           = new NonTerminal("idlistPar");
            var orderList              = new NonTerminal("orderList");
            var orderMember            = new NonTerminal("orderMember");
            var orderDirOpt            = new NonTerminal("orderDirOpt");
            var defaultValueParams     = new NonTerminal("defaultValueParams");
            var indexTypeOpt           = new NonTerminal("indexTypeOpt");
            var indexTypeList          = new NonTerminal("indexTypeList");
            var withClauseOpt          = new NonTerminal("withClauseOpt");
            var alterCmdOpt            = new NonTerminal("alterCmdOpt");
            var insertData             = new NonTerminal("insertData");
            var intoOpt                = new NonTerminal("intoOpt");
            var assignList             = new NonTerminal("assignList");
            var whereClauseOpt         = new NonTerminal("whereClauseOpt");
            var andClauseOpt           = new NonTerminal("andClauseOpt");
            var betweenClauseOpt       = new NonTerminal("betweenClauseOpt");
            var assignment             = new NonTerminal("assignment");
            var expression             = new NonTerminal("expression");
            var exprList               = new NonTerminal("exprList");
            var selRestrOpt            = new NonTerminal("selRestrOpt");
            var selList                = new NonTerminal("selList");
            var intoClauseOpt          = new NonTerminal("intoClauseOpt");
            var fromClauseOpt          = new NonTerminal("fromClauseOpt");
            var groupClauseOpt         = new NonTerminal("groupClauseOpt");
            var havingClauseOpt        = new NonTerminal("havingClauseOpt");
            var orderClauseOpt         = new NonTerminal("orderClauseOpt");
            var columnItemList         = new NonTerminal("columnItemList");
            var columnItem             = new NonTerminal("columnItem");
            var columnSource           = new NonTerminal("columnSource");
            var asOpt                  = new NonTerminal("asOpt");
            var aliasOpt               = new NonTerminal("aliasOpt");
            var aggregate              = new NonTerminal("aggregate");
            var aggregateArg           = new NonTerminal("aggregateArg");
            var aggregateName          = new NonTerminal("aggregateName");
            var tuple                  = new NonTerminal("tuple");
            var joinChainOpt           = new NonTerminal("joinChainOpt");
            var joinKindOpt            = new NonTerminal("joinKindOpt");
            var term                   = new NonTerminal("term");
            var unExpr                 = new NonTerminal("unExpr");
            var unOp                   = new NonTerminal("unOp");
            var binExpr                = new NonTerminal("binExpr");
            var binOp                  = new NonTerminal("binOp");
            var betweenExpr            = new NonTerminal("betweenExpr");
            var notOpt                 = new NonTerminal("notOpt");
            var funCall                = new NonTerminal("funCall");
            var stmtLine               = new NonTerminal("stmtLine");
            var semiOpt                = new NonTerminal("semiOpt");
            var stmtList               = new NonTerminal("stmtList");
            var funArgsOpt             = new NonTerminal("funArgsOpt");
            var inStmt                 = new NonTerminal("inStmt");
            var settingList            = new NonTerminal("settingList");
            var settingListItem        = new NonTerminal("settingListItem");
            var onOpt                  = new NonTerminal("onOpt");
            var textImageOnOpt         = new NonTerminal("textImageOnOpt");
            var defaultValueParamsList = new NonTerminal("defaultValueParamsList");
            var typeNameParamsList     = new NonTerminal("typeNameParamsList");
            var notForReplOpt          = new NonTerminal("notForReplOpt");
            var collateOpt             = new NonTerminal("collateOpt");
            var columnDef              = new NonTerminal("columnDef");
            var identityOpt            = new NonTerminal("identityOpt");
            var referencesOpt          = new NonTerminal("referencesOpt");
            var fieldDefLists          = new NonTerminal("fieldDefLists");
            var onListOpt              = new NonTerminal("onListOpt");
            var printStmt              = new NonTerminal("printStmt");
            var beginEndStmt           = new NonTerminal("beginEndStmt");
            var beginTryCatchStmt      = new NonTerminal("beginTryCatchStmt");
            var beginEndStmtList       = new NonTerminal("beginEndStmtList");
            var isNullOpt              = new NonTerminal("isNullOpt");
            var setStmtOpt             = new NonTerminal("setStmtOpt");
            var useStmt                = new NonTerminal("useStmt");
            var forOpt                 = new NonTerminal("forOpt");
            var execStmt               = new NonTerminal("execStmt");
            var cascadeOpt             = new NonTerminal("cascadeOpt");
            var cascadeListOpt         = new NonTerminal("cascadeListOpt");
            var alterProcedureStmt     = new NonTerminal("alterProcedureStmt");
            var declareStmt            = new NonTerminal("declareStmt");
            var concatStringItem       = new NonTerminal("concatStringItem");
            var concatStringList       = new NonTerminal("concatStringList");
            var castFunCall            = new NonTerminal("castFunCall");
            var funCallList            = new NonTerminal("funCallList");
            var funcallDelim           = new NonTerminal("funcallDelim");
            var declareList            = new NonTerminal("declareList");
            var declareListItem        = new NonTerminal("declareListItem");
            var grantStmt              = new NonTerminal("grantStmt");
            var joinChainOptList       = new NonTerminal("joinChainOptList");
            var leftParenOpt           = new NonTerminal("leftParenOpt");
            var rightParenOpt          = new NonTerminal("rightParenOpt");
            var unionAllOpt            = new NonTerminal("unionAllOpt");
            var selectCaseStmts        = new NonTerminal("selectCaseStmts");
            var selectCaseStmt         = new NonTerminal("selectCaseStmt");
            var caseWhenThenLists      = new NonTerminal("caseWhenThenLists");
            var caseWhenThenList       = new NonTerminal("caseWhenThenList");
            var caseWhenThenStmt       = new NonTerminal("caseWhenThenStmt");
            var unionAllListOpt        = new NonTerminal("unionAllListOpt");
            var returnStmt             = new NonTerminal("returnStmt");
            var beginTransStmt         = new NonTerminal("beginTransStmt");
            var rollbackTransStmt      = new NonTerminal("rollbackTransStmt");
            var topOpt                 = new NonTerminal("topOpt");
            var mergeStmt              = new NonTerminal("mergeStmt");
            var mergeWhenMatched       = new NonTerminal("mergeWhenMatched");
            var mergeWhenNotMatched    = new NonTerminal("mergeWhenNotMatched");
            var truncateStmt           = new NonTerminal("truncateStmt");
            var commitTransStmt        = new NonTerminal("commitTransStmt");
            var noLockOpt              = new NonTerminal("noLockOpt");
            var declareTableStmt       = new NonTerminal("declareTableStmt");
            var joinStmtOpt            = new NonTerminal("joinStmtOpt");
            var forXmlStmtOpt          = new NonTerminal("forXmlStmtOpt");
            var forXmlFunCallList      = new NonTerminal("forXmlFunCallList");
            var funArgsList            = new NonTerminal("funArgsList");
            var updateStatisticsStmt   = new NonTerminal("updateStatisticsStmt");
            var createRoleStmt         = new NonTerminal("createRoleStmt");
            var whileStmt              = new NonTerminal("whileStmt");
            var alterIndexStmt         = new NonTerminal("alterIndexStmt");
            var ifCondition            = new NonTerminal("ifCondition");
            var ifConditionChain       = new NonTerminal("ifConditionChain");
            var hashOpt                = new NonTerminal("hashOpt");
            var IdAsType               = new NonTerminal("IdAsType");
            var selectWithUnion        = new NonTerminal("selectWithUnion");
            var withStmt               = new NonTerminal("withStmt");

            //BNF Rules
            this.Root             = stmtList;
            stmtLine.Rule         = stmt + semiOpt;
            semiOpt.Rule          = Empty | ";";
            stmtList.Rule         = MakePlusRule(stmtList, stmtLine);
            setStmtOpt.Rule       = Empty | SET + Id + Id | SET + Id + equals + (leftParenOpt + selectStmt + rightParenOpt | Id | funCall | concatStringList | expression);
            useStmt.Rule          = USE + Id;
            execStmt.Rule         = EXEC + (Empty | Id | Id + ".." + Id) + (leftParenOpt + funArgsList + rightParenOpt);
            declareStmt.Rule      = DECLARE + declareList;
            declareTableStmt.Rule = DECLARE + Id + TABLE + "(" + fieldDefList + ")";
            declareListItem.Rule  = Id + typeName
                                    | Id + typeName + equals + term;
            declareList.Rule        = MakePlusRule(declareList, comma, declareListItem);
            castFunCall.Rule        = CAST + "(" + funCall + asOpt + (Empty | typeName) + ")" + asOpt + (Empty | typeName);
            grantStmt.Rule          = GRANT + term + ON + TYPE + "::" + Id + "TO" + Id;
            returnStmt.Rule         = RETURN + term;
            leftParenOpt.Rule       = Empty | "(";
            rightParenOpt.Rule      = Empty | ")";
            unionAllOpt.Rule        = Empty | UNION + ALL + leftParenOpt + selectStmt + rightParenOpt;
            unionAllListOpt.Rule    = MakeStarRule(unionAllListOpt, unionAllOpt);
            idOrExpression.Rule     = Id | expression;
            idOrExpressionList.Rule = MakeStarRule(idOrExpressionList, comma, idOrExpression);
            whileStmt.Rule          = WHILE + expression + beginEndStmt;

            //ID
            Id.Rule               = MakePlusRule(Id, dot, Id_simple);
            IdWithAliasOpt.Rule   = Id | Id + Id | Id + AS + Id;
            IdAsType.Rule         = Id + AS + typeName;
            concatStringItem.Rule = leftParenOpt + term + rightParenOpt;
            concatStringList.Rule = MakePlusRule(concatStringList, plus, concatStringItem);

            stmt.Rule = createProcedureStmt | createTableStmt | createIndexStmt | createViewStmt | createTypeStmt | createRoleStmt
                        | declareTableStmt | alterStmt | dropTableStmt | dropIndexStmt | dropViewStmt | dropProcedureStmt
                        | selectWithUnion | insertStmt | updateStmt | deleteStmt | whileStmt
                        | GO | ifStmt | elseStmt | beginEndStmt | printStmt | withStmt
                        | execStmt | setStmtOpt | useStmt | funCall | declareStmt | returnStmt
                        | grantStmt | mergeStmt | truncateStmt | updateStatisticsStmt
                        | beginTransStmt | commitTransStmt | rollbackTransStmt
                        | BREAK | CHECKPOINT
                        | ";";

            onOpt.Rule          = Empty | ON + Id;
            textImageOnOpt.Rule = Empty | TEXTIMAGE_ON + Id;
            forOpt.Rule         = Empty | FOR + Id;
            onListOpt.Rule      = MakePlusRule(onListOpt, onOpt);
            withStmt.Rule       = WITH + Id + AS + leftParenOpt + selectStmt + rightParenOpt;
            fieldDefLists.Rule  = MakePlusRule(fieldDefLists, fieldDefList);

            printStmt.Rule = PRINT + concatStringList;

            beginEndStmtList.Rule  = MakePlusRule(beginEndStmtList, stmt);
            beginEndStmt.Rule      = beginTryCatchStmt | BEGIN + beginEndStmtList + END;
            beginTryCatchStmt.Rule = BEGIN + TRY + beginEndStmtList + END + TRY + BEGIN + CATCH + beginEndStmtList + END + CATCH;
            beginTransStmt.Rule    = BEGIN + (TRAN | TRANSACTION) + (Empty | Id);
            commitTransStmt.Rule   = COMMIT + (TRAN | TRANSACTION) + (Empty | Id);
            rollbackTransStmt.Rule = ROLLBACK + (TRAN | TRANSACTION) + (Empty | Id);
            truncateStmt.Rule      = TRUNCATE + TABLE + Id;
            isNullOpt.Rule         = Empty | IS + NULL;

            funcallDelim.Rule = AND | OR;
            funCallList.Rule  = MakePlusRule(funCallList, funcallDelim, funCall);

            // If
            ifStmt.Rule      = IF + leftParenOpt + ifConditionChain + rightParenOpt;
            ifCondition.Rule = (notOpt + funCall + isNullOpt | NOT + leftParenOpt + expression + rightParenOpt)
                               | (Empty | "EXISTS") + "(" + (Id_simple + IS + NULL | settingListItem | selectWithUnion) + ")"
                               | "EXISTS" + "(" + selectWithUnion + ")"
                               | (Id_simple + IS + (Empty | NOT) + NULL | settingListItem)
                               | expression;
            ifConditionChain.Rule = MakePlusRule(ifConditionChain, AND | OR, ifCondition);
            elseStmt.Rule         = ELSE;

            createRoleStmt.Rule = CREATE + ROLE + Id;
            createViewStmt.Rule = CREATE + VIEW + Id + AS + leftParenOpt + selectWithUnion + rightParenOpt + unionAllListOpt;
            createTypeStmt.Rule = CREATE + TYPE + Id + FROM + Id
                                  | CREATE + TYPE + Id + AS + TABLE + "(" + fieldDefLists + ")";

            //Create procedure
            createProcedureStmt.Rule = CREATE + PROCEDURE + Id + "(" + variableDefLists + ")" + AS + BEGIN + stmtList + END;
            variableDefLists.Rule    = MakePlusRule(variableDefLists, variableDefList);
            variableDefList.Rule     = MakeListRule(variableDefList, comma, variableDef, TermListOptions.AllowTrailingDelimiter | TermListOptions.PlusList);
            variableDef.Rule         = Id + typeName + outputOpt;
            outputOpt.Rule           = Empty | OUTPUT;

            //Create table
            createTableStmt.Rule = CREATE + TABLE + Id + "(" + fieldDefLists + ")" + (onOpt | withClauseOpt) + textImageOnOpt;
            fieldDefList.Rule    = MakeListRule(fieldDefList, comma, fieldDef, TermListOptions.AllowTrailingDelimiter | TermListOptions.PlusList);
            fieldDef.Rule        = columnDef | constraintListOpt;
            columnDef.Rule       = Id + typeName + collateOpt + primaryKeyOpt + nullSpecOpt + referencesOpt + defaultValueOpt + withClauseOpt
                                   | Id + typeName + collateOpt + primaryKeyOpt + nullSpecOpt + constraintListOpt + withClauseOpt
                                   | Id + typeName + collateOpt + primaryKeyOpt + notForReplOpt + nullSpecOpt + defaultValueOpt + withClauseOpt
                                   | Id + typeName + collateOpt + primaryKeyOpt + notForReplOpt + nullSpecOpt + constraintListOpt + withClauseOpt
                                   | Id + typeName + equals + term
                                   | primaryKeyOpt + indexTypeOpt + idlistParOpt + withClauseOpt
                                   | term;
            referencesOpt.Rule      = Empty | "References" + Id + idlistParOpt;
            notForReplOpt.Rule      = Empty | (NOT + FOR + REPLICATION);
            nullSpecOpt.Rule        = Empty | (NOT + FOR + REPLICATION) | NULL | NOT + NULL | NOT + NULL + typeName | NULL + typeName;
            collateOpt.Rule         = Empty | COLLATE + Id_simple;
            identityOpt.Rule        = Empty | IDENTITY;
            typeNameParamsList.Rule = MakePlusRule(typeNameParamsList, comma, term);
            typeName.Rule           = Id_simple | Id_simple + "(" + typeNameParamsList + ")" | Id_simple + "(max)";
            constraintDef.Rule      = CONSTRAINT + Id + constraintTypeOpt + onListOpt;
            indexContraintDef.Rule  = constraintTypeOpt + onListOpt;
            constraintListOpt.Rule  = MakeStarRule(constraintListOpt, constraintDef);
            constraintTypeOpt.Rule  = Empty | defaultValueOpt + withClauseOpt
                                      | primaryKeyOpt + indexTypeList + idlistParOpt + withClauseOpt
                                      | CHECK + "(" + expression + ")" + withClauseOpt
                                      | NOT + NULL + idlistParOpt + withClauseOpt
                                      | "Foreign" + KEY + idlistParOpt + referencesOpt + notForReplOpt + withClauseOpt
                                      | "INCLUDE" + idlistParOpt + withClauseOpt + onOpt;
            idlistParOpt.Rule           = Empty | "(" + orderList + ")";
            idlist.Rule                 = MakePlusRule(idlist, comma, Id);
            idlistForSelect.Rule        = MakePlusRule(idlist, comma, IdWithAliasOpt);
            defaultValueParamsList.Rule = MakePlusRule(defaultValueParamsList, comma, term);
            defaultValueOpt.Rule        = Empty | (DEFAULT + defaultValueParams);
            defaultValueParams.Rule     = term | "(" + term + ")";

            //Create Index
            primaryKeyOpt.Rule   = Empty | PRIMARY + KEY | typeName;
            createIndexStmt.Rule = CREATE + indexTypeList + INDEX + Id + onOpt + "(" + orderList + ")" + constraintTypeOpt + whereClauseOpt + withClauseOpt + onOpt;
            orderList.Rule       = MakePlusRule(orderList, comma, orderMember);
            orderMember.Rule     = Id + orderDirOpt;
            orderDirOpt.Rule     = Empty | "ASC" | "DESC";
            indexTypeOpt.Rule    = Empty | UNIQUE | CLUSTERED | NONCLUSTERED;
            indexTypeList.Rule   = MakeStarRule(indexTypeList, indexTypeOpt);
            settingList.Rule     = MakePlusRule(settingList, comma, settingListItem);
            settingListItem.Rule = Id + equals + term;
            withClauseOpt.Rule   = Empty | (WITH + PRIMARY | WITH + "Disallow" + NULL | WITH + "Ignore" + NULL | WITH + "(" + settingList + ")" + onOpt + textImageOnOpt);
            cascadeOpt.Rule      = Empty | (ON + (UPDATE | DELETE) + CASCADE);
            cascadeListOpt.Rule  = MakePlusRule(cascadeListOpt, cascadeOpt);
            noLockOpt.Rule       = (Empty | WITH + leftParenOpt + "NOLOCK" + rightParenOpt);

            //Alter
            alterStmt.Rule = ALTER + (TABLE | DATABASE) + Id + setStmtOpt + alterCmdOpt
                             | alterProcedureStmt
                             | alterIndexStmt;
            alterCmdOpt.Rule = Empty | ADD + COLUMN + fieldDefList + constraintDef
                               | CHECK + CONSTRAINT + Id
                               | WITH + (CHECK | NOCHECK) + ADD + CONSTRAINT + Id + constraintTypeOpt + cascadeListOpt
                               | ADD + constraintDef + forOpt
                               | DROP + COLUMN + Id
                               | DROP + CONSTRAINT + Id;
            alterProcedureStmt.Rule = ALTER + PROCEDURE + Id + leftParenOpt + fieldDefLists + rightParenOpt + asOpt + beginEndStmt;
            alterIndexStmt.Rule     = ALTER + INDEX + Id + ON + Id + REBUILD + WITH + "(" + settingList + ")";

            //Drop stmts
            dropTableStmt.Rule     = DROP + TABLE + Id;
            dropIndexStmt.Rule     = DROP + INDEX + Id + ON + Id;
            dropViewStmt.Rule      = DROP + VIEW + Id;
            dropProcedureStmt.Rule = DROP + PROCEDURE + Id;

            //Insert stmt
            insertStmt.Rule = INSERT + (Empty | intoOpt + Id) + (idlistParOpt + insertData | execStmt);
            insertData.Rule = leftParenOpt + selectWithUnion + rightParenOpt | VALUES + "(" + exprList + ")";
            intoOpt.Rule    = Empty | INTO; //Into is optional in MSSQL

            //Update stmt
            updateStmt.Rule           = UPDATE + topOpt + (Empty | Id) + SET + assignList + fromClauseOpt + joinStmtOpt + whereClauseOpt + andClauseOpt;
            assignList.Rule           = MakePlusRule(assignList, comma, assignment);
            assignment.Rule           = Id + "=" + expression;
            updateStatisticsStmt.Rule = UPDATE + STATISTICS + Id;

            //Delete stmt
            deleteStmt.Rule = DELETE + (Empty | FROM) + Id + whereClauseOpt + andClauseOpt;

            //Select stmt
            selectCaseStmt.Rule    = CASE + caseWhenThenLists + ELSE + expression + END + (Empty | asOpt + Id);
            caseWhenThenLists.Rule = MakePlusRule(caseWhenThenLists, caseWhenThenList);
            caseWhenThenList.Rule  = WHEN + leftParenOpt + expression + rightParenOpt + THEN + term;
            variableDef.Rule       = Id + typeName + outputOpt;


            selectStmt.Rule = SELECT + topOpt + selRestrOpt + selList + intoClauseOpt + fromClauseOpt + forXmlStmtOpt + joinChainOptList + whereClauseOpt + andClauseOpt +
                              betweenClauseOpt + groupClauseOpt + havingClauseOpt + orderClauseOpt;
            selectWithUnion.Rule = MakePlusRule(selectWithUnion, UNION, selectStmt);
            mergeStmt.Rule       = MERGE + Id + AS + Id + USING + (Empty | Id) + leftParenOpt + (Empty | selectWithUnion) + rightParenOpt + AS + Id + ON + expression + mergeWhenMatched +
                                   mergeWhenNotMatched + mergeWhenNotMatched;
            mergeWhenMatched.Rule    = WHEN + MATCHED + andClauseOpt + THEN + stmt;
            mergeWhenNotMatched.Rule = Empty | WHEN + NOT + MATCHED + BY + Id + THEN + stmt;
            forXmlStmtOpt.Rule       = Empty | FOR + "XML" + forXmlFunCallList;
            forXmlFunCallList.Rule   = MakePlusRule(forXmlFunCallList, comma, funCall);

            topOpt.Rule           = Empty | TOP + leftParenOpt + (number | Id) + rightParenOpt;
            selRestrOpt.Rule      = Empty | "ALL" | "DISTINCT";
            selList.Rule          = columnItemList + semiOpt | "*";
            columnItemList.Rule   = MakePlusRule(columnItemList, comma, columnItem);
            columnItem.Rule       = columnSource;
            aliasOpt.Rule         = Empty | asOpt + Id;
            asOpt.Rule            = Empty | AS;
            columnSource.Rule     = Id + aliasOpt | Id + "=" + (selectCaseStmt | concatStringList | expression) | expression | expression + asOpt + (Empty | Id) | selectCaseStmt;
            aggregate.Rule        = aggregateName + "(" + aggregateArg + ")";
            aggregateArg.Rule     = expression | "*";
            aggregateName.Rule    = COUNT | "Avg" | "Min" | "Max" | "StDev" | "StDevP" | "Sum" | "Var" | "VarP";
            intoClauseOpt.Rule    = Empty | INTO + Id;
            fromClauseOpt.Rule    = Empty | FROM + leftParenOpt + (selectStmt | funCall | idlistForSelect) + rightParenOpt + (Empty | AS + Id) + noLockOpt;
            joinStmtOpt.Rule      = Empty | JOIN + Id + asOpt + Id + noLockOpt + ON + expression;
            joinChainOpt.Rule     = Empty | joinKindOpt + hashOpt + joinStmtOpt;
            joinChainOptList.Rule = MakeStarRule(joinChainOptList, joinChainOpt);
            joinKindOpt.Rule      = Empty | "INNER" | "OUTER" | "LEFT" | "RIGHT";
            hashOpt.Rule          = Empty | HASH;
            whereClauseOpt.Rule   = Empty | "WHERE" + expression;
            andClauseOpt.Rule     = Empty | "AND" + expression;
            betweenClauseOpt.Rule = Empty | "BETWEEN" + expression;
            groupClauseOpt.Rule   = Empty | "GROUP" + BY + idOrExpressionList;
            havingClauseOpt.Rule  = Empty | "HAVING" + expression;
            orderClauseOpt.Rule   = Empty | "ORDER" + BY + orderList;

            //Expression
            exprList.Rule   = MakePlusRule(exprList, comma, expression);
            expression.Rule = term | unExpr | binExpr | betweenExpr;                                 //-- BETWEEN doesn't work - yet; brings a few parsing conflicts
            term.Rule       = Id | IdAsType | string_literal | number | funCall | tuple | aggregate; // | inStmt;
            tuple.Rule      = "(" + exprList + ")";
            unExpr.Rule     = unOp + term;
            unOp.Rule       = NOT | "+" | "-" | "~";
            binExpr.Rule    = expression + binOp + expression;
            binOp.Rule      = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic
                              | "&" | "|" | "^"                   //bit
                              | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>"
                              | "AND" | "OR" | "LIKE" | NOT + "LIKE" | IS | "IN" | NOT + "IN";
            betweenExpr.Rule = expression + notOpt + "BETWEEN" + expression + "AND" + expression;
            notOpt.Rule      = Empty | NOT;

            //funCall covers some psedo-operators and special forms like ANY(...), SOME(...), ALL(...), EXISTS(...), IN(...)
            funCall.Rule     = Id + "(" + funArgsList + ")" + (Empty | AS + typeName);
            funArgsOpt.Rule  = Empty | selectStmt | expression | string_literal | Id + "=" + term;
            funArgsList.Rule = MakePlusRule(funArgsList, comma, funArgsOpt);
            inStmt.Rule      = expression + "IN" + "(" + exprList + ")";

            //Operators
            RegisterOperators(10, "*", "/", "%");
            RegisterOperators(9, "+", "-");
            RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>", "LIKE", "IN");
            RegisterOperators(7, "^", "&", "|");
            RegisterOperators(6, NOT);
            RegisterOperators(5, "AND");
            RegisterOperators(4, "OR");

            MarkPunctuation(",", "(", ")");
            MarkPunctuation(asOpt, semiOpt);
            //Note: we cannot declare binOp as transient because it includes operators "NOT LIKE", "NOT IN" consisting of two tokens.
            // Transient non-terminals cannot have more than one non-punctuation child nodes.
            // Instead, we set flag InheritPrecedence on binOp , so that it inherits precedence value from it's children, and this precedence is used
            // in conflict resolution when binOp node is sitting on the stack
            base.MarkTransient(stmt, term, asOpt, aliasOpt, stmtLine, expression, unOp, tuple);
            binOp.SetFlag(TermFlags.InheritPrecedence);
        } //constructor
Esempio n. 10
0
        public Gramatica() : base(caseSensitive: true)
        {
            //------------------------------------------------------------------------Expresiones Regulares-----------------------------------------------
            #region ER
            NumberLiteral      numero = TerminalFactory.CreateCSharpNumber("numero");
            IdentifierTerminal id     = TerminalFactory.CreateCSharpIdentifier("id");
            #endregion

            //--------------------------------------------------------------------------Palabras Reservadas-----------------------------------------------------------
            #region PalabrasReservadas
            MarkReservedWords("imprimir");
            MarkReservedWords("raiz");
            MarkReservedWords("graficar");
            MarkReservedWords("programa");
            MarkReservedWords("var");
            MarkReservedWords("double");
            MarkReservedWords("string");
            MarkReservedWords("int");
            MarkReservedWords("bool");
            MarkReservedWords("OR");
            MarkReservedWords("AND");
            MarkReservedWords("NOT");
            MarkReservedWords("retornar");
            MarkReservedWords("void");
            MarkReservedWords("principal");
            MarkReservedWords("SI");
            MarkReservedWords("SINO_SI");
            MarkReservedWords("SINO");
            MarkReservedWords("INTERRUMPIR");
            MarkReservedWords("CASO");
            MarkReservedWords("DEFECTO");
            MarkReservedWords("MIENTRAS");
            MarkReservedWords("HACER");
            MarkReservedWords("salir");
            #endregion



            #region Terminales
            var mas      = ToTerm("+");
            var menos    = ToTerm("-");
            var por      = ToTerm("*");
            var division = ToTerm("/");
            var potencia = ToTerm("^");

            var parentesis  = ToTerm("(");
            var imprimir    = ToTerm("imprimir");
            var raiz        = ToTerm("raiz");
            var graficar    = ToTerm("graficar");
            var programa    = ToTerm("programa");
            var variable    = ToTerm("var");
            var vadouble    = ToTerm("double");
            var vastring    = ToTerm("string");
            var varint      = ToTerm("int");
            var vabool      = ToTerm("bool");
            var or          = ToTerm("OR");
            var and         = ToTerm("AND");
            var retornar    = ToTerm("retornar");
            var tvoid       = ToTerm("void");
            var principal   = ToTerm("principal");
            var si          = ToTerm("SI");
            var sinosi      = ToTerm("SINO_SI");
            var sino        = ToTerm("SINO");
            var interruptor = ToTerm("INTERRUMPIR");
            var caso        = ToTerm("CASO");
            var defecto     = ToTerm("DEFECTO");
            var mientras    = ToTerm("MIENTRAS");
            var hacer       = ToTerm("HACER");
            var salir       = ToTerm("salir");

            var tString = new StringLiteral("tString", "\"", StringOptions.AllowsDoubledQuote);
            var tchar   = new StringLiteral("tchar", "\'", StringOptions.AllowsDoubledQuote);

            var mayor      = ToTerm(">");
            var menor      = ToTerm("<");
            var mayorigual = ToTerm(">=");
            var menorigual = ToTerm("<=");
            var igualigual = ToTerm("==");
            var diferente  = ToTerm("!=");

            var asignacion = ToTerm("::=");
            var puntocoma  = ToTerm(";");

            var opencorch  = ToTerm("[");
            var closecorch = ToTerm("]");
            var openpare   = ToTerm("(");
            var closepare  = ToTerm(")");
            var coma       = ToTerm(",");

            var trues    = ToTerm("true");
            var falses   = ToTerm("false");
            var negacion = ToTerm("!");
            #endregion


            #region Noterminales
            var INICIO       = new NonTerminal("INICIO");
            var CUERPO       = new NonTerminal("CUERPO");
            var ESTRUCTURA   = new NonTerminal("ESTRUCTURA");
            var CUERPO2      = new NonTerminal("CUERPO2");
            var ESTRUCTURA2  = new NonTerminal("ESTRUCTURA2");
            var IMPRIMIR     = new NonTerminal("IMPRIMIR");
            var EXPRESION    = new NonTerminal("EXPRESION");
            var LLAMADAFUNC  = new NonTerminal("LLAMADAFUNC");
            var RAIZZ        = new NonTerminal("RAIZ");
            var GRAFICAR     = new NonTerminal("GRAFICAR");
            var DECLARACION  = new NonTerminal("DECLARACION");
            var DECLARACION2 = new NonTerminal("DECLARACION2");
            var MULTIVAR     = new NonTerminal("MULTIVAR");
            var ASIGNACION   = new NonTerminal("ASIGNACION");
            var DECLASIGNA   = new NonTerminal("DECLAASIGNA");
            var DECLASIGNA2  = new NonTerminal("DECLAASIGNA2");
            var METOFUNC     = new NonTerminal("METOFUNC");
            var TIPO         = new NonTerminal("TIPO");
            var CUERPOME     = new NonTerminal("CUERPOME");
            var ESTRUCTURAME = new NonTerminal("ESTRUCTURAME");
            var RETORNAR     = new NonTerminal("RETORNAR");
            var PARAMETROS   = new NonTerminal("PARAMETROS");
            var MVOID        = new NonTerminal("MVOID");
            var PRINCIPAL    = new NonTerminal("PRINCIPAL");
            var CIF          = new NonTerminal("CIF");
            var CONDICION    = new NonTerminal("CONDICION");
            var SINOSI       = new NonTerminal("SINOSI");
            var SINO         = new NonTerminal("SINO");
            var CINTERRUMPIR = new NonTerminal("CINTERRUMPIR");
            var CASO         = new NonTerminal("CASO");
            var DEFECTO      = new NonTerminal("DEFECTO");
            var CMIENTRAS    = new NonTerminal("CMIENTRAS");
            var CHACER       = new NonTerminal("CHACER");
            var SALIR        = new NonTerminal("SALIR");
            var DECLAPARA    = new NonTerminal("DECLAPARA");
            var PARALLAMA    = new NonTerminal("PARALLAMA");
            #endregion

            //---------------------------------------------------------------------PRODUCCIONES-----------------------------------------------------------
            #region producciones
            this.Root = INICIO;

            INICIO.Rule = programa + id + opencorch + CUERPO2 + closecorch;

            CUERPO2.Rule = MakeStarRule(CUERPO2, ESTRUCTURA2);


            ESTRUCTURA2.Rule = DECLARACION2
                               | DECLASIGNA2
                               | METOFUNC
                               | MVOID
                               | PRINCIPAL;


            CUERPO.Rule = MakeStarRule(CUERPO, ESTRUCTURA);

            ESTRUCTURA.Rule = IMPRIMIR
                              | GRAFICAR
                              | DECLARACION
                              | ASIGNACION
                              | DECLASIGNA
                              | LLAMADAFUNC
                              | CIF
                              | CINTERRUMPIR
                              | CMIENTRAS
                              | CHACER
                              | RETORNAR;

            CUERPOME.Rule = MakeStarRule(CUERPOME, ESTRUCTURAME);

            ESTRUCTURAME.Rule = IMPRIMIR
                                | GRAFICAR
                                | DECLARACION
                                | ASIGNACION
                                | DECLASIGNA
                                | LLAMADAFUNC
                                | CIF
                                | CINTERRUMPIR
                                | CMIENTRAS
                                | CHACER
                                | RETORNAR
                                | SALIR;
            //----------------------------------------------------------------IMPRIMIR-----------------------------------------------

            IMPRIMIR.Rule = imprimir + openpare + EXPRESION + closepare + puntocoma;

            //--------------------------------------------------------------RAIZ CUADRADA------------------------------------------------------
            RAIZZ.Rule = raiz + openpare + EXPRESION + coma + EXPRESION + closepare;

            //-----------------------------------------------------------------GRAFICAR-----------------------------------------------------------

            GRAFICAR.Rule = graficar + openpare + "\"x\"" + coma + EXPRESION + coma + numero + coma + numero + coma + tString + closepare + puntocoma
                            | graficar + openpare + "\"y\"" + coma + EXPRESION + coma + numero + coma + numero + coma + tString + closepare + puntocoma;

            //-----------------------------------------------------------------DECLARACION DE VARIABLES------------------------------------------------
            DECLARACION.Rule  = variable + MULTIVAR + puntocoma;
            DECLARACION2.Rule = variable + MULTIVAR + puntocoma;
            MULTIVAR.Rule     = id + coma + MULTIVAR | id;
            //-----------------------------------------------------------------ASIGNACION DE VARIABLES----------------------------------------------
            ASIGNACION.Rule = id + asignacion + EXPRESION + puntocoma;
            //------------------------------------------------------------------ASIGNACION Y DECLARACION-----------------------------------------------
            DECLASIGNA.Rule  = variable + MULTIVAR + asignacion + EXPRESION + puntocoma;
            DECLASIGNA2.Rule = variable + MULTIVAR + asignacion + EXPRESION + puntocoma;
            //-------------------------------------------------------------------------FUNCIONES------------------------------------------------------
            METOFUNC.Rule   = TIPO + id + openpare + DECLAPARA + closepare + opencorch + CUERPOME + closecorch;
            TIPO.Rule       = varint | vastring | vadouble;
            PARAMETROS.Rule = EXPRESION
                              | EXPRESION + coma + PARAMETROS
                              | Empty;
            DECLAPARA.Rule = variable + id + coma + DECLAPARA
                             | variable + id
                             | Empty;
            //-----------------------------------------------------------------------METODO VOID-------------------------------------------------------
            MVOID.Rule = tvoid + id + openpare + DECLAPARA + closepare + opencorch + CUERPO + closecorch;


            //----------------------------------------------------------------RETORNAR------------------------------------------------------
            RETORNAR.Rule = retornar + EXPRESION + puntocoma;
            //-------------------------------------------------------------------LLAMADA A FUNCION-------------------------------------------
            LLAMADAFUNC.Rule = id + openpare + PARAMETROS + closepare + puntocoma;
            PARALLAMA.Rule   = id + openpare + PARAMETROS + closepare;
            //-------------------------------------------------------------------METODO PRINCIPAL-----------------------------------------------
            PRINCIPAL.Rule = principal + openpare + closepare + opencorch + CUERPO + closecorch;

            //--------------------------------------------------------------------CONTROL IF--------------------------------------------------------
            CIF.Rule = si + openpare + EXPRESION + closepare + opencorch + CUERPO + closecorch + SINOSI + SINO;

            //--------------------------------------------------------------ELSE IF----------------------------------------------------------------
            SINOSI.Rule = sinosi + openpare + EXPRESION + closepare + opencorch + CUERPO + closecorch + SINOSI | Empty;
            //-----------------------------------------------------------------ELSE-------------------------------------------------------------------
            SINO.Rule = sino + opencorch + CUERPO + closecorch | Empty;

            //------------------------------------------------------------------CONTROL SWITCH----------------------------------------------------------
            CINTERRUMPIR.Rule = interruptor + openpare + EXPRESION + closepare + opencorch + CASO + DEFECTO + closecorch;

            //------------------------------------------------------------------- CASE-----------------------------------------------------------------
            CASO.Rule = caso + numero + ":" + CUERPO + CASO
                        | caso + id + ":" + CUERPO + CASO
                        | Empty;

            //-------------------------------------------------------------------------DEFAULT------------------------------------------------------------
            DEFECTO.Rule = defecto + ":" + CUERPO
                           | Empty;

            //----------------------------------------------------------------------------WHILE-----------------------------------------------------------------
            CMIENTRAS.Rule = mientras + openpare + EXPRESION + closepare + opencorch + CUERPOME + closecorch;

            //-----------------------------------------------------------------------DO WHILE-------------------------------------------------------------------
            CHACER.Rule = hacer + opencorch + CUERPOME + closecorch + mientras + openpare + EXPRESION + closepare + puntocoma;

            //-----------------------------------------------------------------------BREAK----------------------------------------------------------------
            SALIR.Rule = salir + puntocoma;

            //-----------------------------------------------------------------------EXPRESION-----------------------------------------------------------------
            EXPRESION.Rule = EXPRESION + or + EXPRESION
                             | EXPRESION + and + EXPRESION
                             | EXPRESION + igualigual + EXPRESION
                             | EXPRESION + diferente + EXPRESION
                             | EXPRESION + mayor + EXPRESION
                             | EXPRESION + menor + EXPRESION
                             | EXPRESION + mayorigual + EXPRESION
                             | EXPRESION + menorigual + EXPRESION
                             | EXPRESION + mas + EXPRESION
                             | EXPRESION + menos + EXPRESION
                             | EXPRESION + por + EXPRESION
                             | EXPRESION + potencia + EXPRESION
                             | EXPRESION + division + EXPRESION
                             | openpare + EXPRESION + closepare
                             | negacion + EXPRESION
                             | id
                             | numero
                             | tString
                             | tchar
                             | trues
                             | falses
                             | RAIZZ
                             | PARALLAMA;
            #endregion

            #region comentarios
            //---------------------> Comentarios
            CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "//", "\n", "\r\n");
            CommentTerminal COMENTARIO_MULT   = new CommentTerminal("comentario_mult", "/*", "*/");
            NonGrammarTerminals.Add(COMENTARIO_SIMPLE);
            NonGrammarTerminals.Add(COMENTARIO_MULT);
            #endregion

            //---------------------> Definir Asociatividad
            RegisterOperators(1, Associativity.Left, "||");                 //OR
            RegisterOperators(2, Associativity.Left, "&&");                 //AND
            RegisterOperators(3, Associativity.Left, "==", "!=");           //IGUAL, DIFERENTE
            RegisterOperators(4, Associativity.Left, ">", "<", ">=", "<="); //MAYORQUES, MENORQUES
            RegisterOperators(5, Associativity.Left, "+", "-");             //MAS, MENOS
            RegisterOperators(6, Associativity.Left, "*", "/");             //POR, DIVIDIR
            RegisterOperators(6, Associativity.Left, "^");                  //POTENCIA
            RegisterOperators(7, Associativity.Right, "!");                 //NOT

            //---------------------------------------------------MANEJO DE ERRORES-------------------------------------------------------------------
            ESTRUCTURA.ErrorRule   = SyntaxError + ESTRUCTURA;
            ESTRUCTURA2.ErrorRule  = SyntaxError + ESTRUCTURA2;
            ESTRUCTURAME.ErrorRule = SyntaxError + ESTRUCTURAME;
        }
Esempio n. 11
0
        public Gramatica1() : base(caseSensitive: false)
        {
            #region ER
            IdentifierTerminal tokId    = new IdentifierTerminal("tokId", "_", "");
            var             tokNumero   = TerminalFactory.CreateCSharpNumber("tokNumero");
            StringLiteral   tokCadena   = new StringLiteral("tokenCadena", "\"");
            StringLiteral   tokChar     = new StringLiteral("tokenCaracter", "\'");
            CommentTerminal comentLinea = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            CommentTerminal comentMulti = new CommentTerminal("DelimitedComment", "/*", "*/");
            NonGrammarTerminals.Add(comentLinea);
            NonGrammarTerminals.Add(comentMulti);
            #endregion

            #region RESERVADAS
            MarkReservedWords("configuration");
            MarkReservedWords("background");
            MarkReservedWords("figure");
            MarkReservedWords("design");
            MarkReservedWords("x-nombre");
            MarkReservedWords("x-imagen");
            MarkReservedWords("x-tipo");
            MarkReservedWords("x-vida");
            MarkReservedWords("x-heroe");
            MarkReservedWords("x-enemigo");
            MarkReservedWords("x-destruir");
            MarkReservedWords("x-descripcion");
            MarkReservedWords("x-bomba");
            MarkReservedWords("x-arma");
            MarkReservedWords("x-creditos");
            MarkReservedWords("x-meta");
            MarkReservedWords("x-bloque");
            MarkReservedWords("x-bonus");
            MarkReservedWords("x-arma");
            MarkReservedWords("x-bomba");
            #endregion

            #region TERMINALES
            var tokConfig      = ToTerm("configuration");
            var tokBackground  = ToTerm("background");
            var tokFigure      = ToTerm("figure");
            var tokDesign      = ToTerm("design");
            var tokNombre      = ToTerm("x-nombre");
            var tokImagen      = ToTerm("x-imagen");
            var tokTipo        = ToTerm("x-tipo");
            var tokVida        = ToTerm("x-vida");
            var tokHero        = ToTerm("x-heroe");
            var tokEnemy       = ToTerm("x-enemigo");
            var tokDestruir    = ToTerm("x-destruir");
            var tokDescripcion = ToTerm("x-descripcion");
            var tokBomba       = ToTerm("x-bomba");
            var tokArma        = ToTerm("x-arma");
            var tokCreditos    = ToTerm("x-creditos");
            var tokMeta        = ToTerm("x-meta");
            var tokBloque      = ToTerm("x-bloque");
            var tokBonus       = ToTerm("x-bonus");
            var tokDiv         = ToTerm("/");
            var tokAllave      = ToTerm("{");
            var tokCllave      = ToTerm("}");
            var tokComa        = ToTerm(",");
            var tokPcoma       = ToTerm(";");
            var tokIgual       = ToTerm("=");
            var tokMas         = ToTerm("+");
            var tokMenos       = ToTerm("-");
            var tokPor         = ToTerm("*");
            var tokApar        = ToTerm("(");
            var tokCpar        = ToTerm(")");
            var tokAconf       = ToTerm("<configuration>");
            var tokCconf       = ToTerm("</configuration>");
            var tokAbackground = ToTerm("<background>");
            var tokCbackground = ToTerm("</background>");
            var tokAfigure     = ToTerm("<figure>");
            var tokCfigure     = ToTerm("</figure>");
            var tokAdesign     = ToTerm("<design>");
            var tokCdesign     = ToTerm("</design>");


            #endregion

            #region NO TERMINALES
            var START            = new NonTerminal("START");
            var BODIES           = new NonTerminal("BODIES");
            var BODY             = new NonTerminal("BODY");
            var LABELBACKGROUND  = new NonTerminal("LABELBACKGROUND");
            var BACKGROUNDS      = new NonTerminal("BACKGROUNDS");
            var BACKGROUND       = new NonTerminal("BACKGROUND");
            var BODIESBACKGROUND = new NonTerminal("BODIESBACKGROUND");
            var BODYBACKGROUND   = new NonTerminal("BODYBACKGROUND");
            var LABELFIGURE      = new NonTerminal("LABELFIGURE");
            var FIGURES          = new NonTerminal("FIGURES");
            var FIGURE           = new NonTerminal("FIGURE");
            var FIGUREBODIES     = new NonTerminal("FIGUREBODIES");
            var FIGUREBODY       = new NonTerminal("FIGUREBODY");
            var LABELDESIGN      = new NonTerminal("LABELDESIGN");
            var FIGURETYPE       = new NonTerminal("FIGURETYPE");
            var FTYPE            = new NonTerminal("FTYPE");
            var NAME             = new NonTerminal("NAME");
            var SOURCE           = new NonTerminal("SOURCE");
            var DESCRIPTION      = new NonTerminal("DESCRIPTION");
            var LIFE             = new NonTerminal("LIFE");
            var DESTRUCTION      = new NonTerminal("DESTRUCTION");
            var HERO             = new NonTerminal("HERO");
            var HEROBODIES       = new NonTerminal("HEROBODIES");
            var HEROBODY         = new NonTerminal("HEROBODY");
            var HEROTYPE         = new NonTerminal("HEROTYPE");
            var ENEMY            = new NonTerminal("ENEMY");
            var ENEMYBODIES      = new NonTerminal("ENEMYBODIES");
            var ENEMYBODY        = new NonTerminal("ENEMYBODY");
            var ENEMYTYPE        = new NonTerminal("ENEMYTYPE");
            var DESIGN           = new NonTerminal("DESIGN");
            var DESIGNS          = new NonTerminal("DESIGNS");
            var DESIGNBODIES     = new NonTerminal("DESIGNBODIES");
            var DESIGNBODY       = new NonTerminal("DESIGNBODY");
            var DESIGNTYPE       = new NonTerminal("DESIGNTYPE");
            var DTYPE            = new NonTerminal("DTYPE");
            var FINISH           = new NonTerminal("FINISH");
            var FINISHTYPE       = new NonTerminal("FINISHTYPE");
            var BLOCK            = new NonTerminal("BLOCK");
            var BLOCKTYPE        = new NonTerminal("BLOCKTYPE");
            var BONUS            = new NonTerminal("BONUS");
            var BONUSTYPE        = new NonTerminal("BONUSTYPE");
            var POINTS           = new NonTerminal("POINTS");
            var WEAPON           = new NonTerminal("WEAPON");
            var WEAPONTYPE       = new NonTerminal("WEAPONTYPE");
            var WTYPE            = new NonTerminal("TYPE");
            var EXP = new NonTerminal("EXP");



            #endregion

            #region GRAMATICA

            START.Rule = tokAconf + BODIES + tokCconf
            ;

            BODIES.Rule = MakePlusRule(BODIES, BODY)
            ;

            BODY.Rule = LABELBACKGROUND
                        | LABELFIGURE
                        | LABELDESIGN
            ;
            BODY.ErrorRule = SyntaxError + ">";

            LABELBACKGROUND.Rule = tokAbackground + BACKGROUNDS + tokCbackground
            ;

            LABELFIGURE.Rule = tokAfigure + FIGURES + tokCfigure
            ;

            LABELDESIGN.Rule = tokAdesign + DESIGNS + tokCdesign
            ;

            BACKGROUNDS.Rule = MakePlusRule(BACKGROUNDS, tokComa, BACKGROUND)
            ;

            BACKGROUND.Rule = tokAllave + BODIESBACKGROUND + tokCllave
            ;
            BACKGROUND.ErrorRule = SyntaxError + "}";

            BODIESBACKGROUND.Rule = MakeStarRule(BODIESBACKGROUND, BODYBACKGROUND)
            ;

            BODYBACKGROUND.Rule = NAME
                                  | SOURCE
            ;

            NAME.Rule = tokNombre + tokIgual + tokId + tokPcoma
            ;
            //NAME.ErrorRule = SyntaxError + ";";

            SOURCE.Rule = tokImagen + tokIgual + tokCadena + tokPcoma
            ;
            //SOURCE.ErrorRule = SyntaxError + ";";

            DESCRIPTION.Rule = tokDescripcion + tokIgual + tokCadena + tokPcoma
            ;
            //DESCRIPTION.ErrorRule = SyntaxError + ";";

            LIFE.Rule = tokVida + tokIgual + EXP + tokPcoma
            ;
            //LIFE.ErrorRule = SyntaxError + ";";

            DESTRUCTION.Rule = tokDestruir + tokIgual + EXP + tokPcoma
            ;
            //DESTRUCTION.ErrorRule = SyntaxError + ";";


            FIGURES.Rule = MakePlusRule(FIGURES, tokComa, FIGURE)
            ;

            FIGURE.Rule = tokAllave + FIGUREBODIES + tokCllave
            ;
            FIGURE.ErrorRule = SyntaxError + "}";

            FIGUREBODIES.Rule = MakePlusRule(FIGUREBODIES, FIGUREBODY)
            ;

            FIGUREBODY.Rule = NAME
                              | SOURCE
                              | LIFE
                              | DESCRIPTION
                              | DESTRUCTION
                              | FIGURETYPE
            ;

            FIGURETYPE.Rule = tokTipo + tokIgual + FTYPE + tokPcoma
            ;
            FIGURETYPE.ErrorRule = SyntaxError + ";";

            FTYPE.Rule = tokHero
                         | tokEnemy
            ;

            EXP.Rule = EXP + tokMas + EXP
                       | EXP + tokMenos + EXP
                       | EXP + tokPor + EXP
                       | EXP + "/" + EXP
                       | tokNumero
                       | tokApar + EXP + tokCpar
                       | tokMenos + EXP
            ;

            DESIGNS.Rule = MakePlusRule(DESIGNS, tokComa, DESIGN)
            ;

            DESIGN.Rule = tokAllave + DESIGNBODIES + tokCllave
            ;
            DESIGN.ErrorRule = SyntaxError + "}";

            DESIGNBODIES.Rule = MakePlusRule(DESIGNBODIES, DESIGNBODY)
            ;

            DESIGNBODY.Rule = NAME
                              | SOURCE
                              | POINTS
                              | DESTRUCTION
                              | DESIGNTYPE
            ;

            POINTS.Rule = tokCreditos + tokIgual + EXP + tokPcoma
            ;
            POINTS.ErrorRule = SyntaxError + ";";

            DESIGNTYPE.Rule = tokTipo + tokIgual + DTYPE + tokPcoma
            ;
            DESIGNTYPE.ErrorRule = SyntaxError + ";";

            DTYPE.Rule = tokMeta
                         | tokBloque
                         | tokBonus
                         | tokBomba
                         | tokArma
            ;

            RegisterOperators(1, Associativity.Left, tokMas, tokMenos);
            RegisterOperators(2, Associativity.Left, tokPor, tokDiv);
            RegisterOperators(3, "-()");
            RegisterOperators(4, tokApar + tokCpar);

            this.MarkPunctuation(";", "{", "}", "(", ")", tokAconf.Text, tokAfigure.Text, tokAbackground.Text, tokAdesign.Text, tokCconf.Text, tokCfigure.Text, tokCbackground.Text, tokCdesign.Text);
            this.MarkTransient(BACKGROUND, BODYBACKGROUND, FIGUREBODY, DESIGNBODY, FTYPE, DTYPE, BODY, FIGURE, DESIGN, LABELBACKGROUND, LABELDESIGN, LABELFIGURE);

            this.Root = START;
            #endregion
        }
Esempio n. 12
0
        public void TestNumber_CSharp()
        {
            Parser parser; Token token;

            double eps = 0.0001;

            parser = TestHelper.CreateParser(TerminalFactory.CreateCSharpNumber("Number"));

            //Simple integers and suffixes
            token = parser.ParseInput("123 ");
            CheckType(token, typeof(int));
            Assert.True(token.Details != null, "ScanDetails object not found in token.");
            Assert.True((int)token.Value == 123, "Failed to read int value");

            token = parser.ParseInput(Int32.MaxValue.ToString());
            CheckType(token, typeof(int));
            Assert.True((int)token.Value == Int32.MaxValue, "Failed to read Int32.MaxValue.");

            token = parser.ParseInput(UInt64.MaxValue.ToString());
            CheckType(token, typeof(ulong));
            Assert.True((ulong)token.Value == UInt64.MaxValue, "Failed to read uint64.MaxValue value");

            token = parser.ParseInput("123U ");
            CheckType(token, typeof(UInt32));
            Assert.True((UInt32)token.Value == 123, "Failed to read uint value");

            token = parser.ParseInput("123L ");
            CheckType(token, typeof(long));
            Assert.True((long)token.Value == 123, "Failed to read long value");

            token = parser.ParseInput("123uL ");
            CheckType(token, typeof(ulong));
            Assert.True((ulong)token.Value == 123, "Failed to read ulong value");

            //Hex representation
            token = parser.ParseInput("0x012 ");
            CheckType(token, typeof(Int32));
            Assert.True((Int32)token.Value == 0x012, "Failed to read hex int value");

            token = parser.ParseInput("0x12U ");
            CheckType(token, typeof(UInt32));
            Assert.True((UInt32)token.Value == 0x012, "Failed to read hex uint value");

            token = parser.ParseInput("0x012L ");
            CheckType(token, typeof(long));
            Assert.True((long)token.Value == 0x012, "Failed to read hex long value");

            token = parser.ParseInput("0x012uL ");
            CheckType(token, typeof(ulong));
            Assert.True((ulong)token.Value == 0x012, "Failed to read hex ulong value");

            //Floating point types
            token = parser.ParseInput("123.4 ");
            CheckType(token, typeof(double));
            Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value #1");

            token = parser.ParseInput("1234e-1 ");
            CheckType(token, typeof(double));
            Assert.True(Math.Abs((double)token.Value - 1234e-1) < eps, "Failed to read double value #2");

            token = parser.ParseInput("12.34e+01 ");
            CheckType(token, typeof(double));
            Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value  #3");

            token = parser.ParseInput("0.1234E3 ");
            CheckType(token, typeof(double));
            Assert.True(Math.Abs((double)token.Value - 123.4) < eps, "Failed to read double value  #4");

            token = parser.ParseInput("123.4f ");
            CheckType(token, typeof(float));
            Assert.True(Math.Abs((Single)token.Value - 123.4) < eps, "Failed to read float(single) value");

            token = parser.ParseInput("123.4m ");
            CheckType(token, typeof(decimal));
            Assert.True(Math.Abs((decimal)token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value");

            token = parser.ParseInput("123. ", useTerminator: false); //should ignore dot and read number as int. compare it to python numbers - see below
            CheckType(token, typeof(int));
            Assert.True((int)token.Value == 123, "Failed to read int value with trailing dot");

            //Quick parse
            token = parser.ParseInput("1 ");
            CheckType(token, typeof(int));
            //When going through quick parse path (for one-digit numbers), the NumberScanInfo record is not created and hence is absent in Attributes
            Assert.True(token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should not produce this object.");
            Assert.True((int)token.Value == 1, "Failed to read quick-parse value");
        }
Esempio n. 13
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
        }
Esempio n. 14
0
        public GrammarP1() : base(caseSensitive: true)
        {
            /*************** Comentarios ***************/
            //No hay :D


            /*************** Reservados ***************/
            MarkReservedWords("CONJ");
            MarkReservedWords("RESERV");
            MarkReservedWords("retorno");
            MarkReservedWords("yytext");
            MarkReservedWords("yyline");
            MarkReservedWords("yyrow");
            MarkReservedWords("error");
            MarkReservedWords("int");
            MarkReservedWords("float");
            MarkReservedWords("string");
            MarkReservedWords("char");
            MarkReservedWords("bool");

            var conj    = ToTerm("CONJ");
            var reserv  = ToTerm("RESERV");
            var retorno = ToTerm("retorno");
            var yytext  = ToTerm("yytext");
            var yyline  = ToTerm("yyline");
            var yyrow   = ToTerm("yyrow");
            var rerror  = ToTerm("error");
            var rint    = ToTerm("int");
            var rfloat  = ToTerm("float");
            var rstring = ToTerm("string");
            var rchar   = ToTerm("char");
            var rbool   = ToTerm("bool");

            var flecha      = ToTerm("->");
            var fin         = ToTerm(";");
            var dosp        = ToTerm(":");
            var coma        = ToTerm(",");
            var apar        = ToTerm("(");
            var cpar        = ToTerm(")");
            var acor        = ToTerm("[");
            var ccor        = ToTerm("]");
            var and         = ToTerm(".");
            var or          = ToTerm("|");
            var muchos      = ToTerm("+");
            var nada_muchos = ToTerm("*");
            var nada        = ToTerm("?");

            //var barra = ToTerm("\\");
            var salto         = ToTerm("\\n");
            var retorno_carro = ToTerm("\\r");
            var tab           = ToTerm("\\t");
            var comillas_s    = ToTerm("\\'");
            var comillas_d    = ToTerm("\\\"");
            var blanco        = ToTerm("[:blanco:]");
            var todo          = ToTerm("[:todo:]");


            /*************** No Terminales ***************/
            var INICIO     = new NonTerminal("INICIO", typeof(AstNode));
            var CUERPO     = new NonTerminal("CUERPO", typeof(AstNode));
            var CODIGO     = new NonTerminal("CODIGO", typeof(AstNode));
            var SENTENCIA  = new NonTerminal("SENTENCIA", typeof(AstNode));
            var CONJUNTO   = new NonTerminal("CONJUNTO", typeof(AstNode));
            var SERIE      = new NonTerminal("SERIE", typeof(AstNode));
            var SERIE2     = new NonTerminal("SERIE2", typeof(AstNode));
            var LISTA      = new NonTerminal("LISTA", typeof(AstNode));
            var SIMBOLO    = new NonTerminal("SIMBOLO", typeof(AstNode));
            var REGLA      = new NonTerminal("REGLA", typeof(AstNode));
            var METODO     = new NonTerminal("METODO", typeof(AstNode));
            var ER         = new NonTerminal("ER", typeof(AstNode));
            var ESCAPE     = new NonTerminal("ESCAPE", typeof(AstNode));
            var M1         = new NonTerminal("M1", typeof(AstNode));
            var M2         = new NonTerminal("M2", typeof(AstNode));
            var TIPO       = new NonTerminal("TIPO", typeof(AstNode));
            var RERROR     = new NonTerminal("ERROR", typeof(AstNode));
            var RESERVAR   = new NonTerminal("RESERVAR", typeof(AstNode));
            var RESERVADAS = new NonTerminal("RESERVADAS", typeof(AstNode));
            var RESERVADA  = new NonTerminal("RESERVADA", typeof(AstNode));


            /*************** Terminales ***************/
            NumberLiteral      numero = TerminalFactory.CreateCSharpNumber("numero");
            IdentifierTerminal id     = TerminalFactory.CreateCSharpIdentifier("id");
            var tstring = new StringLiteral("tstring", "\"", StringOptions.AllowsDoubledQuote);
            var tchar   = new StringLiteral("tchar", "'", StringOptions.AllowsDoubledQuote);
            RegexBasedTerminal ascii = new RegexBasedTerminal("ascii", "[^\008\009\010\011\013\020\024\032\034\039\092\096\0239\0249]");

            //AstNode
            numero.AstConfig.NodeType  = typeof(AstNode);
            id.AstConfig.NodeType      = typeof(AstNode);
            tstring.AstConfig.NodeType = typeof(AstNode);
            tchar.AstConfig.NodeType   = typeof(AstNode);
            ascii.AstConfig.NodeType   = typeof(AstNode);


            /*************** Gramatica ***************/
            this.Root = INICIO;

            INICIO.Rule = CUERPO;

            CUERPO.Rule = ToTerm("%%") + CODIGO + ToTerm("%%");

            CODIGO.Rule = MakeStarRule(CODIGO, SENTENCIA);

            SENTENCIA.Rule = CONJUNTO
                             | REGLA
                             | RERROR;

            CONJUNTO.Rule = conj + dosp + id + flecha + SERIE + fin
                            | conj + dosp + id + flecha + LISTA + fin;

            //SERIE.Rule = SIMBOLO + ToTerm("~") + SIMBOLO;
            //SERIE.Rule = SERIE2;
            SERIE.Rule = SIMBOLO + ToTerm("~") + SIMBOLO;

            LISTA.Rule = MakeStarRule(LISTA, coma, SIMBOLO);

            SIMBOLO.Rule = SERIE
                           | ESCAPE
                           | numero
                           | tstring
                           | tchar
                           | id
                           | ascii;

            REGLA.Rule = id + flecha + ER + flecha + METODO + fin
                         | id + flecha + ER + flecha + METODO + flecha + RESERVAR + fin
                         | id + flecha + ER + flecha + METODO + fin + flecha + RESERVAR + fin;

            ER.Rule = ER + ER + and
                      | ER + ER + or
                      | ER + muchos
                      | ER + nada_muchos
                      | ER + nada
                      | ESCAPE
                      | tstring
                      | tchar
                      | numero
                      | id;

            ESCAPE.Rule = salto
                          | retorno_carro
                          | tab
                          | comillas_s
                          | comillas_d
                          | blanco
                          | todo;

            /*ESCAPE.Rule = barra+ToTerm("n")
             | barra + ToTerm("r")
             | barra + ToTerm("t")
             | barra + ToTerm("'")
             | barra + ToTerm("\"")
             | blanco
             | todo;*/

            METODO.Rule = M1
                          | M2;

            RESERVAR.Rule = reserv + acor + RESERVADAS + ccor;

            RESERVADAS.Rule = MakeStarRule(RESERVADAS, RESERVADA);

            RESERVADA.Rule = tstring + flecha + retorno + apar + id + coma + yyline + coma + yyrow + cpar + fin
                             | id + flecha + retorno + apar + id + coma + yyline + coma + yyrow + cpar + fin;

            M1.Rule = retorno + apar + id + coma + yyline + coma + yyrow + cpar;

            M2.Rule = retorno + apar + id + coma + yytext + coma + TIPO + coma + yyline + coma + yyrow + cpar;

            TIPO.Rule = rint
                        | rfloat
                        | rstring
                        | rchar
                        | rbool;

            RERROR.Rule = rerror + flecha + ER + flecha + rerror + apar + yyline + coma + yyrow + coma + yytext + cpar + fin
                          | id + flecha + ER + flecha + rerror + apar + yyline + coma + yyrow + coma + yytext + cpar + fin;


            /*************** Precedencia y Asociatividad ***************/
            //RegisterOperators(1, or, and);
            //RegisterOperators(2, muchos, nada_muchos, nada);

            /*************** Errores ***************/
            CODIGO.ErrorRule     = SyntaxError + CODIGO;
            LISTA.ErrorRule      = SyntaxError + LISTA;
            RESERVADAS.ErrorRule = SyntaxError + RESERVADAS;


            /*************** Eliminación ***************/
            this.MarkPunctuation("%%", "->", ":", ";", ",", "~", "(", ")", "[", "]", "CONJ", "RESERV", "retorno");
            this.MarkTransient(CUERPO, SENTENCIA, SIMBOLO, RESERVAR, METODO, TIPO);

            LanguageFlags = LanguageFlags.CreateAst;
        }
        ///--------------------------------------------------------------------------------
        /// <summary>The default constructor sets up the overall grammar.</summary>
        ///
        /// <param name="solution">The solution containing model structure to add to the grammar.</param>
        ///--------------------------------------------------------------------------------
        public CodeTemplateContentGrammar(Solution solution)
        {
            bool isFirstItem = true;

            this.LanguageFlags  |= LanguageFlags.CreateAst;
            this.GrammarComments = "This grammar is used to parse the CONTENT section of an M+ code template.";

            #region "Literals, Symbols, Operators, Punctuation, etc."

            // literals
            StringLiteral StringLiteral = TerminalFactory.CreateCSharpString("StringLiteral");
            NumberLiteral Number        = TerminalFactory.CreateCSharpNumber("Number");
            Number.Options |= NumberOptions.AllowSign;
            IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier");

            // symbols
            KeyTerm textOpen   = ToTerm(LanguageTerms.TextOpenTag);
            KeyTerm evalOpen   = ToTerm(LanguageTerms.EvalOpenTag);
            KeyTerm outputOpen = ToTerm(LanguageTerms.OutputOpenTag);
            KeyTerm propOpen   = ToTerm(LanguageTerms.PropOpenTag);
            KeyTerm close      = ToTerm(LanguageTerms.CloseTag);
            KeyTerm dot        = ToTerm(".");
            KeyTerm comma      = ToTerm(",");
            KeyTerm Lbr        = ToTerm("{");
            KeyTerm Rbr        = ToTerm("}");
            KeyTerm Lpar       = ToTerm("(");
            KeyTerm Rpar       = ToTerm(")");
            KeyTerm slash      = ToTerm("/");

            // operators
            RegisterOperators(1, "||");
            RegisterOperators(2, "&&");
            RegisterOperators(3, "==", "!=");
            RegisterOperators(4, "<", ">", "<=", ">=");
            RegisterOperators(5, ".");
            RegisterOperators(6, "+", "-", "*", "/");

            // delimiters and punctuation
            this.Delimiters = "{}[](),:;+-*/%&|^!~<>=";
            this.MarkPunctuation("=", ";", ",", "(", ")", "{", "}", ".", LanguageTerms.ProgressTerm, LanguageTerms.TraceTerm, LanguageTerms.DebugTerm, LanguageTerms.WhileTerm, LanguageTerms.VarTerm, LanguageTerms.ParamTerm, LanguageTerms.IfTerm, LanguageTerms.ElseTerm, LanguageTerms.WithTerm, LanguageTerms.ForeachTerm, LanguageTerms.BreakTerm, LanguageTerms.ContinueTerm, LanguageTerms.ClearTerm, LanguageTerms.ReturnTerm, LanguageTerms.SwitchTerm, LanguageTerms.CaseTerm, LanguageTerms.DefaultTerm, LanguageTerms.WhereTerm, LanguageTerms.InTerm, LanguageTerms.LimitTerm, LanguageTerms.SortTerm, LanguageTerms.FromTerm, LanguageTerms.TextOpenTag, LanguageTerms.EvalOpenTag, LanguageTerms.OutputOpenTag, LanguageTerms.PropOpenTag, LanguageTerms.CloseTag);

            // whitespace and line terminators
            this.LineTerminators = "\r\n\u2085\u2028\u2029";
            this.WhitespaceChars = " \t\r\n\v\u2085\u2028\u2029";

            // comments
            CommentTerminal singleLineComment = new CommentTerminal("singleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            CommentTerminal delimitedComment  = new CommentTerminal("delimitedComment", "/*", "*/");
            TextTerminal    templateText      = new TextTerminal("templateText", "<%%-", "%%>");
            NonGrammarTerminals.Add(singleLineComment);
            NonGrammarTerminals.Add(delimitedComment);
            #endregion

            #region "Nodes"
            // high level nodes
            var template      = new NonTerminal("template", typeof(TemplateNode));
            var templateBlock = new NonTerminal("templateBlock");

            // statements
            var statementList     = new NonTerminal("statementList", typeof(StatementListNode));
            var statement         = new NonTerminal("statement");
            var ifStatement       = new NonTerminal("ifStatement", typeof(IfStatementNode));
            var switchStatement   = new NonTerminal("switchStatement", typeof(SwitchStatementNode));
            var foreachStatement  = new NonTerminal("foreachStatement", typeof(ForeachStatementNode));
            var whileStatement    = new NonTerminal("whileStatement", typeof(WhileStatementNode));
            var withStatement     = new NonTerminal("withStatement", typeof(WithStatementNode));
            var breakStatement    = new NonTerminal("breakStatement", typeof(BreakStatementNode));
            var clearStatement    = new NonTerminal("clearStatement", typeof(ClearTextStatementNode));
            var returnStatement   = new NonTerminal("returnStatement", typeof(ReturnStatementNode));
            var continueStatement = new NonTerminal("continueStatement", typeof(ContinueStatementNode));
            var currentItemAssignmentStatement      = new NonTerminal("currentItemAssignmentStatement", typeof(CurrentItemAssignmentStatementNode));
            var templatePropertyAssignmentStatement = new NonTerminal("templatePropertyAssignmentStatement", typeof(TemplatePropertyAssignmentStatementNode));
            var debugStatement      = new NonTerminal("debugStatement", typeof(DebugStatementNode));
            var traceStatement      = new NonTerminal("traceStatement", typeof(TraceStatementNode));
            var logStatement        = new NonTerminal("logStatement", typeof(LogStatementNode));
            var progressStatement   = new NonTerminal("progressStatement", typeof(ProgressStatementNode));
            var varStatement        = new NonTerminal("varStatement", typeof(VarStatementNode));
            var paramStatement      = new NonTerminal("paramStatement", typeof(ParamStatementNode));
            var assignmentStatement = new NonTerminal("assignmentStatement", typeof(AssignmentStatementNode));

            // clauses
            var elseClause            = new NonTerminal("elseClause", typeof(ElseClauseNode));
            var elseIfList            = new NonTerminal("elseIfList", typeof(ElseIfListNode));
            var elseIfClause          = new NonTerminal("elseIfClause", typeof(ElseIfClauseNode));
            var caseList              = new NonTerminal("caseList", typeof(CaseListNode));
            var caseClause            = new NonTerminal("caseClause", typeof(CaseClauseNode));
            var defaultClause         = new NonTerminal("defaultClause", typeof(DefaultClauseNode));
            var caseConditionList     = new NonTerminal("caseConditionList", typeof(CaseConditionListNode));
            var caseCondition         = new NonTerminal("caseCondition", typeof(CaseConditionNode));
            var foreachClause         = new NonTerminal("foreachClause", typeof(ForeachClauseNode));
            var whereClause           = new NonTerminal("whereClause", typeof(WhereClauseNode));
            var inClause              = new NonTerminal("inClause", typeof(InClauseNode));
            var limitClause           = new NonTerminal("limitClause", typeof(LimitClauseNode));
            var sortClause            = new NonTerminal("sortClause", typeof(SortClauseNode));
            var sortDirectionClause   = new NonTerminal("sortDirectionClause", typeof(SortDirectionClauseNode));
            var fromClause            = new NonTerminal("fromClause", typeof(FromClauseNode));
            var templateParameterList = new NonTerminal("templateParameterList", typeof(TemplateParameterListNode));
            var templateParameter     = new NonTerminal("templateParameter", typeof(TemplateParameterNode));

            // expressions
            var expression  = new NonTerminal("expression", typeof(ExpressionNode));
            var binOp       = new NonTerminal("binOp", "operator symbol", typeof(BinaryOperatorNode));
            var mathOp      = new NonTerminal("mathOp", "operator symbol", typeof(MathOperatorNode));
            var literal     = new NonTerminal("literal", typeof(LiteralNode));
            var popContext  = new NonTerminal("popContext", typeof(PopContextNode));
            var thisContext = new NonTerminal("thisContext", typeof(ThisContextNode));

            // properties
            var property              = new NonTerminal("property");
            var contentProperty       = new NonTerminal("contentProperty");
            var templateProperty      = new NonTerminal("templateProperty", typeof(TemplatePropertyNode));
            var inClauseItem          = new NonTerminal("inClauseItem", typeof(InClauselItemNode));
            var modelContext          = new NonTerminal("modelContext", typeof(ModelContextNode));
            var currentItem           = new NonTerminal("currentItem", typeof(CurrentItemNode));
            var modelProperty         = new NonTerminal("modelProperty", typeof(ModelPropertyNode));
            var assignableProperty    = new NonTerminal("assignableProperty", typeof(AssignablePropertyNode));
            var configurationProperty = new NonTerminal("configurationProperty", typeof(ConfigurationPropertyNode));
            var contextHelper         = new NonTerminal("contextHelper", typeof(ContextHelperNode));
            var collectionHelper      = new NonTerminal("collectionHelper", typeof(CollectionHelperNode));
            var parameter             = new NonTerminal("parameter", typeof(ParameterNode));
            #endregion

            #region "Rules"
            // a template consists of any number of template blocks
            template.Rule = MakeStarRule(template, null, templateBlock);

            // a template block is a property or an evaluation (a statement list surrounded by eval tags)
            templateBlock.Rule = property | evalOpen + statementList + close;

            // a statement list consists of any number of statements
            statementList.Rule = MakeStarRule(statementList, null, statement);

            // a statement can be an if, switch, foreach, with, or a property
            statement.Rule = ifStatement
                             | switchStatement
                             | foreachStatement
                             | whileStatement
                             | withStatement
                             | breakStatement
                             | continueStatement
                             | clearStatement
                             | returnStatement
                             | currentItemAssignmentStatement
                             | templatePropertyAssignmentStatement
                             | traceStatement
                             | logStatement
                             | varStatement
                             | paramStatement
                             | assignmentStatement
                             | property
                             | progressStatement;

            // var statement
            varStatement.Rule = ToTerm(LanguageTerms.VarTerm) + identifier | ToTerm(LanguageTerms.VarTerm) + identifier + "=" + parameter;

            // param statement
            paramStatement.Rule = ToTerm(LanguageTerms.ParamTerm) + identifier;

            // assignment statement
            assignmentStatement.Rule = identifier + "=" + parameter;

            // if statement
            ifStatement.Rule  = ToTerm(LanguageTerms.IfTerm) + Lpar + expression + Rpar + Lbr + statementList + Rbr + elseIfList + elseClause;
            elseIfList.Rule   = MakeStarRule(elseIfList, null, elseIfClause);
            elseIfClause.Rule = ToTerm(LanguageTerms.ElseTerm) + LanguageTerms.IfTerm + Lpar + expression + Rpar + Lbr + statementList + Rbr;
            elseClause.Rule   = Empty | ToTerm(LanguageTerms.ElseTerm) + Lbr + statementList + Rbr;

            // break and return statements, etc.
            breakStatement.Rule    = ToTerm(LanguageTerms.BreakTerm);
            continueStatement.Rule = ToTerm(LanguageTerms.ContinueTerm);
            clearStatement.Rule    = ToTerm(LanguageTerms.ClearTerm);
            returnStatement.Rule   = ToTerm(LanguageTerms.ReturnTerm);
            popContext.Rule        = dot + dot + slash;
            thisContext.Rule       = ToTerm(LanguageTerms.ThisTerm);

            // switch statement
            switchStatement.Rule   = ToTerm(LanguageTerms.SwitchTerm) + Lpar + modelProperty + Rpar + Lbr + caseList + defaultClause + Rbr;
            caseList.Rule          = MakePlusRule(caseList, null, caseClause);
            caseClause.Rule        = caseConditionList + statementList + breakStatement;
            defaultClause.Rule     = Empty | ToTerm(LanguageTerms.DefaultTerm) + ":" + statementList;
            caseConditionList.Rule = MakePlusRule(caseConditionList, null, caseCondition);
            caseCondition.Rule     = ToTerm(LanguageTerms.CaseTerm) + literal + ":";

            // a foreach statement consists of a foreach keyword, followed by a model context,
            // optionally followed by a where clause, and includes a set of statements
            // or, a foreach statement consists of a Record item
            foreachStatement.Rule    = ToTerm(LanguageTerms.ForeachTerm) + Lpar + foreachClause + Rpar + Lbr + statementList + Rbr;
            foreachClause.Rule       = modelContext + inClause + whereClause + limitClause + sortClause | ToTerm(LanguageTerms.RecordItem) + limitClause;
            inClause.Rule            = Empty | ToTerm(LanguageTerms.InTerm) + inClauseItem;
            whereClause.Rule         = Empty | ToTerm(LanguageTerms.WhereTerm) + expression;
            limitClause.Rule         = Empty | ToTerm(LanguageTerms.LimitTerm) + Number;
            sortClause.Rule          = Empty | ToTerm(LanguageTerms.SortTerm) + modelProperty + sortDirectionClause;
            sortDirectionClause.Rule = Empty | ToTerm(LanguageTerms.AscTerm) | ToTerm(LanguageTerms.DescTerm);

            // a while statement consists of a while keyword, followed by an expression,
            // and includes a set of statements
            whileStatement.Rule = ToTerm(LanguageTerms.WhileTerm) + Lpar + expression + Rpar + Lbr + statementList + Rbr;

            // current item assignment statement
            currentItemAssignmentStatement.Rule = currentItem + "=" + modelContext | currentItem + "=" + "null";

            // template property assignment statement
            templatePropertyAssignmentStatement.Rule = ToTerm(LanguageTerms.TextProperty) + "=" + parameter;

            // debug statement
            debugStatement.Rule = ToTerm(LanguageTerms.DebugTerm) + Lpar + parameter + Rpar
                                  | ToTerm(LanguageTerms.DebugTerm) + Lpar + parameter + comma + parameter + Rpar;

            // trace statement
            traceStatement.Rule = ToTerm(LanguageTerms.TraceTerm) + Lpar + parameter + Rpar
                                  | ToTerm(LanguageTerms.TraceTerm) + Lpar + parameter + comma + parameter + Rpar;

            // log statement
            logStatement.Rule = ToTerm(LanguageTerms.LogTerm) + Lpar + parameter + comma + parameter + comma + parameter + Rpar;

            // a with statement consists of a with keyword, followed by a model context,
            // and includes a set of statements
            withStatement.Rule = ToTerm(LanguageTerms.WithTerm) + Lpar + modelContext + fromClause + Rpar + Lbr + statementList + Rbr | LanguageTerms.WithTerm + Lpar + currentItem + Rpar + Lbr + statementList + Rbr;
            fromClause.Rule    = Empty | ToTerm(LanguageTerms.FromTerm) + contextHelper;

            // progress statement
            progressStatement.Rule = ToTerm(LanguageTerms.ProgressTerm) | LanguageTerms.ProgressTerm + Lpar + parameter + Rpar;

            // a context helper is one of the specifically supported internal methods to set model context
            contextHelper.Rule = modelContext + dot + LanguageTerms.FindMethod + Lpar + modelProperty + comma + parameter + Rpar
                                 | modelContext + dot + LanguageTerms.FindMethod + Lpar + parameter + Rpar
                                 | currentItem + dot + LanguageTerms.FindMethod + Lpar + modelProperty + comma + parameter + Rpar
                                 | currentItem + dot + LanguageTerms.FindMethod + Lpar + parameter + Rpar;

            // a property is a content property or an output property
            property.Rule = contentProperty | templateText;

            // a content property can be a template property, model property, or configuration property (template property is lowest precedence)
            contentProperty.Rule = propOpen + configurationProperty + close
                                   | propOpen + parameter + close;

            // a parameter is a model property or string literal
            parameter.Rule = modelProperty | literal | parameter + mathOp + parameter;

            // an in clause item is a collection from a model context, current item, or a special collection
            inClauseItem.Rule = modelContext
                                | currentItem
                                | collectionHelper;

            // a collection helper gets specialized collections
            collectionHelper.Rule = modelContext + dot + LanguageTerms.FindAllMethod + Lpar + modelProperty + comma + parameter + Rpar
                                    | currentItem + dot + LanguageTerms.FindAllMethod + Lpar + modelProperty + comma + parameter + Rpar
                                    | ToTerm(LanguageTerms.GetEntityAndBasesCollection)
                                    | ToTerm(LanguageTerms.GetBaseAndEntitiesCollection)
                                    | ToTerm(LanguageTerms.ExtendingEntitiesCollection)
                                    | ToTerm(LanguageTerms.PathRelationships);

            // a current item node is a valid name of a type of node in the model that can be assigned to
            isFirstItem = true;
            // add all CurrentItemTypeCode enums to currentItem rule
            foreach (string key in GrammarHelper.CurrentItemTypes.AllKeys)
            {
                if (isFirstItem == true)
                {
                    currentItem.Rule = ToTerm(key);
                    isFirstItem      = false;
                }
                else
                {
                    currentItem.Rule = currentItem.Rule | ToTerm(key);
                }
            }
            // add all ModelObject instances in model to currentItem rule
            if (solution != null)
            {
                foreach (string key in solution.ModelObjectNames.AllKeys)
                {
                    currentItem.Rule = currentItem.Rule | ToTerm("Current" + key);
                }
            }
            // add all ModelObjectProperty instances in model to currentItem rule
            if (solution != null)
            {
                foreach (string key in solution.ModelObjectPropertyNames.AllKeys)
                {
                    currentItem.Rule = currentItem.Rule | ToTerm("Current" + key);
                }
            }

            // a model context node is a valid name of a type of node in the model or a pop context directive
            modelContext.Rule = popContext
                                | popContext + modelContext
                                | thisContext
                                | thisContext + dot + modelContext;
            // add all ModelContextTypeCode enums to modelContext rule
            foreach (string key in GrammarHelper.ModelContextTypes.AllKeys)
            {
                modelContext.Rule = modelContext.Rule | ToTerm(key);
            }
            // add all OtherModelContextTypeCode enums to modelContext rule
            foreach (string key in GrammarHelper.OtherModelContextTypes.AllKeys)
            {
                modelContext.Rule = modelContext.Rule | ToTerm(key);
            }
            // add all ModelObject instances in model to modelContext rule
            if (solution != null)
            {
                foreach (string key in solution.ModelObjectNames.AllKeys)
                {
                    modelContext.Rule = modelContext.Rule | ToTerm(key);
                }
            }
            // add all ModelObjectProperty instances in model to assignableProperty rule
            if (solution != null)
            {
                foreach (string key in solution.ModelObjectPropertyNames.AllKeys)
                {
                    modelContext.Rule = modelContext.Rule | ToTerm(key);
                }
            }

            // an assignable property is a model property that can have values assigned to it
            isFirstItem = true;
            // add all AssignablePropertyCode enums to assignableProperty rule
            foreach (string key in GrammarHelper.AssignableProperties.AllKeys)
            {
                if (isFirstItem == true)
                {
                    assignableProperty.Rule = ToTerm(key);
                    isFirstItem             = false;
                }
                else
                {
                    assignableProperty.Rule = assignableProperty.Rule | ToTerm(key);
                }
            }
            // add all ModelProperty instances in model to assignableProperty rule
            if (solution != null)
            {
                foreach (string key in solution.ModelPropertyNames.AllKeys)
                {
                    assignableProperty.Rule = assignableProperty.Rule | ToTerm(key);
                }
            }

            // a model property is a valid property name of a node in the model (can refer to other nodes with the dot notation)
            modelProperty.Rule = assignableProperty
                                 | ToTerm(LanguageTerms.ItemIndexProperty)
                                 | ToTerm(LanguageTerms.TextProperty)
                                 | ToTerm(LanguageTerms.PathProperty)
                                 //| ToTerm(LanguageTerms.LibraryDirectoryProperty)
                                 | ToTerm(LanguageTerms.IsRelatedToProperty)
                                 | modelContext + dot + modelProperty
                                 | currentItem + dot + modelProperty
                                 | templateProperty
                                 | popContext + modelProperty
                                 | thisContext + dot + modelProperty
                                 | ToTerm(LanguageTerms.ColumnMethod) + Lpar + parameter + Rpar
                                 | ToTerm(LanguageTerms.FileMethod) + Lpar + parameter + Rpar
                                 | ToTerm(LanguageTerms.FileExistsMethod) + Lpar + parameter + Rpar
                                 | ToTerm(LanguageTerms.LogMethod) + Lpar + parameter + comma + parameter + Rpar
                                 | ToTerm(LanguageTerms.HasPropertyNamed) + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringStartsWith + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringEndsWith + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringContains + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringRegexReplace + Lpar + parameter + comma + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringRegexIsMatch + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringCamelCase + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringCapitalCase + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringCapitalWordCase + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringUnderscoreCase + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringToLower + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringToUpper + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringTrim + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringTrimStart + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringTrimEnd + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringReplace + Lpar + parameter + comma + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringFilter + Lpar + parameter + comma + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringFilterProtected + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringFilterIgnored + Lpar + Rpar
                                 | modelProperty + dot + LanguageTerms.StringSubstring + Lpar + parameter + comma + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringSubstring + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringIndexOf + Lpar + parameter + Rpar
                                 | modelProperty + dot + LanguageTerms.StringLength;
            // add all ReadOnlyPropertyCode enums to modelProperty rule
            foreach (string key in GrammarHelper.ReadOnlyProperties.AllKeys)
            {
                modelProperty.Rule = modelProperty.Rule | ToTerm(key);
            }

            // a configuration property is one of the specfically supported internal methods to process model data
            configurationProperty.Rule = ToTerm(LanguageTerms.TabMethod) + Number
                                         | ToTerm(LanguageTerms.UseTabsMethod) + "true"
                                         | ToTerm(LanguageTerms.UseTabsMethod) + "false"
                                         | ToTerm(LanguageTerms.TabStringMethod) + StringLiteral
                                         | ToTerm(LanguageTerms.UseProtectedAreasMethod) + "true"
                                         | ToTerm(LanguageTerms.UseProtectedAreasMethod) + "false"
                                         | ToTerm(LanguageTerms.ProtectedAreaStartMethod) + StringLiteral
                                         | ToTerm(LanguageTerms.ProtectedAreaEndMethod) + StringLiteral
                                         | ToTerm(LanguageTerms.UseIgnoredAreasMethod) + "true"
                                         | ToTerm(LanguageTerms.UseIgnoredAreasMethod) + "false"
                                         | ToTerm(LanguageTerms.IgnoredAreaStartMethod) + StringLiteral
                                         | ToTerm(LanguageTerms.IgnoredAreaEndMethod) + StringLiteral
                                         | ToTerm(LanguageTerms.UserMethod)
                                         | ToTerm(LanguageTerms.NowMethod);

            // a template property from the parser perspective is just an identifier, the interpreter will resolve template references
            templateProperty.Rule = identifier
                                    | identifier + Lpar + templateParameterList + Rpar;

            // a template parameter list consists of any number of template parameters delimited by commas
            templateParameterList.Rule = MakeStarRule(templateParameterList, comma, templateParameter);

            // template parameter
            templateParameter.Rule = identifier + "=" + parameter;

            // an expression can be a hierarchy of expressions with binary operators, model properties, and literals
            expression.Rule = literal
                              | modelProperty
                              | modelContext
                              | currentItem
                              | expression + binOp + expression
                              | expression + mathOp + expression
                              | Lpar + expression + Rpar;

            // a literal can be a number, string, character, true, false, or null
            literal.Rule = Number | StringLiteral | "true" | "false" | "null";

            // binary operator
            binOp.Rule = ToTerm("||") | "&&" | "==" | "!=" | "<" | ">" | "<=" | ">=";

            // math operator
            mathOp.Rule = ToTerm("+") | "-" | "*" | "/";

            #endregion

            // the template is the root of the grammar
            this.Root = template;

            // mark nodes to filter from the parse tree
            this.MarkTransient(statement, templateBlock, property, contentProperty);
        }
Esempio n. 16
0
        internal virtual void InitProductions()
        {
            #region Definitions
            var statement                    = new NonTerminal(XpressConstants.Tokens.NonTerminals.Statement);
            var expression                   = new NonTerminal(XpressConstants.Tokens.NonTerminals.Expression);
            var parenExpression              = new NonTerminal(XpressConstants.Tokens.NonTerminals.ParenExpression);
            var relationalExpression         = new NonTerminal(XpressConstants.Tokens.NonTerminals.RelationalExpression);
            var binaryAdditiveExpression     = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryAdditiveExpression);
            var binaryMultiplicityExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryMultiplicityExpression);
            var unaryExpression              = new NonTerminal(XpressConstants.Tokens.NonTerminals.UnaryExpression);
            var conditionalOperator          = new NonTerminal(XpressConstants.Tokens.NonTerminals.ConditionalOperator);
            var relationalOperator           = new NonTerminal(XpressConstants.Tokens.NonTerminals.RelationalOperator);
            var binaryAdditiveOperator       = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryAdditiveOperator);
            var binaryMultiplicityOperator   = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryMultiplicityOperator);
            var unaryOperator                = new NonTerminal(XpressConstants.Tokens.NonTerminals.UnaryOperator);
            var primaryExpression            = new NonTerminal(XpressConstants.Tokens.NonTerminals.PrimaryExpression);
            var nullLiteral                  = new NonTerminal(XpressConstants.Tokens.NonTerminals.NullLiteral);
            var booleanLiteral               = new NonTerminal(XpressConstants.Tokens.NonTerminals.BooleanLiteral);
            var identifier                   = TerminalFactory.CreateCSharpIdentifier(XpressConstants.Tokens.NonTerminals.Identifier);
            var numberLiteral                = TerminalFactory.CreateCSharpNumber(XpressConstants.Tokens.NonTerminals.NumberLiteral);
            var stringLiteral                = TerminalFactory.CreateCSharpString(XpressConstants.Tokens.NonTerminals.StringLiteral);

            var expressionBegin                    = ToTerm(XpressConstants.Tokens.Terminals.ExpressionBeginSymbol);
            var expressionEnd                      = ToTerm(XpressConstants.Tokens.Terminals.ExpressionEndSymbol);
            var conditionalAndOperator             = ToTerm(XpressConstants.Tokens.Terminals.ConditionalAndOperator);
            var conditionalOrOperator              = ToTerm(XpressConstants.Tokens.Terminals.ConditionalOrOperator);
            var relationalGreatThanOperator        = ToTerm(XpressConstants.Tokens.Terminals.RelationalGreatThanOperator);
            var relationalLessThanOperator         = ToTerm(XpressConstants.Tokens.Terminals.RelationalLessThanOperator);
            var relationalGreatThanOrEqualOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalGreatThanOrEqualOperator);
            var relationalLessThanOrEqualOperator  = ToTerm(XpressConstants.Tokens.Terminals.RelationalLessThanOrEqualOperator);
            var relationalEqualityOperator         = ToTerm(XpressConstants.Tokens.Terminals.RelationalEqualityOperator);
            var relationalNonEqualityOperator      = ToTerm(XpressConstants.Tokens.Terminals.RelationalNonEqualityOperator);
            var binaryAdditionOperator             = ToTerm(XpressConstants.Tokens.Terminals.BinaryAdditionOperator);
            var binarySubtrationOperator           = ToTerm(XpressConstants.Tokens.Terminals.BinarySubtrationOperator);
            var binaryMultiplicationOperator       = ToTerm(XpressConstants.Tokens.Terminals.BinaryMultiplicationOperator);
            var binaryDivisionOperator             = ToTerm(XpressConstants.Tokens.Terminals.BinaryDivisionOperator);
            var binaryModuloOperator               = ToTerm(XpressConstants.Tokens.Terminals.BinaryModuloOperator);
            var unaryNegationOperator              = ToTerm(XpressConstants.Tokens.Terminals.UnaryNegationOperator);
            var nullValue         = ToTerm(XpressConstants.Tokens.Terminals.NullValue);
            var booleanTrueValue  = ToTerm(XpressConstants.Tokens.Terminals.BooleanTrueValue);
            var booleanFalseValue = ToTerm(XpressConstants.Tokens.Terminals.BooleanFalseValue);
            stringLiteral.AddStartEnd(XpressConstants.Tokens.Terminals.StringStartEndSymbol, StringOptions.NoEscapes);
            #endregion

            // BNF

            Root           = statement;
            statement.Rule = expression;

            parenExpression.Rule = expressionBegin + expression + expressionEnd;

            expression.Rule
                = expression + conditionalOperator + relationalExpression
                  | relationalExpression;

            conditionalOperator.Rule = conditionalAndOperator | conditionalOrOperator;

            relationalExpression.Rule
                = relationalExpression + relationalOperator + binaryAdditiveExpression
                  | binaryAdditiveExpression;

            relationalOperator.Rule = relationalGreatThanOperator
                                      | relationalGreatThanOrEqualOperator
                                      | relationalLessThanOperator
                                      | relationalLessThanOrEqualOperator
                                      | relationalEqualityOperator
                                      | relationalNonEqualityOperator;

            binaryAdditiveExpression.Rule
                = binaryAdditiveExpression + binaryAdditiveOperator + binaryMultiplicityExpression
                  | binaryMultiplicityExpression;

            binaryAdditiveOperator.Rule = binaryAdditionOperator | binarySubtrationOperator;

            binaryMultiplicityExpression.Rule
                = binaryMultiplicityExpression + binaryMultiplicityOperator + unaryExpression
                  | unaryExpression;

            binaryMultiplicityOperator.Rule = binaryMultiplicationOperator
                                              | binaryDivisionOperator
                                              | binaryModuloOperator;

            unaryExpression.Rule = unaryOperator + primaryExpression
                                   | primaryExpression;

            unaryOperator.Rule = unaryNegationOperator;

            primaryExpression.Rule = identifier
                                     | numberLiteral
                                     | stringLiteral
                                     | booleanLiteral
                                     | nullLiteral
                                     | parenExpression;

            nullLiteral.Rule    = nullValue;
            booleanLiteral.Rule = booleanTrueValue | booleanFalseValue;
        }
Esempio n. 17
0
        public AnalizadorPy()
            : base(caseSensitive: false)
        {
            #region expresiones regulares

            var           identificador = TerminalFactory.CreateCSharpIdentifier("identificador");
            var           numero        = TerminalFactory.CreateCSharpNumber("numero");
            var           val_false     = Constantes.falso;
            var           val_true      = Constantes.verdadero;
            StringLiteral cadena        = new StringLiteral("cadena", "\"");
            var           caracter      = TerminalFactory.CreateCSharpChar(Constantes.caracter);

            CommentTerminal COMENT_BLOQUE = new CommentTerminal("COMENTARIO BLOQUE", "/*", "*/");
            CommentTerminal COMENT_LINEA  = new CommentTerminal("COMENTARIO LINEA", "//", "\n", "\r\n");
            NonGrammarTerminals.Add(COMENT_BLOQUE);
            NonGrammarTerminals.Add(COMENT_LINEA);

            #endregion


            #region palabras reservadas
            var tipoDecimal  = Constantes.tipoDecimal;
            var tipoString   = Constantes.tipoCadena;
            var tipoBoolean  = Constantes.tipoBool;
            var tipoCaracter = Constantes.tipoChar;
            var tipoInt      = Constantes.tipoEntero;
            var tipoVoid     = Constantes.tipoVoid;

            var visiPublico   = Constantes.publico;
            var visiPrivado   = Constantes.privado;
            var visiProtegido = Constantes.protegido;

            var clase         = Constantes.clase;
            var sobreescribir = Constantes.sobreescribir;

            #endregion



            #region declaproducciones
            NonTerminal FUN_SOBRE    = new NonTerminal(Constantes.funSobre);
            NonTerminal TIPO         = new NonTerminal(Constantes.tipo);
            NonTerminal FUNCION      = new NonTerminal(Constantes.funcion);
            NonTerminal VISIBILIDAD  = new NonTerminal(Constantes.visibilidad);
            NonTerminal CUERPO       = new NonTerminal(Constantes.cuerpo);
            NonTerminal PARAMETRO    = new NonTerminal(Constantes.parametro);
            NonTerminal L_PARAMETRO  = new NonTerminal(Constantes.listaParametros);
            NonTerminal L_ELEMENTOS  = new NonTerminal(Constantes.listaElementos);
            NonTerminal ATRIBUTO     = new NonTerminal(Constantes.atributo);
            NonTerminal L_IDS        = new NonTerminal(Constantes.listaIds);
            NonTerminal EXPRESION    = new NonTerminal(Constantes.expresion);
            NonTerminal ELEMENTO     = new NonTerminal(Constantes.elementoClase);
            NonTerminal CLASE        = new NonTerminal(Constantes.clase);
            NonTerminal CUERPO_CLASE = new NonTerminal(Constantes.CUERPO_CLASE);
            NonTerminal PRINCIPAL    = new NonTerminal(Constantes.principal);
            NonTerminal CONSTRUCTOR  = new NonTerminal(Constantes.constructor);



            NonTerminal IMPRIMIR      = new NonTerminal(Constantes.imprimir);
            NonTerminal DECLAPARA     = new NonTerminal("DECLAPARA");
            NonTerminal INSTRUCCIONES = new NonTerminal(Constantes.instrucciones);
            NonTerminal INSTRUCCION   = new NonTerminal(Constantes.instruccion);
            NonTerminal DECLARACION   = new NonTerminal(Constantes.declaracion);
            NonTerminal LPOSICIONES   = new NonTerminal(Constantes.lposiciones);
            NonTerminal LEXPRESIONES  = new NonTerminal(Constantes.lexpresiones);
            NonTerminal LFILAS        = new NonTerminal(Constantes.lfilas);
            NonTerminal ASIGNACION    = new NonTerminal(Constantes.asignacion);
            NonTerminal POSICION      = new NonTerminal(Constantes.posicion);
            NonTerminal FILA          = new NonTerminal(Constantes.fila);


            NonTerminal DECIMAL     = new NonTerminal(Constantes.tipoDecimal);
            NonTerminal ENTERO      = new NonTerminal(Constantes.tipoEntero);
            NonTerminal CADENA      = new NonTerminal(Constantes.tipoCadena);
            NonTerminal CHAR        = new NonTerminal(Constantes.tipoChar);
            NonTerminal BOOLEANO    = new NonTerminal(Constantes.tipoBool);
            NonTerminal SIMB_ARIT   = new NonTerminal(Constantes.simb_arit);
            NonTerminal SIMB_REL    = new NonTerminal(Constantes.simb_rel);
            NonTerminal UNARIO      = new NonTerminal(Constantes.unario);
            NonTerminal ID          = new NonTerminal(Constantes.id);
            NonTerminal NEGATIVO    = new NonTerminal(Constantes.negativo);
            NonTerminal RELACIONAL  = new NonTerminal(Constantes.relacional);
            NonTerminal ARITMETICA  = new NonTerminal(Constantes.aritmetica);
            NonTerminal LOGICA      = new NonTerminal(Constantes.logica);
            NonTerminal LLAMADA     = new NonTerminal(Constantes.llamada);
            NonTerminal POSVECTOR   = new NonTerminal(Constantes.posvector);
            NonTerminal LISTAPUNTOS = new NonTerminal(Constantes.listapuntos);
            NonTerminal SIMB_LOG    = new NonTerminal(Constantes.simb_log);
            NonTerminal MAS_MAS     = new NonTerminal(Constantes.masmas);
            NonTerminal MENOS_MENOS = new NonTerminal(Constantes.menosmenos);
            NonTerminal ASIG_ARRAY  = new NonTerminal(Constantes.asig_array);
            NonTerminal termino     = new NonTerminal(Constantes.termino);
            NonTerminal RETORNO     = new NonTerminal(Constantes.retorno);
            NonTerminal LISTACLASES = new NonTerminal(Constantes.l_clases);



            NonTerminal SUMA           = new NonTerminal(Constantes.suma);
            NonTerminal RESTA          = new NonTerminal(Constantes.resta);
            NonTerminal MULTIPLICACION = new NonTerminal(Constantes.multiplicacion);
            NonTerminal DIVISION       = new NonTerminal(Constantes.division);
            NonTerminal POTENCIA       = new NonTerminal(Constantes.potencia);
            NonTerminal MENOR          = new NonTerminal(Constantes.menor);
            NonTerminal MENORIGUAL     = new NonTerminal(Constantes.menorIgual);
            NonTerminal MAYOR          = new NonTerminal(Constantes.mayor);
            NonTerminal MAYORIGUAL     = new NonTerminal(Constantes.mayorIgual);
            NonTerminal IGUALIGUAL     = new NonTerminal(Constantes.igualIgual);
            NonTerminal DISTINTOA      = new NonTerminal(Constantes.distintoA);
            NonTerminal XOR            = new NonTerminal(Constantes.xorJava);
            NonTerminal AND            = new NonTerminal(Constantes.andJava);
            NonTerminal NOT            = new NonTerminal(Constantes.notJavaPython);
            NonTerminal OR             = new NonTerminal(Constantes.orJava);
            NonTerminal INSTANCIA      = new NonTerminal(Constantes.instancia);
            NonTerminal SALIR          = new NonTerminal(Constantes.salir);
            NonTerminal CONTINUAR      = new NonTerminal(Constantes.continuar);

            NonTerminal SI       = new NonTerminal(Constantes.si);
            NonTerminal EXTRA    = new NonTerminal(Constantes.extraSi);
            NonTerminal SINO     = new NonTerminal(Constantes.sino);
            NonTerminal CUERPOSI = new NonTerminal(Constantes.cuerposi);
            NonTerminal L_EXTRAS = new NonTerminal(Constantes.lextra);

            NonTerminal MIENTRAS = new NonTerminal(Constantes.mientras);
            NonTerminal REPETIR  = new NonTerminal(Constantes.repetir);
            NonTerminal HACER    = new NonTerminal(Constantes.hacer);
            NonTerminal PARA     = new NonTerminal(Constantes.para);
            NonTerminal LOOP     = new NonTerminal(Constantes.loop);


            #endregion

            VISIBILIDAD.Rule = ToTerm(visiPrivado)
                               | ToTerm(visiProtegido)
                               | ToTerm(visiPublico);


            TIPO.Rule = ToTerm(tipoBoolean)
                        | ToTerm(tipoCaracter)
                        | ToTerm(tipoDecimal)
                        | ToTerm(tipoInt)
                        | ToTerm(tipoString)
                        | identificador;


            L_IDS.Rule = MakePlusRule(L_IDS, ToTerm(","), identificador);

            DECLARACION.Rule = TIPO + L_IDS
                               | TIPO + L_IDS + LPOSICIONES;


            POSICION.Rule = ToTerm("[") + EXPRESION + "]";

            LPOSICIONES.Rule = MakePlusRule(LPOSICIONES, POSICION);

            FILA.Rule = ToTerm("{") + LEXPRESIONES + "}";



            LFILAS.Rule = MakePlusRule(LFILAS, ToTerm(","), FILA);


            ASIGNACION.Rule = EXPRESION + ToTerm("=") + ">" + EXPRESION;



            INSTRUCCION.Rule = DECLARACION + Eos
                               | CONTINUAR + Eos
                               | SALIR + Eos
                               | MIENTRAS + Eos
                               | HACER
                               | REPETIR
                               | LOOP + Eos;


            INSTRUCCIONES.Rule = MakePlusRule(INSTRUCCIONES, INSTRUCCION);

            CUERPO.Rule = Indent + INSTRUCCIONES + Dedent;

            FUNCION.Rule = VISIBILIDAD + ToTerm("funcion") + TIPO + identificador + "[" + "]" + Eos + CUERPO;



            #region estructuras de control

            CONTINUAR.Rule = ToTerm(Constantes.continuar);

            SALIR.Rule = ToTerm(Constantes.salir);

            MIENTRAS.Rule = ToTerm(Constantes.mientras) + EXPRESION + ":" + Eos + CUERPO;

            HACER.Rule = ToTerm(Constantes.hacer) + ":" + Eos + CUERPO + ToTerm(Constantes.mientras) + EXPRESION + Eos;

            REPETIR.Rule = ToTerm(Constantes.repetir) + ":" + Eos + CUERPO + ToTerm(Constantes.hasta) + EXPRESION + Eos;

            LOOP.Rule = ToTerm(Constantes.loop) + ":" + Eos + CUERPO;



            #endregion



            #region expresion



            DECIMAL.Rule  = numero;
            ENTERO.Rule   = numero;
            CADENA.Rule   = cadena;
            ID.Rule       = identificador;
            CHAR.Rule     = caracter;
            BOOLEANO.Rule = ToTerm(val_false)
                            | ToTerm(val_true);


            ARITMETICA.Rule = SUMA
                              | RESTA
                              | MULTIPLICACION
                              | DIVISION
                              | POTENCIA;

            RELACIONAL.Rule = MENOR
                              | MAYOR
                              | MENORIGUAL
                              | MAYORIGUAL
                              | DISTINTOA
                              | IGUALIGUAL;

            LOGICA.Rule = XOR
                          | OR
                          | AND
                          | NOT;



            SUMA.Rule           = EXPRESION + ToTerm(Constantes.suma) + EXPRESION;
            RESTA.Rule          = EXPRESION + ToTerm(Constantes.resta) + EXPRESION;
            MULTIPLICACION.Rule = EXPRESION + ToTerm(Constantes.multiplicacion) + EXPRESION;
            DIVISION.Rule       = EXPRESION + ToTerm(Constantes.division) + EXPRESION;
            POTENCIA.Rule       = EXPRESION + ToTerm(Constantes.potencia) + EXPRESION;
            MENOR.Rule          = EXPRESION + ToTerm(Constantes.menor) + EXPRESION;
            MENORIGUAL.Rule     = EXPRESION + ToTerm(Constantes.menorIgual) + EXPRESION;
            MAYOR.Rule          = EXPRESION + ToTerm(Constantes.mayor) + EXPRESION;
            MAYORIGUAL.Rule     = EXPRESION + ToTerm(Constantes.mayorIgual) + EXPRESION;
            IGUALIGUAL.Rule     = EXPRESION + ToTerm(Constantes.igualIgual) + EXPRESION;
            DISTINTOA.Rule      = EXPRESION + ToTerm(Constantes.distintoA) + EXPRESION;
            XOR.Rule            = EXPRESION + ToTerm(Constantes.xorPython) + EXPRESION;
            AND.Rule            = EXPRESION + ToTerm(Constantes.andPython) + EXPRESION;
            NOT.Rule            = ToTerm(Constantes.notJavaPython) + EXPRESION;
            OR.Rule             = EXPRESION + ToTerm(Constantes.orPython) + EXPRESION;

            INSTANCIA.Rule = Constantes.nuevoPython + identificador + "[" + LEXPRESIONES + "]"
                             | Constantes.nuevoPython + identificador + "[" + "]";

            UNARIO.Rule = MAS_MAS
                          | MENOS_MENOS;

            MAS_MAS.Rule = identificador + ToTerm(Constantes.masmas);

            MENOS_MENOS.Rule = identificador + ToTerm(Constantes.menosmenos);


            NEGATIVO.Rule = ToTerm("-") + EXPRESION;

            termino.Rule = ToTerm("(") + ARITMETICA + ")"
                           | ToTerm("[") + RELACIONAL + "]"
                           | ToTerm("{") + LOGICA + "}"
                           | DECIMAL
                           | ENTERO
                           | ID
                           | CADENA
                           | BOOLEANO
                           | CHAR
                           | LLAMADA
                           | POSVECTOR
                           | ToTerm("(") + UNARIO + ")"
                           | NEGATIVO
                           | "{" + LFILAS + "}"
                           | INSTANCIA;

            LLAMADA.Rule = identificador + ToTerm("[") + LEXPRESIONES + "]"
                           | identificador + ToTerm("[") + "]";


            POSVECTOR.Rule = identificador + LPOSICIONES;

            L_IDS.Rule = MakePlusRule(L_IDS, ToTerm(","), identificador);



            EXPRESION.Rule = MakePlusRule(EXPRESION, ToTerm("."), termino);

            LEXPRESIONES.Rule = MakePlusRule(EXPRESION, ToTerm(","), EXPRESION);



            #endregion



            NonTerminal n = new NonTerminal("fdsfd");
            n.Rule = termino + Eos;



            this.Root = n;
        }
Esempio n. 18
0
        public Gramatica() : base(caseSensitive: true)
        {
            //---------------------> Comentarios
            CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "!!", "\n", "\r\n");
            CommentTerminal COMENTARIO_MULT   = new CommentTerminal("comentario_mult", "<<", ">>");

            NonGrammarTerminals.Add(COMENTARIO_SIMPLE);
            NonGrammarTerminals.Add(COMENTARIO_MULT);

            /*--------------------Definir Palabras Reservadas ----------------*/
            MarkReservedWords("Importar");
            MarkReservedWords("Definir");
            MarkReservedWords("Double");
            MarkReservedWords("String");
            MarkReservedWords("Bool");
            MarkReservedWords("Int");
            MarkReservedWords("Char");
            MarkReservedWords("Retorno");
            MarkReservedWords("Vacio");
            MarkReservedWords("Principal");
            MarkReservedWords("Si");
            MarkReservedWords("Sino");
            MarkReservedWords("Selecciona");
            MarkReservedWords("Defecto");
            MarkReservedWords("Para");
            MarkReservedWords("Hasta");
            MarkReservedWords("Mientras");
            MarkReservedWords("Detener");
            MarkReservedWords("Continuar");
            MarkReservedWords("Mostrar");
            MarkReservedWords("DibujarAST");
            MarkReservedWords("DibujarEXP");
            MarkReservedWords("DibujarTS");


            /*--------------------- (Opcional)Definir variables para palabras reservadas--*/

            var mas      = ToTerm("+");
            var punto    = ToTerm(".");
            var menos    = ToTerm("-");
            var por      = ToTerm("*");
            var division = ToTerm("/");
            var potencia = ToTerm("^");
            var igual    = ToTerm("=");
            var porc     = ToTerm("%");

            var allave    = ToTerm("{");
            var cllave    = ToTerm("}");
            var apar      = ToTerm("(");
            var cpar      = ToTerm(")");
            var coma      = ToTerm(",");
            var dospuntos = ToTerm(":");
            var puntocoma = ToTerm(";");
            var llavea    = ToTerm("{");
            var llavec    = ToTerm("}");
            var trues     = ToTerm("true");
            var falses    = ToTerm("false");

            /*-------------relacionales------------------*/
            var igualigual = ToTerm("==");
            var diferente  = ToTerm("!=");
            var mayor      = ToTerm(">");
            var menor      = ToTerm("<");
            var mayorigual = ToTerm(">=");
            var menorigual = ToTerm("<=");
            var incerteza  = ToTerm("~");
            var masmas     = ToTerm("++");
            var menosmenos = ToTerm("--");
            /*--------------------expresiones logicas---------*/
            var or  = ToTerm("||");
            var and = ToTerm("&&");
            var not = ToTerm("!");
            var xor = ToTerm("|&");

            /*----------------------palabras-------*/
            var importar   = ToTerm("Importar");
            var definir    = ToTerm("Definir");
            var vadouble   = ToTerm("Double");
            var vastring   = ToTerm("String");
            var varint     = ToTerm("Int");
            var vabool     = ToTerm("Bool");
            var vachar     = ToTerm("Char");
            var retorno    = ToTerm("Retorno");
            var vacio      = ToTerm("Vacio");
            var principal  = ToTerm("Principal");
            var si         = ToTerm("Si");
            var sino       = ToTerm("Sino");
            var selecciona = ToTerm("Selecciona");
            var defecto    = ToTerm("Defecto");
            var para       = ToTerm("Para");
            var hasta      = ToTerm("Hasta");
            var mientras   = ToTerm("Mientras");
            var detener    = ToTerm("Detener");
            var continuar  = ToTerm("Continuar");
            var mostrar    = ToTerm("Mostrar");
            var dibast     = ToTerm("DibujarAST");
            var dibexp     = ToTerm("DibujarEXP");
            var dibts      = ToTerm("DibujarTS");



            /*--------------------- No Terminales --------*/
            var INICIO       = new NonTerminal("INICIO");
            var LISTA        = new NonTerminal("LISTA");
            var ESTRUC       = new NonTerminal("ESTRUC");
            var DECLARACION  = new NonTerminal("DECLARACION");
            var DECLARACION2 = new NonTerminal("DECLARACION2");
            var EXPRESION    = new NonTerminal("EXPRESION");

            var EXPRESION2     = new NonTerminal("EXPRESION2");
            var CTIPO          = new NonTerminal("CTIPO");
            var VARIOS         = new NonTerminal("VARIOS");
            var ESTRUCTURA     = new NonTerminal("ESTRUCTURA");
            var ENCABEZADO     = new NonTerminal("ENCABEZADO");
            var TIPO           = new NonTerminal("TIPO");
            var CUERPO         = new NonTerminal("CUERPO");
            var ASIGNACION     = new NonTerminal("ASIGNACION");
            var ASIGNACION2    = new NonTerminal("ASIGNACION2");
            var FUN            = new NonTerminal("FUN");
            var METOD          = new NonTerminal("METOD");
            var LISTA2         = new NonTerminal("LISTA2");
            var DECLAPARA      = new NonTerminal("DECLAPARA");
            var PARAMETROS     = new NonTerminal("PARAMETROS");
            var ESTRUC2        = new NonTerminal("ESTRUC2");
            var FUNPRIN        = new NonTerminal("FUNPRIN");
            var LISTA3         = new NonTerminal("LISTA3");
            var ESTRUC3        = new NonTerminal("ESTRUC3");
            var LLAMADAS       = new NonTerminal("LLAMADAS");
            var RETORN         = new NonTerminal("RETORN");
            var SENTSI         = new NonTerminal("SENTSI");
            var SENTSINO       = new NonTerminal("SENTSINO");
            var SENTHASTA      = new NonTerminal("SENTHASTA");
            var SENTMIENTRAS   = new NonTerminal("SENTMIENTRAS");
            var SENTPARA       = new NonTerminal("SENTPARA");
            var SENTSELECCIONA = new NonTerminal("SENTSELECCIONA");
            var CASO           = new NonTerminal("CASO");
            var DEFECT         = new NonTerminal("DEFECT");
            var PRINT          = new NonTerminal("PRINT");
            var DIBAST         = new NonTerminal("DIBAST");
            var DIBEXP         = new NonTerminal("DIBEXP");
            var DIBTS          = new NonTerminal("DIBTS");
            var LLAMAR         = new NonTerminal("LLAMAR");
            var VARIOS2        = new NonTerminal("VARIOS2");

            //---------------------> Terminales
            var                tString = new StringLiteral("tString", "\"", StringOptions.AllowsDoubledQuote);
            var                tchar   = new StringLiteral("tchar", "\'", StringOptions.AllowsDoubledQuote);
            NumberLiteral      numero  = TerminalFactory.CreateCSharpNumber("numero");
            IdentifierTerminal id      = TerminalFactory.CreateCSharpIdentifier("id");


            //---------------------> No Terminal Inicial
            this.Root = INICIO;

            //---------------------> Producciones ------------------------------------------
            INICIO.Rule = ENCABEZADO + LISTA;

            ENCABEZADO.Rule = importar + id + punto + id + puntocoma + ENCABEZADO
                              | definir + CTIPO + puntocoma + ENCABEZADO | Empty;



            LISTA.Rule = MakeStarRule(LISTA, ESTRUC);

            /*----------------------lo que puede llevar todo el programa-----------------*/
            ESTRUC.Rule = DECLARACION
                          | ASIGNACION
                          | FUN
                          | METOD
                          | FUNPRIN
            ;



            /*---------------------------lo que llevan las funciones y metodos----------------------*/
            LISTA2.Rule = MakeStarRule(LISTA2, ESTRUC2);

            ESTRUC2.Rule = DECLARACION2
                           | ASIGNACION2
                           | LLAMADAS
                           | RETORN
                           | SENTSI
                           | SENTPARA
                           | SENTMIENTRAS
                           | SENTHASTA
                           | SENTSELECCIONA
                           | DIBEXP
                           | DIBAST
                           | DIBTS | PRINT;


            /*----------------------------puede llevar funcion principal y otros  ---------*/
            LISTA3.Rule = MakeStarRule(LISTA3, ESTRUC3);

            ESTRUC3.Rule = DECLARACION2
                           | ASIGNACION2
                           | LLAMADAS
                           | detener + puntocoma
                           | continuar + puntocoma
                           | SENTSI
                           | SENTPARA
                           | SENTMIENTRAS
                           | SENTHASTA
                           | SENTSELECCIONA
                           | DIBEXP
                           | DIBAST
                           | DIBTS
                           | PRINT
                           | RETORN;



            /*------------------------------DECLArACION y asignacion---------------------------*/


            DECLARACION.Rule = TIPO + VARIOS + igual + EXPRESION + puntocoma
                               | TIPO + VARIOS + puntocoma;


            ASIGNACION.Rule = id + igual + EXPRESION + puntocoma;

            DECLARACION2.Rule = TIPO + VARIOS + igual + EXPRESION + puntocoma
                                | TIPO + VARIOS + puntocoma;


            ASIGNACION2.Rule = id + igual + EXPRESION + puntocoma;

            VARIOS.Rule  = CTIPO + coma + VARIOS | CTIPO;
            VARIOS2.Rule = coma + EXPRESION + VARIOS2 | Empty;

            CTIPO.Rule = tString | tchar | numero | id;



            TIPO.Rule = vabool | vachar | vadouble | varint | vastring;


            /*---------------------metodos funciones----------------------*/

            FUN.Rule = TIPO + id + apar + DECLAPARA + cpar + allave + LISTA2 + cllave;

            METOD.Rule = vacio + id + apar + DECLAPARA + cpar + allave + LISTA2 + cllave;

            PARAMETROS.Rule = EXPRESION
                              | EXPRESION + coma + PARAMETROS
                              | Empty;

            DECLAPARA.Rule = TIPO + id + coma + DECLAPARA
                             | TIPO + id
                             | Empty;
            LLAMAR.Rule = id + apar + PARAMETROS + cpar;

            /*-------------------funcion principal----------------------*/

            FUNPRIN.Rule = vacio + principal + apar + cpar + allave + LISTA3 + cllave;



            /*--------------llamdas a funciones ----------*/

            LLAMADAS.Rule = id + apar + PARAMETROS + cpar + puntocoma;


            /*----------------retornar-------------*/

            RETORN.Rule = retorno + EXPRESION + puntocoma | retorno + puntocoma;



            /*----------------------sentencia si---------------*/


            SENTSI.Rule = si + apar + EXPRESION + cpar + allave + LISTA3 + cllave + SENTSINO;

            SENTSINO.Rule = sino + allave + LISTA3 + cllave | Empty;

            /*-----------------sentencia selecciona-------------*/

            SENTSELECCIONA.Rule = selecciona + apar + EXPRESION + cpar + llavea + CASO + DEFECT + cllave;

            CASO.Rule = EXPRESION + dospuntos + LISTA3 + CASO | Empty;

            DEFECT.Rule = defecto + dospuntos + LISTA3 | Empty;



            /*----------------------sentencia para-------------------*/

            SENTPARA.Rule = para + apar + vadouble + id + igual + EXPRESION + puntocoma + EXPRESION + puntocoma + masmas + cpar + allave + LISTA3 + cllave
                            | para + apar + vadouble + id + igual + EXPRESION + puntocoma + EXPRESION + puntocoma + menosmenos + cpar + allave + LISTA3 + cllave;


            /*-------------------------sentencia hasta ------------*/


            SENTHASTA.Rule = hasta + apar + EXPRESION + cpar + allave + LISTA3 + cllave;


            /*------------sentencias mientras ---------------*/


            SENTMIENTRAS.Rule = mientras + apar + EXPRESION + cpar + allave + LISTA3 + cllave;

            /*------------------------mostrar----*/

            PRINT.Rule = mostrar + apar + tString + VARIOS2 + cpar + puntocoma;

            /*----------------funcion dibujar ast-----------*/

            DIBAST.Rule = dibast + apar + id + cpar + puntocoma;

            /*--------------------funcion dibujar exp------*/

            DIBEXP.Rule = dibexp + apar + EXPRESION2 + cpar + puntocoma;


            /*------------------------------------------dibujar ts-------------------*/

            DIBTS.Rule = dibts + apar + cpar + puntocoma;

            EXPRESION.Rule = EXPRESION + or + EXPRESION
                             | EXPRESION + and + EXPRESION
                             | not + EXPRESION
                             | EXPRESION + xor + EXPRESION
                             | EXPRESION + igualigual + EXPRESION
                             | EXPRESION + diferente + EXPRESION
                             | EXPRESION + mayor + EXPRESION
                             | EXPRESION + menor + EXPRESION
                             | EXPRESION + mayorigual + EXPRESION
                             | EXPRESION + menorigual + EXPRESION
                             | EXPRESION + mas + EXPRESION
                             | EXPRESION + menos + EXPRESION
                             | EXPRESION + por + EXPRESION
                             | EXPRESION + potencia + EXPRESION
                             | EXPRESION + division + EXPRESION
                             | EXPRESION + incerteza + EXPRESION
                             | apar + EXPRESION + cpar
                             | EXPRESION + porc + EXPRESION
                             | id
                             | LLAMAR
                             | numero
                             | tString
                             | tchar
                             | trues
                             | falses
                             | menos + EXPRESION;
            // | distinto + EXPRESION



            /*-----------------para dibujar expresion-----------------*/

            EXPRESION2.Rule = EXPRESION2 + or + EXPRESION2
                              | EXPRESION2 + and + EXPRESION2
                              | not + EXPRESION2
                              | EXPRESION2 + xor + EXPRESION2
                              | EXPRESION2 + diferente + EXPRESION2
                              | EXPRESION2 + mayor + EXPRESION2
                              | EXPRESION2 + menor + EXPRESION2
                              | EXPRESION2 + mayorigual + EXPRESION2
                              | EXPRESION2 + menorigual + EXPRESION2
                              | EXPRESION2 + mas + EXPRESION2
                              | EXPRESION2 + menos + EXPRESION2
                              | EXPRESION2 + por + EXPRESION2
                              | EXPRESION2 + potencia + EXPRESION2
                              | EXPRESION2 + division + EXPRESION2
                              | EXPRESION2 + incerteza + EXPRESION2
                              | apar + EXPRESION2 + cpar
                              | EXPRESION2 + igualigual + EXPRESION2
                              | EXPRESION2 + porc + EXPRESION2
                              | id
                              | LLAMAR
                              | numero
                              | tString
                              | tchar
                              | trues
                              | falses
                              | menos + EXPRESION;
            // | distinto + EXPRESION



            //---------------------> Definir Asociatividad
            RegisterOperators(1, Associativity.Left, "||");             //OR
            RegisterOperators(2, Associativity.Left, "&&");             //AND
            RegisterOperators(7, Associativity.Left, "!");              //NOT
            RegisterOperators(7, Associativity.Left, "|&");             //NOT
            RegisterOperators(5, Associativity.Left, "+", "-");         //MAS, MENOS
            RegisterOperators(6, Associativity.Left, "*", "/", "%");    //POR, DIVIDIR
            RegisterOperators(6, Associativity.Right, "^");             //POTENCIA


            ESTRUC.ErrorRule  = SyntaxError + ESTRUC;
            ESTRUC2.ErrorRule = SyntaxError + ESTRUC2;

            ESTRUC3.ErrorRule = SyntaxError + ESTRUC3;
        }
Esempio n. 19
0
        public SLAngGrammer()
            : base()
        {
            StringLiteral      stringLiteral     = TerminalFactory.CreateCSharpString("StringLiteral");
            StringLiteral      charLiteral       = TerminalFactory.CreateCSharpChar("CharLiteral");
            NumberLiteral      number            = TerminalFactory.CreateCSharpNumber("Number");
            IdentifierTerminal identifier        = TerminalFactory.CreateCSharpIdentifier("Identifier");
            CommentTerminal    delimitedComment  = new CommentTerminal("DelimitedComment", "/[", "]/");
            CommentTerminal    SingleLineComment = new CommentTerminal("SingleLineComment", "--", "\r", "\n", "\u2085", "\u2028", "\u2029");

            NonGrammarTerminals.Add(SingleLineComment);
            NonGrammarTerminals.Add(delimitedComment);

            #region Terminals
            KeyTerm colon      = ToTerm(":");
            KeyTerm dot        = ToTerm(".");
            KeyTerm comma      = ToTerm(",");
            KeyTerm propertyIs = ToTerm("->");
            KeyTerm lbr        = ToTerm("{");
            KeyTerm rbr        = ToTerm("}");
            KeyTerm lpar       = ToTerm("(");
            KeyTerm rpar       = ToTerm(")");
            KeyTerm scopeIn    = ToTerm("::");
            KeyTerm suchThat   = ToTerm("|");
            KeyTerm _package   = ToTerm("package");
            KeyTerm context    = ToTerm("context");
            KeyTerm body       = ToTerm("body");
            KeyTerm def        = ToTerm("def");
            KeyTerm derive     = ToTerm("derive");
            KeyTerm In         = ToTerm("in");
            KeyTerm inv        = ToTerm("inv");
            KeyTerm let        = ToTerm("let");
            KeyTerm post       = ToTerm("post");
            KeyTerm pre        = ToTerm("pre");
            KeyTerm Static     = ToTerm("static");
            KeyTerm self       = ToTerm("self");
            KeyTerm result     = ToTerm("result");
            KeyTerm equalsTo   = ToTerm("=");
            KeyTerm _null      = ToTerm("null");
            KeyTerm invalid    = ToTerm("invalid");
            KeyTerm not        = ToTerm("not");
            KeyTerm and        = ToTerm("and");
            KeyTerm or         = ToTerm("or");
            KeyTerm xor        = ToTerm("xor");
            #endregion

            #region NonTerminal
            var specification       = new NonTerminal("specification");
            var specificationBody   = new NonTerminal("specificationBody");
            var package             = new NonTerminal("package");
            var packages            = new NonTerminal("packages");
            var oclPackage          = new NonTerminal("oclPackage");
            var emofOclPackage      = new NonTerminal("emofOclPackage");
            var packageBody         = new NonTerminal("packageBody");
            var packageBodyItem     = new NonTerminal("packageBodyItem");
            var contextExp          = new NonTerminal("contextExp");
            var classType           = new NonTerminal("classType");
            var enumeration         = new NonTerminal("enumeration");
            var primitive           = new NonTerminal("primitive");
            var primitiveType       = new NonTerminal("primitiveType");
            var primitiveTypes      = new NonTerminal("primitiveTypes");
            var delimitedIdentifier = new NonTerminal("delimitedIdentifier");
            var classSignature      = new NonTerminal("classSignature");
            var classBody           = new NonTerminal("classBody");
            var classBodyItem       = new NonTerminal("classBodyItem");
            var invExp                   = new NonTerminal("invExp");
            var functionDefination       = new NonTerminal("functionDefination");
            var attributeDiclaration     = new NonTerminal("attributeDiclaration");
            var emofAttributeDiclaration = new NonTerminal("emofAttributeDiclaration");
            var oclAttributeDiclaration  = new NonTerminal("oclAttributeDiclaration");
            var type                        = new NonTerminal("type");
            var expression                  = new NonTerminal("expression");
            var customType                  = new NonTerminal("customType");
            var collectionTpye              = new NonTerminal("collectionTpye");
            var fullType                    = new NonTerminal("fullType");
            var globalType                  = new NonTerminal("globalType");
            var setType                     = new NonTerminal("setType");
            var orderedSetType              = new NonTerminal("orderedSetType");
            var sequenceType                = new NonTerminal("sequenceType");
            var bagType                     = new NonTerminal("bagType");
            var functionSignature           = new NonTerminal("functionSignature");
            var functionSignatureBody       = new NonTerminal("functionSignatureBody");
            var functionBody                = new NonTerminal("functionBody");
            var oclFunctionSignature        = new NonTerminal("oclFunctionSignature");
            var emofFunctionSignature       = new NonTerminal("emofFunctionSignature");
            var argumentList                = new NonTerminal("argumentList");
            var variableDiclaration         = new NonTerminal("variableDiclaration");
            var emofFunctionBody            = new NonTerminal("emofFunctionBody");
            var oclFunctionBody             = new NonTerminal("oclFunctionBody");
            var singleValueCollectionMember = new NonTerminal("singleValueCollectionMember");
            var booleanValueCollection      = new NonTerminal("booleanValueCollection");
            var letExp                      = new NonTerminal("letExp");
            var ifThenElseExp               = new NonTerminal("ifThenElseExp");
            var collectionValueExp          = new NonTerminal("collectionValueExp");
            var sum                        = new NonTerminal("sum");
            var size                       = new NonTerminal("size");
            var first                      = new NonTerminal("first");
            var last                       = new NonTerminal("last");
            var at                         = new NonTerminal("at");
            var indexOf                    = new NonTerminal("indexOf");
            var countOperation             = new NonTerminal("countOperation");
            var maxOperation               = new NonTerminal("maxOperation");
            var minOperation               = new NonTerminal("minOperation");
            var valueExp                   = new NonTerminal("valueExp");
            var includesOperation          = new NonTerminal("includesOperation");
            var includesAllOperation       = new NonTerminal("includesAllOperation");
            var excludesOperation          = new NonTerminal("excludesOperation");
            var excludesAllOperation       = new NonTerminal("excludesAllOperation");
            var isEmptyOperation           = new NonTerminal("isEmptyOperation");
            var notEmptyOperation          = new NonTerminal("notEmptyOperation");
            var specialIteratorBodyExp     = new NonTerminal("specialIteratorBodyExp");
            var existsExp                  = new NonTerminal("existsExp");
            var forAllExp                  = new NonTerminal("forAllExp");
            var isUniqueExp                = new NonTerminal("isUniqueExp");
            var anyExp                     = new NonTerminal("anyExp");
            var oneExp                     = new NonTerminal("oneExp");
            var selectExp                  = new NonTerminal("selectExp");
            var includingOperation         = new NonTerminal("includingOperation");
            var excludingOperation         = new NonTerminal("excludingOperation");
            var collect                    = new NonTerminal("collect");
            var subOrderedSet              = new NonTerminal("subOrderedSet");
            var symmetricDifference        = new NonTerminal("symmetricDifference");
            var prepend                    = new NonTerminal("prepend");
            var append                     = new NonTerminal("append");
            var insertAt                   = new NonTerminal("insertAt");
            var intersection               = new NonTerminal("intersection");
            var union                      = new NonTerminal("union");
            var asBag                      = new NonTerminal("asBag");
            var asSequence                 = new NonTerminal("asSequence");
            var asOrderdSet                = new NonTerminal("asOrderdSet");
            var asSet                      = new NonTerminal("asSet");
            var flatten                    = new NonTerminal("flatten");
            var subSequence                = new NonTerminal("subSequence");
            var andExp                     = new NonTerminal("andExp");
            var orExp                      = new NonTerminal("orExp");
            var notExp                     = new NonTerminal("notExp");
            var xorExp                     = new NonTerminal("xorExp");
            var impliesExp                 = new NonTerminal("impliesExp");
            var comparisonOperator         = new NonTerminal("comparisonOperator");
            var arithmaticOperator         = new NonTerminal("arithmaticOperator");
            var oclInvExp                  = new NonTerminal("oclInvExp");
            var emofInvExp                 = new NonTerminal("emofInvExp");
            var operationContextExp        = new NonTerminal("operationContextExp");
            var attributeContextExp        = new NonTerminal("attributeContextExp");
            var classContextExp            = new NonTerminal("classContextExp");
            var classContextSignature      = new NonTerminal("classContextSignature");
            var attributeContextbody       = new NonTerminal("attributeContextbody");
            var attributeContextbodyItem   = new NonTerminal("attributeContextbodyItem");
            var deriveExp                  = new NonTerminal("deriveExp");
            var initExp                    = new NonTerminal("initExp");
            var operationContextBodyExps   = new NonTerminal("operationContextBodyExps");
            var operationContextSignature  = new NonTerminal("operationContextSignature");
            var operationContextBodyItem   = new NonTerminal("operationContextBodyItem");
            var preCondition               = new NonTerminal("preCondition");
            var postCondition              = new NonTerminal("postCondition");
            var bodyExp                    = new NonTerminal("bodyExp");
            var iterateExp                 = new NonTerminal("iterateExp");
            var productExp                 = new NonTerminal("productExp");
            var tupleExp                   = new NonTerminal("tupleExp");
            var rejectExp                  = new NonTerminal("rejectExp");
            var collection                 = new NonTerminal("collection");
            var tuplElementList            = new NonTerminal("tuplElementList");
            var tupleElement               = new NonTerminal("tupleElement");
            var binaryOperator             = new NonTerminal("binaryOperator");
            var parameterList              = new NonTerminal("parameterList");
            var structuralExp              = new NonTerminal("structuralExp");
            var setLiteral                 = new NonTerminal("setLiteral");
            var bagLiteral                 = new NonTerminal("orderedSetLiteral");
            var orderedSetLiteral          = new NonTerminal("");
            var sequenceLiteral            = new NonTerminal("sequenceLiteral");
            var tupleLiteral               = new NonTerminal("tupleLiteral");
            var literalList                = new NonTerminal("literalList");
            var iteratorList               = new NonTerminal("iteratorList");
            var iteratorInitializationList = new NonTerminal("iteratorInitializationList");
            var iteratorInitialization     = new NonTerminal("iteratorInitialization");
            var collectionValue            = new NonTerminal("collectionValue");
            var ArrayType                  = new NonTerminal("ArrayType");
            var binaryBooleanOperator      = new NonTerminal("binaryBooleanOperator");
            var oclIsTypeOf                = new NonTerminal("oclIsTypeOf");
            var ValueExp                   = new NonTerminal("ValueExp");
            var unValueExp                 = new NonTerminal("unValueExp");
            var instanceMemberAccess       = new NonTerminal("instanceMemberAccess");
            var instanceMathodAccess       = new NonTerminal("instanceMathodAccess");
            #endregion

            #region Rules

            #region specification
            specification.Rule     = "specification" + identifier + lbr + specificationBody + rbr;
            specificationBody.Rule = MakePlusRule(packages, package);
            #endregion

            #region package
            package.Rule         = oclPackage | emofOclPackage;
            oclPackage.Rule      = _package + identifier + packageBody + "endpackage";
            emofOclPackage.Rule  = _package + identifier + lbr + packageBody + rbr;
            packageBody.Rule     = MakeStarRule(packageBody, null, packageBodyItem);
            packageBodyItem.Rule = primitive | enumeration | classType | contextExp | package;
            #endregion

            #region primitive
            primitive.Rule      = "primitive" + primitiveTypes + identifier + "IDENTICAL";
            primitiveTypes.Rule = ToTerm("Real") | ToTerm("Integer") | ToTerm("String") | ToTerm("Boolean");
            #endregion

            #region enumeration
            enumeration.Rule         = "enumeration" + identifier + lbr + delimitedIdentifier + rbr;
            delimitedIdentifier.Rule = MakePlusRule(delimitedIdentifier, comma, identifier);
            #endregion

            #region class
            classType.Rule      = classSignature + lbr + classBody + rbr;
            classSignature.Rule = ToTerm("class") + identifier
                                  | ToTerm("abstract") + ToTerm("class") + identifier
                                  | ToTerm("abstract") + ToTerm("class") + identifier + ToTerm("extends") + identifier
                                  | ToTerm("class") + identifier + ToTerm("extends") + type;
            classBody.Rule     = MakeStarRule(classBody, classBodyItem);
            classBodyItem.Rule = attributeDiclaration | functionDefination | invExp;
            #endregion

            #region attribute
            attributeDiclaration.Rule    = oclAttributeDiclaration | emofAttributeDiclaration;
            oclAttributeDiclaration.Rule = def + colon + identifier + type + ReduceHere()
                                           | def + colon + identifier + type + PreferShiftHere() + equalsTo + expression + ReduceHere()
                                           | def + colon + "attr" + identifier + type + PreferShiftHere() + equalsTo + expression + ReduceHere()
                                           | def + colon + "attr" + identifier + type + ReduceHere();
            emofAttributeDiclaration.Rule = identifier + colon + type + ReduceHere()
                                            | ToTerm("component") + identifier + colon + type + ToTerm("opposite") + identifier + ReduceHere()
                                            | ToTerm("component") + identifier + colon + type + ToTerm("unique") + ToTerm("opposite") + identifier + ReduceHere()
                                            | identifier + colon + type + equalsTo + expression + ReduceHere()
                                            | identifier + colon + type + ToTerm("opposite") + identifier + ReduceHere()
                                            | identifier + colon + type + ToTerm("unique") + ToTerm("opposite") + identifier + ReduceHere()
                                            | identifier + colon + type + ToTerm("unique") + ReduceHere();
            #endregion

            #region type
            type.Rule       = primitiveTypes | customType;
            customType.Rule = fullType | globalType | ArrayType | collectionTpye | tupleExp;
            fullType.Rule   = identifier + scopeIn + fullType | identifier + ReduceHere();
            globalType.Rule = PreferShiftHere() + scopeIn + fullType
                              | PreferShiftHere() + scopeIn + ArrayType;
            ArrayType.Rule = fullType + "[" + "*" + "]"
                             | fullType + "[" + identifier + "]"
                             | fullType + "[" + number + "]"
                             | fullType + "[" + number + comma + number + "]"
                             | fullType + "[" + number + comma + "*" + "]";
            collectionTpye.Rule = setType | orderedSetType | sequenceType | bagType | collection;
            setType.Rule        = "Set(" + customType + ")";
            orderedSetType.Rule = "OrderedSet(" + customType + ")";
            sequenceType.Rule   = "Sequence(" + customType + ")";
            bagType.Rule        = "Bag(" + customType + ")";
            collection.Rule     = "Collection(" + customType + ")";
            tupleExp.Rule       = "Tuple" + lbr + argumentList + rbr;
            #endregion

            #region function
            functionDefination.Rule    = functionSignature + functionBody;
            functionSignature.Rule     = oclFunctionSignature | emofFunctionSignature;
            oclFunctionSignature.Rule  = def + colon + functionSignatureBody;
            functionSignatureBody.Rule = identifier + lpar + argumentList + rpar + colon + type
                                         | identifier + lpar + argumentList + rpar + colon + type + ToTerm("ordered") + ToTerm("unique")
                                         | identifier + lpar + argumentList + rpar + colon;
            argumentList.Rule          = MakeStarRule(argumentList, comma, variableDiclaration);
            variableDiclaration.Rule   = identifier + PreferShiftHere() + colon + type;
            emofFunctionSignature.Rule = functionSignatureBody;
            functionBody.Rule          = oclFunctionBody | emofFunctionBody;
            oclFunctionBody.Rule       = equalsTo + expression;
            emofFunctionBody.Rule      = equalsTo + lbr + expression + rbr;
            #endregion

            #region expression
            expression.Rule = valueExp | structuralExp;
            #endregion

            #region valueExp
            valueExp.Rule = // ValueExp + ReduceHere() |
                            unValueExp + ReduceHere()
                            | valueExp + PreferShiftHere() + binaryOperator + valueExp
                            | ToTerm("not") + valueExp
                            | lpar + valueExp + rpar;
            #endregion

            #region unValueExp

            unValueExp.Rule = booleanValueCollection
                              | ToTerm("false") | ToTerm("true")
                              | collectionValue
                              | tupleLiteral
                              | singleValueCollectionMember
                              | collectionValueExp
                              | iterateExp
                              | stringLiteral
                              | charLiteral
                              | number
                              | self
                              | oclIsTypeOf
                              | unValueExp + lpar + parameterList + rpar
                              | instanceMemberAccess
                              | instanceMathodAccess
                              | ToTerm("-") + number;
            #endregion

            #region ValueExp
            ValueExp.Rule = fullType + dot + instanceMemberAccess
                            | globalType + dot + instanceMemberAccess
                            | ValueExp + dot + identifier + lpar + parameterList + rpar;
            #endregion

            #region instanceMemberAccess
            instanceMemberAccess.Rule = MakePlusRule(instanceMemberAccess, dot, identifier);
            instanceMathodAccess.Rule = unValueExp + dot + identifier + lpar + parameterList + rpar;
            #endregion

            #region parameterList
            parameterList.Rule = MakeStarRule(parameterList, comma, expression);
            #endregion

            #region booleanExp
            booleanValueCollection.Rule = includesOperation | includesAllOperation | excludesOperation | excludesAllOperation
                                          | isEmptyOperation | notEmptyOperation | existsExp | forAllExp | isUniqueExp | anyExp | oneExp;
            #endregion

            #region oclBuildInMethods
            oclIsTypeOf.Rule = valueExp + dot + ToTerm("oclIsTypeOf") + lpar + type + rpar;
            #endregion

            #region binaryOperator

            binaryOperator.Rule        = comparisonOperator | arithmaticOperator | binaryBooleanOperator;
            arithmaticOperator.Rule    = ToTerm("/") | ToTerm("div") | ToTerm("*") | ToTerm("+") | ToTerm("-");
            comparisonOperator.Rule    = ToTerm(">") | ToTerm("<") | ToTerm(">=") | ToTerm("<=") | ToTerm("<>") | equalsTo;
            binaryBooleanOperator.Rule = ToTerm("and") | ToTerm("or") | ToTerm("xor") | ToTerm("implies");

            #endregion

            #region booleanValueCollection
            includesOperation.Rule    = valueExp + PreferShiftHere() + propertyIs + ToTerm("includes") + lpar + valueExp + rpar;
            includesAllOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("includesAll") + lpar + identifier + rpar;
            excludesOperation.Rule    = valueExp + PreferShiftHere() + propertyIs + ToTerm("excludes") + lpar + identifier + rpar;
            excludesAllOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("excludesAll") + lpar + identifier + rpar;
            isEmptyOperation.Rule     = valueExp + PreferShiftHere() + propertyIs + ToTerm("isEmpty") + lpar + rpar;
            notEmptyOperation.Rule    = valueExp + PreferShiftHere() + propertyIs + ToTerm("notEmpty") + lpar + rpar;
            existsExp.Rule            = valueExp + PreferShiftHere() + propertyIs + ToTerm("exists") + lpar + specialIteratorBodyExp + rpar;
            forAllExp.Rule            = valueExp + PreferShiftHere() + propertyIs + ToTerm("forAll") + lpar + specialIteratorBodyExp + rpar;
            isUniqueExp.Rule          = valueExp + PreferShiftHere() + propertyIs + ToTerm("isUnique") + lpar + specialIteratorBodyExp + rpar;
            anyExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("any") + lpar + specialIteratorBodyExp + rpar;
            oneExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("one") + lpar + specialIteratorBodyExp + rpar;
            specialIteratorBodyExp.Rule = delimitedIdentifier + colon + type + suchThat + valueExp
                                          | argumentList + suchThat + valueExp
                                          | valueExp;
            #endregion

            #region collectionValue
            collectionValue.Rule = setLiteral | bagLiteral | orderedSetLiteral | sequenceLiteral;
            setLiteral.Rule      = "Set" + lbr + literalList + rbr
                                   | "Set" + lpar + type + rpar + lbr + literalList + rbr;
            bagLiteral.Rule = "Bag" + lbr + literalList + rbr
                              | "Bag" + lpar + type + rpar + lbr + literalList + rbr;
            orderedSetLiteral.Rule = "OrderedSet" + lbr + literalList + rbr
                                     | "OrderedSet" + lpar + type + rpar + lbr + literalList + rbr;
            sequenceLiteral.Rule = "Sequence" + lbr + literalList + rbr
                                   | "Sequence" + lpar + type + rpar + lbr + literalList + rbr;
            literalList.Rule        = MakeStarRule(literalList, comma, valueExp);
            tupleLiteral.Rule       = "Tuple" + lbr + tuplElementList + rbr;
            tuplElementList.Rule    = MakePlusRule(tuplElementList, comma, tupleElement);
            tupleElement.Rule       = variableDiclaration + equalsTo + valueExp | identifier + equalsTo + valueExp;
            collectionValueExp.Rule = includingOperation | excludingOperation | selectExp | rejectExp
                                      | union | intersection | insertAt | append | prepend | symmetricDifference | subOrderedSet | collect | productExp
                                      | subSequence | flatten | asSet | asOrderdSet | asSequence | asBag;
            includingOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("including") + lpar + identifier + rpar;
            excludingOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("excluding") + lpar + identifier + rpar;
            selectExp.Rule          = valueExp + PreferShiftHere() + propertyIs + ToTerm("select") + lpar + specialIteratorBodyExp + rpar;
            rejectExp.Rule          = valueExp + PreferShiftHere() + propertyIs + ToTerm("reject") + lpar + specialIteratorBodyExp + rpar;
            union.Rule               = valueExp + PreferShiftHere() + propertyIs + ToTerm("union") + lpar + valueExp + rpar;
            intersection.Rule        = valueExp + PreferShiftHere() + propertyIs + ToTerm("intersection") + lpar + identifier + rpar;
            insertAt.Rule            = valueExp + PreferShiftHere() + propertyIs + ToTerm("insertAt") + lpar + number + comma + identifier + rpar;
            append.Rule              = valueExp + PreferShiftHere() + propertyIs + ToTerm("append") + lpar + identifier + rpar;
            prepend.Rule             = valueExp + PreferShiftHere() + propertyIs + ToTerm("prepend") + lpar + identifier + rpar;
            symmetricDifference.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("symmetricDifference") + lpar + identifier + rpar;
            subOrderedSet.Rule       = valueExp + PreferShiftHere() + propertyIs + ToTerm("subOrderedSet") + lpar + number + comma + number + rpar;
            collect.Rule             = valueExp + PreferShiftHere() + propertyIs + ToTerm("collect") + lpar + specialIteratorBodyExp + rpar
                                       | valueExp + PreferShiftHere() + propertyIs + ToTerm("collect") + lpar + identifier + rpar
                                       | valueExp + dot + identifier + lpar + argumentList + rpar
                                       | valueExp + PreferShiftHere() + propertyIs + identifier + lpar + argumentList + rpar;
            productExp.Rule  = valueExp + PreferShiftHere() + propertyIs + ToTerm("product") + lpar + identifier + rpar;
            subSequence.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("subSequence") + lpar + number + comma + number + rpar;
            flatten.Rule     = valueExp + PreferShiftHere() + propertyIs + ToTerm("flatten") + lpar + rpar;
            asSet.Rule       = valueExp + PreferShiftHere() + propertyIs + ToTerm("asSet") + lpar + rpar;
            asOrderdSet.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("asOrderdSet") + lpar + rpar;
            asSequence.Rule  = valueExp + PreferShiftHere() + propertyIs + ToTerm("asSequence") + lpar + rpar;
            asBag.Rule       = valueExp + PreferShiftHere() + propertyIs + ToTerm("asBag") + lpar + rpar;

            #endregion

            #region singleValueCollectionMember
            singleValueCollectionMember.Rule = maxOperation | minOperation | countOperation | at | indexOf | first | last | sum | size;
            maxOperation.Rule   = valueExp + PreferShiftHere() + propertyIs + "max" + lpar + rpar;
            minOperation.Rule   = valueExp + PreferShiftHere() + propertyIs + "min" + lpar + rpar;
            countOperation.Rule = valueExp + PreferShiftHere() + propertyIs + "count" + lpar + identifier + rpar;
            at.Rule             = valueExp + PreferShiftHere() + propertyIs + "at" + lpar + identifier + rpar;
            indexOf.Rule        = valueExp + PreferShiftHere() + propertyIs + "indexOf" + lpar + identifier + rpar;
            first.Rule          = valueExp + PreferShiftHere() + propertyIs + "first" + lpar + rpar;
            last.Rule           = valueExp + PreferShiftHere() + propertyIs + "last" + lpar + rpar;
            sum.Rule            = valueExp + PreferShiftHere() + propertyIs + "sum" + lpar + rpar;
            size.Rule           = valueExp + PreferShiftHere() + propertyIs + "size" + lpar + rpar;
            #endregion

            #region iterateExp
            iterateExp.Rule = valueExp + PreferShiftHere() + propertyIs + "iterate" + lpar + iteratorList + ";"
                              + iteratorInitializationList + suchThat + expression + rpar;
            iteratorList.Rule = MakePlusRule(iteratorList, comma, variableDiclaration);
            iteratorInitializationList.Rule = MakePlusRule(iteratorInitializationList, comma, iteratorInitialization);
            iteratorInitialization.Rule     = variableDiclaration + equalsTo + valueExp;
            #endregion

            #region structuralExp
            structuralExp.Rule = ifThenElseExp | letExp;
            #endregion

            #region ifThenElseExp
            ifThenElseExp.Rule = "if" + valueExp + "then" + expression + "endif"
                                 | "if" + valueExp + "then" + expression + "else" + expression + "endif";
            #endregion

            #region letExp
            letExp.Rule = let + variableDiclaration + equalsTo + valueExp + In + expression
                          | let + identifier + equalsTo + valueExp + In + expression;
            #endregion

            #region invExp
            invExp.Rule    = oclInvExp | emofInvExp;
            oclInvExp.Rule = inv + identifier + colon + expression
                             | inv + colon + expression;
            emofInvExp.Rule = "invariant" + lbr + expression + rbr;
            #endregion

            #region contextExp
            contextExp.Rule = classContextExp | attributeContextExp | operationContextExp;
            #endregion

            #region classContextExp
            classContextExp.Rule       = classContextSignature + classBody;
            classContextSignature.Rule = context + type
                                         | context + identifier + colon + type;
            classBody.Rule     = MakePlusRule(classBody, null, classBodyItem);
            classBodyItem.Rule = invExp | attributeDiclaration | functionDefination;
            #endregion

            #region attributeContextExp
            attributeContextExp.Rule      = context + type + colon + type + attributeContextbody;
            attributeContextbody.Rule     = MakePlusRule(attributeContextbody, null, attributeContextbodyItem);
            attributeContextbodyItem.Rule = initExp | deriveExp;
            #endregion

            #region initExp
            initExp.Rule = ToTerm("init") + colon + equalsTo + valueExp;
            #endregion

            #region deriveExp
            deriveExp.Rule = ToTerm("derive") + colon + expression;
            #endregion

            #region operationContextExp
            operationContextExp.Rule       = operationContextSignature + invExp + operationContextBodyExps;
            operationContextSignature.Rule = context + customType + PreferShiftHere() + scopeIn + functionSignature;
            operationContextBodyExps.Rule  = MakePlusRule(operationContextBodyExps, null, operationContextBodyItem);
            operationContextBodyItem.Rule  = preCondition | bodyExp | postCondition;
            #endregion

            #region preCondition
            preCondition.Rule = pre + identifier + colon + valueExp
                                | pre + colon + valueExp;
            #endregion

            #region bodyExp
            bodyExp.Rule = body + colon + expression;
            #endregion

            #region postCondition
            postCondition.Rule = post + colon + valueExp
                                 | post + identifier + colon + valueExp;
            #endregion

            #endregion

            #region Operator,punctuation
            MarkPunctuation(",", "(", ")", "{", "}", "[", "]", ":");
            MarkMemberSelect(".", "->"); //dot, propertyIs);
            RegisterOperators(1, lpar, rpar);
            RegisterOperators(2, "let", "in");
            RegisterOperators(3, letExp, In);
            RegisterOperators(4, dot, scopeIn);
            RegisterOperators(5, not);
            RegisterOperators(6, "*", "/");
            RegisterOperators(7, letExp, In);
            RegisterOperators(8, dot, scopeIn);
            RegisterOperators(9, "+", "-");
            RegisterOperators(10, "<", ">", "<=", ">=");
            RegisterOperators(11, "=", "<>");
            RegisterOperators(12, and);
            RegisterOperators(12, "div", "implies");
            RegisterOperators(13, or);
            RegisterOperators(14, xor);
            RegisterOperators(15, "=", "<>");
            #endregion
            this.Root = specification;
        }
Esempio n. 20
0
        public GramaticaPython()
            : base(caseSensitive: false)
        {
            #region expresiones regulares

            var           identificador = TerminalFactory.CreateCSharpIdentifier("identificador");
            var           numero        = TerminalFactory.CreateCSharpNumber("numero");
            var           val_false     = Constantes.falso;
            var           val_true      = Constantes.verdadero;
            StringLiteral cadena        = new StringLiteral("cadena", "\"");
            var           caracter      = TerminalFactory.CreateCSharpChar(Constantes.caracter);

            CommentTerminal COMENT_BLOQUE = new CommentTerminal("COMENTARIO BLOQUE", "/*", "*/");
            CommentTerminal COMENT_LINEA  = new CommentTerminal("COMENTARIO LINEA", "//", "\n", "\r\n");
            NonGrammarTerminals.Add(COMENT_BLOQUE);
            NonGrammarTerminals.Add(COMENT_LINEA);

            #endregion

            NonTerminal EXPRESION   = new NonTerminal(Constantes.expresion);
            NonTerminal DECIMAL     = new NonTerminal(Constantes.tipoDecimal);
            NonTerminal ENTERO      = new NonTerminal(Constantes.tipoEntero);
            NonTerminal CADENA      = new NonTerminal(Constantes.tipoCadena);
            NonTerminal CHAR        = new NonTerminal(Constantes.tipoChar);
            NonTerminal BOOLEANO    = new NonTerminal(Constantes.tipoBool);
            NonTerminal SIMB_ARIT   = new NonTerminal(Constantes.simb_arit);
            NonTerminal SIMB_REL    = new NonTerminal(Constantes.simb_rel);
            NonTerminal UNARIO      = new NonTerminal(Constantes.unario);
            NonTerminal ID          = new NonTerminal(Constantes.id);
            NonTerminal NEGATIVO    = new NonTerminal(Constantes.negativo);
            NonTerminal RELACIONAL  = new NonTerminal(Constantes.relacional);
            NonTerminal ARITMETICA  = new NonTerminal(Constantes.aritmetica);
            NonTerminal LOGICA      = new NonTerminal(Constantes.logica);
            NonTerminal LLAMADA     = new NonTerminal(Constantes.llamada);
            NonTerminal POSVECTOR   = new NonTerminal(Constantes.posvector);
            NonTerminal LISTAPUNTOS = new NonTerminal(Constantes.listapuntos);
            NonTerminal SIMB_LOG    = new NonTerminal(Constantes.simb_log);
            NonTerminal MAS_MAS     = new NonTerminal(Constantes.masmas);
            NonTerminal MENOS_MENOS = new NonTerminal(Constantes.menosmenos);
            NonTerminal ASIG_ARRAY  = new NonTerminal(Constantes.asig_array);
            NonTerminal termino     = new NonTerminal(Constantes.termino);

            NonTerminal L_IDS          = new NonTerminal(Constantes.listaIds);
            NonTerminal SUMA           = new NonTerminal(Constantes.suma);
            NonTerminal RESTA          = new NonTerminal(Constantes.resta);
            NonTerminal MULTIPLICACION = new NonTerminal(Constantes.multiplicacion);
            NonTerminal DIVISION       = new NonTerminal(Constantes.division);
            NonTerminal POTENCIA       = new NonTerminal(Constantes.potencia);
            NonTerminal MENOR          = new NonTerminal(Constantes.menor);
            NonTerminal MENORIGUAL     = new NonTerminal(Constantes.menorIgual);
            NonTerminal MAYOR          = new NonTerminal(Constantes.mayor);
            NonTerminal MAYORIGUAL     = new NonTerminal(Constantes.mayorIgual);
            NonTerminal IGUALIGUAL     = new NonTerminal(Constantes.igualIgual);
            NonTerminal DISTINTOA      = new NonTerminal(Constantes.distintoA);
            NonTerminal XOR            = new NonTerminal(Constantes.xorJava);
            NonTerminal AND            = new NonTerminal(Constantes.andJava);
            NonTerminal NOT            = new NonTerminal(Constantes.notJavaPython);
            NonTerminal OR             = new NonTerminal(Constantes.orJava);
            NonTerminal INSTANCIA      = new NonTerminal(Constantes.instancia);
            NonTerminal POSICION       = new NonTerminal(Constantes.posicion);
            NonTerminal FILA           = new NonTerminal(Constantes.fila);
            NonTerminal LPOSICIONES    = new NonTerminal(Constantes.lposiciones);
            NonTerminal LEXPRESIONES   = new NonTerminal(Constantes.lexpresiones);
            NonTerminal LFILAS         = new NonTerminal(Constantes.lfilas);


            #region expresion


            POSICION.Rule = ToTerm("[") + EXPRESION + "]";

            LPOSICIONES.Rule = MakePlusRule(LPOSICIONES, POSICION);

            FILA.Rule = ToTerm("{") + LEXPRESIONES + "}";

            LEXPRESIONES.Rule = MakePlusRule(LEXPRESIONES, ToTerm(","), EXPRESION);

            LFILAS.Rule = MakePlusRule(LFILAS, ToTerm(","), FILA);

            DECIMAL.Rule  = numero;
            ENTERO.Rule   = numero;
            CADENA.Rule   = cadena;
            ID.Rule       = identificador;
            CHAR.Rule     = caracter;
            BOOLEANO.Rule = ToTerm(val_false)
                            | ToTerm(val_true);



            ARITMETICA.Rule = SUMA
                              | RESTA
                              | MULTIPLICACION
                              | DIVISION
                              | POTENCIA;

            RELACIONAL.Rule = MENOR
                              | MAYOR
                              | MENORIGUAL
                              | MAYORIGUAL
                              | DISTINTOA
                              | IGUALIGUAL;

            LOGICA.Rule = XOR
                          | OR
                          | AND
                          | NOT;



            SUMA.Rule           = EXPRESION + ToTerm(Constantes.suma) + EXPRESION;
            RESTA.Rule          = EXPRESION + ToTerm(Constantes.resta) + EXPRESION;
            MULTIPLICACION.Rule = EXPRESION + ToTerm(Constantes.multiplicacion) + EXPRESION;
            DIVISION.Rule       = EXPRESION + ToTerm(Constantes.division) + EXPRESION;
            POTENCIA.Rule       = EXPRESION + ToTerm(Constantes.potencia) + EXPRESION;
            MENOR.Rule          = EXPRESION + ToTerm(Constantes.menor) + EXPRESION;
            MENORIGUAL.Rule     = EXPRESION + ToTerm(Constantes.menorIgual) + EXPRESION;
            MAYOR.Rule          = EXPRESION + ToTerm(Constantes.mayor) + EXPRESION;
            MAYORIGUAL.Rule     = EXPRESION + ToTerm(Constantes.mayorIgual) + EXPRESION;
            IGUALIGUAL.Rule     = EXPRESION + ToTerm(Constantes.igualIgual) + EXPRESION;
            DISTINTOA.Rule      = EXPRESION + ToTerm(Constantes.distintoA) + EXPRESION;
            XOR.Rule            = EXPRESION + ToTerm(Constantes.xorJava) + EXPRESION;
            AND.Rule            = EXPRESION + ToTerm(Constantes.andJava) + EXPRESION;
            NOT.Rule            = ToTerm(Constantes.notJavaPython) + EXPRESION;
            OR.Rule             = EXPRESION + ToTerm(Constantes.orJava) + EXPRESION;
            INSTANCIA.Rule      = Constantes.nuevo + identificador + "(" + LEXPRESIONES + ")"
                                  | Constantes.nuevo + identificador + "(" + ")";

            UNARIO.Rule = MAS_MAS
                          | MENOS_MENOS;

            MAS_MAS.Rule = identificador + ToTerm(Constantes.masmas);

            MENOS_MENOS.Rule = identificador + ToTerm(Constantes.menosmenos);


            NEGATIVO.Rule = ToTerm("-") + EXPRESION;

            termino.Rule = //ARITMETICA
                           //| RELACIONAL
                           // | LOGICA
                           DECIMAL
                           | ENTERO
                           | ID
                           | CADENA
                           | BOOLEANO
                           | CHAR;
            //| LLAMADA
            //| POSVECTOR
            //| UNARIO
            //| ToTerm("(") + EXPRESION + ")"
            //| NEGATIVO
            //| "{" + LFILAS + "}"
            //| INSTANCIA;

            LLAMADA.Rule = identificador + ToTerm("(") + LEXPRESIONES + ")"
                           | identificador + ToTerm("(") + ")";


            POSVECTOR.Rule = identificador + LPOSICIONES;

            L_IDS.Rule = MakePlusRule(L_IDS, ToTerm(","), identificador);



            EXPRESION.Rule = MakePlusRule(EXPRESION, ToTerm("."), termino);



            NonTerminal n = new NonTerminal("fdsfd");
            n.Rule = EXPRESION;



            #endregion


            Root = n;
        }
Esempio n. 21
0
        public Gramatica() : base(caseSensitive: true)
        {
            #region Terminales

            //comentarios
            CommentTerminal simple   = new CommentTerminal("simple", "//", "\n", "\r\n");
            CommentTerminal multiple = new CommentTerminal("multiple", "/*", "*/");
            NonGrammarTerminals.Add(simple);
            NonGrammarTerminals.Add(multiple);

            //tipos de datos
            var entero   = ToTerm("Int", "Int");
            var cadena   = ToTerm("String", "String");
            var doble    = ToTerm("Double", "Double");
            var booleano = ToTerm("Bool", "Bool");
            var caracter = ToTerm("Char", "Char");
            var vacio    = ToTerm("Void", "Void");

            //palabras reservadas
            var importar       = ToTerm("Import", "Import");
            var retornar       = ToTerm("Return", "Return");
            var imprimir       = ToTerm("Print", "Print");
            var principal      = ToTerm("Main", "Main");
            var comparar       = ToTerm("CompareTo", "CompareTo");
            var obtenerUsuario = ToTerm("GetUser", "GetUser");

            //palabras reservadas de sentencias de control
            var si       = ToTerm("If", "If");
            var sino     = ToTerm("Else", "Else");
            var cambiar  = ToTerm("Switch", "Switch");
            var caso     = ToTerm("Case", "Case");
            var defecto  = ToTerm("Default", "Default");
            var quebrar  = ToTerm("Break", "Break");
            var para     = ToTerm("For", "For");
            var mientras = ToTerm("While", "While");
            var hacer    = ToTerm("Do", "Do");

            //operadores aritmeticos
            var sumar       = ToTerm("+", "+");
            var restar      = ToTerm("-", "-");
            var multiplicar = ToTerm("*", "*");
            var dividir     = ToTerm("/", "/");
            var modular     = ToTerm("%", "%");
            var elevar      = ToTerm("^", "^");
            var asignacion  = ToTerm("=", "=");
            var incremento  = ToTerm("++", "++");
            var decremento  = ToTerm("--", "--");

            //operadores relacionales
            var menorQue      = ToTerm("<", "<");
            var mayorQue      = ToTerm(">", ">");
            var menorIgual    = ToTerm("<=", "<=");
            var mayorIgual    = ToTerm(">=", ">=");
            var equivalente   = ToTerm("==", "==");
            var noEquivalente = ToTerm("!=", "!=");

            //operadores logicos
            var and = ToTerm("&&", "&&");
            var or  = ToTerm("||", "||");
            var xor = ToTerm("|&", "|&");
            var not = ToTerm("!", "!");

            //punctuation mark
            var finSentencia = ToTerm(";", ";");
            var parentesisA  = ToTerm("(", "(");
            var parentesisC  = ToTerm(")", ")");
            var llaveA       = ToTerm("{", "{");
            var llaveC       = ToTerm("}", "}");
            var dosPuntos    = ToTerm(":", ":");
            var corcheteA    = ToTerm("[", "[");
            var corcheteC    = ToTerm("]", "]");
            var coma         = ToTerm(",", ",");
            var punto        = ToTerm(".", ".");

            //valores
            var numero        = TerminalFactory.CreateCSharpNumber("numero");
            var identificador = TerminalFactory.CreateCSharpIdentifier("identificador");
            var cad           = TerminalFactory.CreateCSharpString("cadena");
            var falso         = ToTerm("False", "falso");
            var verdadero     = ToTerm("True", "verdadero");
            var car           = TerminalFactory.CreateCSharpChar("caracter");

            #endregion

            #region Precedencias y puntuaciones
            this.MarkPunctuation(finSentencia, parentesisA, parentesisC,
                                 llaveA, llaveC, dosPuntos, coma, punto);

            RegisterOperators(1, Associativity.Left, sumar, restar);
            RegisterOperators(2, Associativity.Left, multiplicar, modular, dividir);
            RegisterOperators(3, Associativity.Right, elevar);
            RegisterOperators(5, equivalente, noEquivalente, menorQue, menorIgual, mayorQue, mayorIgual);
            RegisterOperators(6, Associativity.Left, or);
            RegisterOperators(7, Associativity.Left, xor);
            RegisterOperators(8, Associativity.Left, and);
            RegisterOperators(9, Associativity.Left, not);
            RegisterOperators(10, parentesisA, parentesisC);

            #endregion

            #region No Terminales

            NonTerminal INICIO               = new NonTerminal("INICIO");
            NonTerminal DECLARACION          = new NonTerminal("DECLARACION");
            NonTerminal PRINCIPAL            = new NonTerminal("PRINCIPAL");
            NonTerminal ASIGNACION           = new NonTerminal("ASIGNACION");
            NonTerminal WHILE                = new NonTerminal("WHILE");
            NonTerminal DO_WHILE             = new NonTerminal("DO_WHILE");
            NonTerminal IF                   = new NonTerminal("IF");
            NonTerminal ELSE                 = new NonTerminal("ELSE");
            NonTerminal FOR                  = new NonTerminal("FOR");
            NonTerminal SWITCH               = new NonTerminal("SWITCH");
            NonTerminal LISTA_ACCIONES       = new NonTerminal("LISTA_ACCIONES");
            NonTerminal ACCION               = new NonTerminal("ACCION");
            NonTerminal IMPORT               = new NonTerminal("IMPORT");
            NonTerminal ENCABEZADO           = new NonTerminal("ENCABEZADO");
            NonTerminal TIPO_DATO            = new NonTerminal("TIPO_DATO");
            NonTerminal LISTA_VARS           = new NonTerminal("LISTA_VARS");
            NonTerminal EXPRESION_LOGICA     = new NonTerminal("EXPRESION_LOGICA");
            NonTerminal EXPRESION_RELACIONAL = new NonTerminal("EXPRESION_RELACIONAL");
            NonTerminal EXPRESION            = new NonTerminal("EXPRESION");
            NonTerminal DECLARACION_ARREGLO  = new NonTerminal("DECLARACION_ARREGLO");
            NonTerminal ASIGNACION_ARREGLO   = new NonTerminal("ASIGNACION_ARREGLO");
            NonTerminal LISTA_DATOS          = new NonTerminal("LISTA_DATOS");
            NonTerminal ASIGNACION_POSICION  = new NonTerminal("ASIGNACION_POSICION");
            NonTerminal SENTENCIA            = new NonTerminal("SENTENCIA");
            NonTerminal LISTA_SENTENCIAS     = new NonTerminal("LISTA_SENTENCIAS");
            NonTerminal PROCEDIMIENTO        = new NonTerminal("PROCEDIMIENTO");
            NonTerminal LISTA_PARAMETROS     = new NonTerminal("LISTA_PARAMETROS");
            NonTerminal PARAMETRO            = new NonTerminal("PARAMETRO");
            NonTerminal FUNCION_PRINT        = new NonTerminal("FUNCION_PRINT");
            NonTerminal FUNCION_COMPARAR     = new NonTerminal("FUNCION_COMPARAR");
            NonTerminal RETORNO              = new NonTerminal("RETORNO");
            NonTerminal OBTENER_USUARIO      = new NonTerminal("OBTENER_USUARIO");
            NonTerminal OPERADOR_RELACIONAL  = new NonTerminal("OPERADOR_RELACIONAL");
            NonTerminal LLAMADA              = new NonTerminal("LLAMADA");
            NonTerminal DINCREMENTO          = new NonTerminal("DINCREMENTO");
            NonTerminal CASE                 = new NonTerminal("CASE");
            NonTerminal DEFAULT              = new NonTerminal("DEFAULT");
            NonTerminal CUERPO_SWITCH        = new NonTerminal("CUERPO_SWITCH");
            NonTerminal LISTA_CASE           = new NonTerminal("LISTA_CASE");
            NonTerminal VALOR                = new NonTerminal("VALOR");
            NonTerminal OPCION_SENTENCIAS    = new NonTerminal("OPCION_SENTENCIAS");

            #endregion

            #region reglas gramaticales

            //Encabezado
            ENCABEZADO.Rule = MakePlusRule(ENCABEZADO, IMPORT)
                              | IMPORT;

            IMPORT.Rule = importar + cad + finSentencia;

            // Cuerpo principal
            this.Root = INICIO;

            INICIO.Rule = ENCABEZADO + LISTA_ACCIONES
                          | ENCABEZADO
                          | LISTA_ACCIONES;

            LISTA_ACCIONES.Rule = MakePlusRule(LISTA_ACCIONES, ACCION)
                                  | ACCION;

            ACCION.Rule = DECLARACION
                          | PROCEDIMIENTO
                          | PRINCIPAL
                          | ASIGNACION
                          | DECLARACION_ARREGLO
                          | ASIGNACION_POSICION
                          | DINCREMENTO + finSentencia
                          | FUNCION_PRINT + finSentencia;

            PRINCIPAL.Rule = principal + dosPuntos + vacio + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC
                             | principal + dosPuntos + TIPO_DATO + parentesisA + LISTA_PARAMETROS + parentesisC
                             + llaveA + OPCION_SENTENCIAS + llaveC
                             | principal + dosPuntos + vacio + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC
                             | principal + dosPuntos + TIPO_DATO + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC;

            // Sintaxis de las Declaraciones
            TIPO_DATO.Rule = entero | doble | cadena | caracter | booleano;

            LISTA_VARS.Rule = MakePlusRule(LISTA_VARS, coma, identificador);

            DECLARACION.Rule = LISTA_VARS + dosPuntos + TIPO_DATO + asignacion + EXPRESION_LOGICA + finSentencia
                               | identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION_LOGICA + finSentencia
                               | LISTA_VARS + dosPuntos + TIPO_DATO + finSentencia
                               | identificador + dosPuntos + TIPO_DATO + finSentencia;

            // Sintaxis de las Asignaciones
            ASIGNACION.Rule = identificador + asignacion + EXPRESION_LOGICA + finSentencia
                              | identificador + asignacion + llaveA + LISTA_DATOS + llaveC + finSentencia;

            // Sintaxis de los arreglos
            DECLARACION_ARREGLO.Rule = identificador + dosPuntos + TIPO_DATO
                                       + corcheteA + EXPRESION + corcheteC + finSentencia
                                       | identificador + dosPuntos + TIPO_DATO + corcheteA + EXPRESION + corcheteC
                                       + asignacion + ASIGNACION_ARREGLO + finSentencia;

            LISTA_DATOS.Rule = MakePlusRule(LISTA_DATOS, coma, EXPRESION_LOGICA)
                               | EXPRESION_LOGICA;

            ASIGNACION_ARREGLO.Rule = llaveA + LISTA_DATOS + llaveC
                                      | identificador;

            ASIGNACION_POSICION.Rule = identificador + corcheteA + EXPRESION + corcheteC
                                       + asignacion + EXPRESION_LOGICA + finSentencia;

            //Sintaxis de Metodos y Funciones
            PROCEDIMIENTO.Rule = identificador + dosPuntos + TIPO_DATO
                                 + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC
                                 | identificador + dosPuntos + vacio
                                 + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC
                                 | identificador + dosPuntos + TIPO_DATO
                                 + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC
                                 | identificador + dosPuntos + vacio
                                 + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC;

            PARAMETRO.Rule = identificador + dosPuntos + TIPO_DATO
                             | identificador + dosPuntos + TIPO_DATO + corcheteA + corcheteC;

            LISTA_PARAMETROS.Rule = MakePlusRule(LISTA_PARAMETROS, coma, PARAMETRO)
                                    | PARAMETRO;

            LISTA_SENTENCIAS.Rule = MakePlusRule(LISTA_SENTENCIAS, SENTENCIA)
                                    | SENTENCIA;

            OPCION_SENTENCIAS.Rule = LISTA_SENTENCIAS | Empty;

            SENTENCIA.Rule = DECLARACION
                             | ASIGNACION
                             | DECLARACION_ARREGLO
                             | ASIGNACION_POSICION
                             | IF
                             | FOR
                             | SWITCH
                             | WHILE
                             | DO_WHILE
                             | FUNCION_PRINT + finSentencia
                             | DINCREMENTO + finSentencia
                             | LLAMADA + finSentencia
                             | quebrar + finSentencia
                             | RETORNO;

            RETORNO.Rule = retornar + EXPRESION_LOGICA + finSentencia
                           | retornar + finSentencia;

            //Funciones nativas
            FUNCION_PRINT.Rule = imprimir + parentesisA + EXPRESION_LOGICA + parentesisC;

            FUNCION_COMPARAR.Rule = punto + comparar + parentesisA + EXPRESION + parentesisC;

            OBTENER_USUARIO.Rule = obtenerUsuario + parentesisA + parentesisC;

            //If Else
            IF.Rule = si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC
                      | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC
                      | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC + ELSE
                      | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC + ELSE;

            ELSE.Rule = sino + llaveA + LISTA_SENTENCIAS + llaveC
                        | sino + llaveA + llaveC;

            //While
            WHILE.Rule = mientras + parentesisA + EXPRESION_LOGICA + parentesisC
                         + llaveA + LISTA_SENTENCIAS + llaveC
                         | mientras + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC;

            //Do While
            DO_WHILE.Rule = hacer + llaveA + LISTA_SENTENCIAS + llaveC + mientras + parentesisA
                            + EXPRESION_LOGICA + parentesisC + finSentencia
                            | hacer + llaveA + llaveC + mientras + parentesisA + EXPRESION_LOGICA + parentesisC + finSentencia;

            //For
            FOR.Rule = para + parentesisA + identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION
                       + finSentencia + EXPRESION_LOGICA + finSentencia + DINCREMENTO + parentesisC + llaveA + LISTA_SENTENCIAS
                       + llaveC
                       | para + parentesisA + identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION
                       + finSentencia + EXPRESION_LOGICA + finSentencia + DINCREMENTO + parentesisC + llaveA + llaveC;

            DINCREMENTO.Rule = identificador + incremento
                               | identificador + decremento;

            //Switch
            SWITCH.Rule = cambiar + parentesisA + identificador + parentesisC + llaveA + CUERPO_SWITCH + llaveC;

            CUERPO_SWITCH.Rule = LISTA_CASE
                                 | LISTA_CASE + DEFAULT;

            LISTA_CASE.Rule = MakePlusRule(LISTA_CASE, CASE)
                              | CASE;

            CASE.Rule = caso + VALOR + dosPuntos + LISTA_SENTENCIAS
                        | caso + VALOR + dosPuntos;

            VALOR.Rule = cad | numero;

            DEFAULT.Rule = defecto + dosPuntos + LISTA_SENTENCIAS
                           | defecto + dosPuntos;

            //Llamadas
            LLAMADA.Rule = identificador + parentesisA + parentesisC
                           | identificador + parentesisA + LISTA_DATOS + parentesisC;

            // Expresiones
            EXPRESION_LOGICA.Rule = EXPRESION_LOGICA + and + EXPRESION_LOGICA
                                    | EXPRESION_LOGICA + or + EXPRESION_LOGICA
                                    | EXPRESION_LOGICA + xor + EXPRESION_LOGICA
                                    | not + EXPRESION_LOGICA
                                    | EXPRESION_RELACIONAL;

            EXPRESION_RELACIONAL.Rule = EXPRESION + OPERADOR_RELACIONAL + EXPRESION
                                        | EXPRESION;

            OPERADOR_RELACIONAL.Rule = menorQue
                                       | menorIgual
                                       | mayorQue
                                       | mayorIgual
                                       | equivalente
                                       | noEquivalente;

            EXPRESION.Rule = EXPRESION + sumar + EXPRESION
                             | EXPRESION + restar + EXPRESION
                             | EXPRESION + multiplicar + EXPRESION
                             | EXPRESION + dividir + EXPRESION
                             | EXPRESION + modular + EXPRESION
                             | EXPRESION + elevar + EXPRESION
                             | restar + EXPRESION
                             | parentesisA + EXPRESION_LOGICA + parentesisC
                             | identificador + corcheteA + EXPRESION + corcheteC
                             | identificador
                             | LLAMADA
                             | OBTENER_USUARIO
                             | verdadero
                             | falso
                             | cad
                             | car
                             | numero
                             | identificador + FUNCION_COMPARAR
                             | identificador + corcheteA + EXPRESION + corcheteC + FUNCION_COMPARAR;
            #endregion
        }
Esempio n. 22
0
        //TerminalSet _skipTokensInPreview = new TerminalSet(); //used in token preview for conflict resolution
        public ExpressionGrammar()
        {
            //this.GrammarComments = "NOTE: This grammar is just a demo, and it is a broken demo.\r\n" +
            //                       "Demonstrates token preview technique to help parser resolve conflicts.\r\n";
            #region Lexical structure
            StringLiteral      StringLiteral = TerminalFactory.CreateCSharpString("StringLiteral");
            StringLiteral      CharLiteral   = TerminalFactory.CreateCSharpChar("CharLiteral");
            NumberLiteral      Number        = TerminalFactory.CreateCSharpNumber("Number");
            IdentifierTerminal identifier    = TerminalFactory.CreateCSharpIdentifier("Identifier");

            CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029");
            CommentTerminal DelimitedComment  = new CommentTerminal("DelimitedComment", "/*", "*/");
            NonGrammarTerminals.Add(SingleLineComment);
            NonGrammarTerminals.Add(DelimitedComment);
            //Temporarily, treat preprocessor instructions like comments
            CommentTerminal ppInstruction = new CommentTerminal("ppInstruction", "#", "\n");
            NonGrammarTerminals.Add(ppInstruction);

            //Symbols
            Terminal    colon    = new Terminal(":"); //ToTerm(":", "colon");
            Terminal    semi     = ToTerm(";");       //, "semi");
            NonTerminal semi_opt = new NonTerminal("semi?");
            semi_opt.Rule = Empty | semi;
            Terminal    dot        = ToTerm("."); //, "dot");
            Terminal    comma      = ToTerm(","); //, "comma");
            NonTerminal comma_opt  = new NonTerminal("comma_opt", Empty | comma);
            NonTerminal commas_opt = new NonTerminal("commas_opt");
            commas_opt.Rule = MakeStarRule(commas_opt, null, comma);
            Terminal    qmark     = ToTerm("?");//, "qmark");
            NonTerminal qmark_opt = new NonTerminal("qmark_opt", Empty | qmark);
            Terminal    Lbr       = ToTerm("{");
            Terminal    Rbr       = ToTerm("}");
            Terminal    Lpar      = ToTerm("(");
            Terminal    Rpar      = ToTerm(")");
            Terminal    tgoto     = ToTerm("goto");
            Terminal    yld       = ToTerm("yield");

            Terminal Lparx = ToTerm("(*");
            #endregion

            #region NonTerminals
            //B.2.1. Basic concepts
            var qual_name_with_targs        = new NonTerminal("qual_name_with_targs");
            var base_type_list              = new NonTerminal("base_type_list");
            var generic_dimension_specifier = new NonTerminal("generic_dimension_specifier");
            var qual_name_segment           = new NonTerminal("qual_name_segment");
            var qual_name_segments_opt      = new NonTerminal("qual_name_segments_opt");
            var type_or_void          = new NonTerminal("type_or_void", "type or void");
            var builtin_type          = new NonTerminal("builtin_type", "built-in type");
            var type_ref_list         = new NonTerminal("type_ref_list");
            var identifier_ext        = new NonTerminal("identifier_ext");
            var identifier_or_builtin = new NonTerminal("identifier_or_builtin");

            //B.2.2. Types
            var type_ref                   = new NonTerminal("type_ref");
            var type_argument_list         = new NonTerminal("type_argument_list");
            var typearg_or_gendimspec_list = new NonTerminal("typearg_or_gendimspec_list");
            var type_argument_list_opt     = new NonTerminal("type_argument_list_opt");
            var integral_type              = new NonTerminal("integral_type");

            //B.2.4. Expressions
            var argument                  = new NonTerminal("argument");
            var argument_list             = new NonTerminal("argument_list");
            var argument_list_opt         = new NonTerminal("argument_list_opt");
            var expression                = new NonTerminal("expression", "expression");
            var expression_list           = new NonTerminal("expression_list");
            var expression_opt            = new NonTerminal("expression_opt");
            var conditional_expression    = new NonTerminal("conditional_expression");
            var lambda_expression         = new NonTerminal("lambda_expression");
            var query_expression          = new NonTerminal("query_expression");
            var unary_operator            = new NonTerminal("unary_operator");
            var assignment_operator       = new NonTerminal("assignment_operator");
            var primary_expression        = new NonTerminal("primary_expression");
            var unary_expression          = new NonTerminal("unary_expression");
            var pre_incr_decr_expression  = new NonTerminal("pre_incr_decr_expression");
            var post_incr_decr_expression = new NonTerminal("post_incr_decr_expression");
            var literal = new NonTerminal("literal");
            var parenthesized_expression   = new NonTerminal("parenthesized_expression");
            var member_access              = new NonTerminal("member_access");
            var member_access_segment      = new NonTerminal("member_access_segment");
            var member_access_segments_opt = new NonTerminal("member_access_segments_opt");
            var array_indexer              = new NonTerminal("array_indexer");
            var argument_list_par          = new NonTerminal("argument_list_par");
            var argument_list_par_opt      = new NonTerminal("argument_list_par_opt");
            var incr_or_decr                         = new NonTerminal("incr_or_decr");
            var incr_or_decr_opt                     = new NonTerminal("incr_or_decr_opt");
            var creation_args                        = new NonTerminal("creation_args");
            var object_creation_expression           = new NonTerminal("object_creation_expression");
            var anonymous_object_creation_expression = new NonTerminal("anonymous_object_creation_expression");
            var typeof_expression                    = new NonTerminal("typeof_expression");
            var checked_expression                   = new NonTerminal("checked_expression");
            var unchecked_expression                 = new NonTerminal("unchecked_expression");
            var default_value_expression             = new NonTerminal("default_value_expression");
            //var anonymous_method_expression = new NonTerminal("anonymous_method_expression");

            var elem_initializer          = new NonTerminal("elem_initializer");
            var elem_initializer_list     = new NonTerminal("elem_initializer_list");
            var elem_initializer_list_ext = new NonTerminal("elem_initializer_list_ext");
            var initializer_value         = new NonTerminal("initializer_value");

            var anonymous_object_initializer    = new NonTerminal("anonymous_object_initializer");
            var member_declarator               = new NonTerminal("member_declarator");
            var member_declarator_list          = new NonTerminal("member_declarator_list");
            var unbound_type_name               = new NonTerminal("unbound_type_name");
            var generic_dimension_specifier_opt = new NonTerminal("generic_dimension_specifier_opt");
            var bin_op_expression               = new NonTerminal("bin_op_expression");
            var typecast_expression             = new NonTerminal("typecast_expression");
            var bin_op = new NonTerminal("bin_op", "operator symbol");

            //B.2.5. Statements
            var statement             = new NonTerminal("statement", "statement");
            var statement_list        = new NonTerminal("statement_list");
            var statement_list_opt    = new NonTerminal("statement_list_opt");
            var declaration_statement = new NonTerminal("declaration_statement");
            var embedded_statement    = new NonTerminal("embedded_statement");
            var selection_statement   = new NonTerminal("selection_statement");
            var iteration_statement   = new NonTerminal("iteration_statement");
            var block = new NonTerminal("block");
            var statement_expression       = new NonTerminal("statement_expression");
            var statement_expression_list  = new NonTerminal("statement_expression_list");
            var local_variable_declaration = new NonTerminal("local_variable_declaration");
            //var local_constant_declaration = new NonTerminal("local_constant_declaration");
            var local_variable_type       = new NonTerminal("local_variable_type");
            var local_variable_declarator = new NonTerminal("local_variable_declarator");
            //var local_variable_declarators = new NonTerminal("local_variable_declarators");
            var if_statement        = new NonTerminal("if_statement");
            var else_clause_opt     = new NonTerminal("else_clause_opt");
            var while_statement     = new NonTerminal("while_statement");
            var do_statement        = new NonTerminal("do_statement");
            var for_statement       = new NonTerminal("for_statement");
            var for_initializer_opt = new NonTerminal("for_initializer_opt");
            var for_condition_opt   = new NonTerminal("for_condition_opt");
            var for_iterator_opt    = new NonTerminal("for_iterator_opt");
            var break_statement     = new NonTerminal("break_statement");
            var continue_statement  = new NonTerminal("continue_statement");
            var return_statement    = new NonTerminal("return_statement");
            var identifier_opt      = new NonTerminal("identifier_opt");

            var resource_acquisition = new NonTerminal("resource_acquisition");

            //namespaces, compilation units
            var qualified_identifier   = new NonTerminal("qualified_identifier");
            var qualified_alias_member = new NonTerminal("qualified_alias_member");

            //B.2.9. Arrays
            var rank_specifier       = new NonTerminal("rank_specifier");
            var rank_specifiers      = new NonTerminal("rank_specifiers");
            var rank_specifiers_opt  = new NonTerminal("rank_specifiers_opt");
            var dim_specifier        = new NonTerminal("dim_specifier");
            var dim_specifier_opt    = new NonTerminal("dim_specifier_opt");
            var list_initializer     = new NonTerminal("array_initializer");
            var list_initializer_opt = new NonTerminal("array_initializer_opt");



            var new_opt = new NonTerminal("new_opt");

            #endregion

            #region operators, punctuation and delimiters
            RegisterOperators(1, "||");
            RegisterOperators(2, "&&");
            RegisterOperators(3, "|");
            RegisterOperators(4, "^");
            RegisterOperators(5, "&");
            RegisterOperators(6, "==", "!=");
            RegisterOperators(7, "<", ">", "<=", ">=", "is", "as");
            RegisterOperators(8, "<<", ">>");
            RegisterOperators(9, "+", "-");
            RegisterOperators(10, "*", "/", "%");

            RegisterOperators(-3, "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=");
            RegisterOperators(-2, "?");
            RegisterOperators(-1, "??");

            this.MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":");
            //this.MarkTransient(/*namespace_member_declaration, member_declaration, type_declaration,*/ statement, embedded_statement, expression,
            //  literal, bin_op, primary_expression, expression);

            //this.AddTermsReportGroup("assignment", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=");
            //this.AddTermsReportGroup("typename", "bool", "decimal", "float", "double", "string", "object",
            //  "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char");
            //this.AddTermsReportGroup("statement", "if", "switch", "do", "while", "for", "foreach", "continue", "goto", "return", "try", "yield",
            //                                      "break", "throw", "unchecked", "using");
            //this.AddTermsReportGroup("type declaration", "public", "private", "protected", "static", "internal", "sealed", "abstract", "partial",
            //                                             "class", "struct", "delegate", "interface", "enum");
            //this.AddTermsReportGroup("member declaration", "virtual", "override", "readonly", "volatile", "extern");
            //this.AddTermsReportGroup("constant", Number, StringLiteral, CharLiteral);
            //this.AddTermsReportGroup("constant", "true", "false", "null");

            //this.AddTermsReportGroup("unary operator", "+", "-", "!", "~");

            //this.AddToNoReportGroup(comma, semi);
            //this.AddToNoReportGroup("var", "const", "new", "++", "--", "this", "base", "checked", "lock", "typeof", "default",
            //                         "{", "}", "[");

            //
            #endregion

            #region "<" conflict resolution
            //var gen_lt = new NonTerminal("gen_lt");
            //gen_lt.Rule = CustomActionHere(this.ResolveLessThanConflict) + "<";
            #endregion

            // RULES
            //B.2.1. Basic concepts
            //qual_name_with_targs is an alias for namespace-name, namespace-or-type-name, type-name,

            generic_dimension_specifier.Rule = /*gen_lt +*/ commas_opt + ">";
            qual_name_segments_opt.Rule      = MakeStarRule(qual_name_segments_opt, null, qual_name_segment);
            identifier_or_builtin.Rule       = identifier | builtin_type;
            identifier_ext.Rule    = identifier_or_builtin | "this" | "base";
            qual_name_segment.Rule = dot + identifier
                                     | "::" + identifier
                                     | type_argument_list;
            //generic_dimension_specifier.Rule = lt + commas_opt + ">";
            generic_dimension_specifier.Rule = /*gen_lt +*/ commas_opt + ">";
            qual_name_with_targs.Rule        = identifier_or_builtin + qual_name_segments_opt;

            type_argument_list.Rule         = /*gen_lt +*/ type_ref_list + ">";
            type_argument_list_opt.Rule     = Empty | type_argument_list;
            typearg_or_gendimspec_list.Rule = type_argument_list | generic_dimension_specifier_opt;

            //B.2.2. Types
            type_or_void.Rule = /*qual_name_with_targs |*/ "void";
            builtin_type.Rule = integral_type | "bool" | "decimal" | "float" | "double" | "string" | "object";

            type_ref.Rule      = type_or_void + qmark_opt + rank_specifiers_opt + typearg_or_gendimspec_list;
            type_ref_list.Rule = MakePlusRule(type_ref_list, comma, type_ref);

            var comma_list_opt = new NonTerminal("comma_list_opt");
            comma_list_opt.Rule      = MakeStarRule(comma_list_opt, null, comma);
            rank_specifier.Rule      = "[" + comma_list_opt + "]";
            rank_specifiers.Rule     = MakePlusRule(rank_specifiers, null, rank_specifier);
            rank_specifiers_opt.Rule = rank_specifiers.Q();
            integral_type.Rule       = ToTerm("sbyte") | "byte" | "short" | "ushort" | "int" | "uint" | "long" | "ulong" | "char";


            //B.2.4. Expressions
            argument.Rule          = expression | "ref" + identifier | "out" + identifier;
            argument_list.Rule     = MakePlusRule(argument_list, comma, argument);
            argument_list_opt.Rule = Empty | argument_list;
            expression.Rule        = conditional_expression
                                     | bin_op_expression
                                     | typecast_expression
                                     | primary_expression;
            expression_opt.Rule         = Empty | expression;
            expression_list.Rule        = MakePlusRule(expression_list, comma, expression);
            unary_operator.Rule         = ToTerm("+") | "-" | "!" | "~" | "*";
            assignment_operator.Rule    = ToTerm("=") | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=";
            conditional_expression.Rule = expression /*+ PreferShiftHere()*/ + qmark + expression + colon + expression;// + ReduceThis();
            bin_op_expression.Rule      = expression + bin_op + expression;

            typecast_expression.Rule = parenthesized_expression + primary_expression;
            primary_expression.Rule  =
                literal
                | unary_expression
                | parenthesized_expression
                | member_access
                | pre_incr_decr_expression
                | post_incr_decr_expression
                | object_creation_expression
                | anonymous_object_creation_expression
                | typeof_expression
                | checked_expression
                | unchecked_expression
                | default_value_expression
                /*| anonymous_method_expression*/;
            unary_expression.Rule          = unary_operator + primary_expression;
            dim_specifier.Rule             = "[" + expression_list + "]";
            dim_specifier_opt.Rule         = dim_specifier.Q();
            literal.Rule                   = Number | StringLiteral | CharLiteral | "true" | "false" | "null";
            parenthesized_expression.Rule  = Lpar + expression + Rpar;
            pre_incr_decr_expression.Rule  = incr_or_decr + member_access;
            post_incr_decr_expression.Rule = member_access + incr_or_decr;

            //joined invocation_expr and member_access; for member access left the most general variant
            member_access.Rule = identifier_ext + member_access_segments_opt;
            member_access_segments_opt.Rule = MakeStarRule(member_access_segments_opt, null, member_access_segment);
            member_access_segment.Rule      = dot + identifier
                                              | array_indexer
                                              | argument_list_par
                                              | type_argument_list;
            array_indexer.Rule = "[" + expression_list + "]";

            argument_list_par.Rule = Lpar + argument_list_opt + Rpar;

            argument_list_par_opt.Rule = Empty | argument_list_par;

            list_initializer.Rule     = Lbr + elem_initializer_list_ext + Rbr;
            list_initializer_opt.Rule = list_initializer.Q();

            elem_initializer.Rule          = initializer_value | identifier + "=" + initializer_value;
            elem_initializer_list.Rule     = MakePlusRule(elem_initializer_list, comma, elem_initializer);
            elem_initializer_list_ext.Rule = Empty | elem_initializer_list + comma_opt;
            initializer_value.Rule         = expression | list_initializer;

            //delegate, anon-object, object
            object_creation_expression.Rule = "new" + qual_name_with_targs + qmark_opt + creation_args + list_initializer_opt;
            creation_args.Rule = dim_specifier | rank_specifier | argument_list_par;

            anonymous_object_creation_expression.Rule = "new" + anonymous_object_initializer;
            anonymous_object_initializer.Rule         = Lbr + Rbr | Lbr + member_declarator_list + comma_opt + Rbr;
            member_declarator.Rule      = expression | identifier + "=" + expression;
            member_declarator_list.Rule = MakePlusRule(member_declarator_list, comma, member_declarator);
            //typeof
            typeof_expression.Rule = "typeof" + Lpar + type_ref + Rpar;
            generic_dimension_specifier_opt.Rule = Empty /*| gen_lt*/ + commas_opt + ">";
            //checked, unchecked
            checked_expression.Rule   = "checked" + parenthesized_expression;
            unchecked_expression.Rule = "unchecked" + parenthesized_expression;
            //default-value
            default_value_expression.Rule = "default" + Lpar + type_ref + Rpar;

            bin_op.Rule = ToTerm("<")
                          | "||" | "&&" | "|" | "^" | "&" | "==" | "!=" | ">" | "<=" | ">=" | "<<" | ">>" | "+" | "-" | "*" | "/" | "%"
                          | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
                          | "is" | "as" | "??";

            //Queries
            query_expression.Rule = "from";

            //B.2.5. Statements
            statement.Rule                  = /*labeled_statement |*/ declaration_statement | embedded_statement;
            statement.ErrorRule             = SyntaxError + semi; //skip all until semicolon
            statement_list.Rule             = MakePlusRule(statement_list, null, statement);
            statement_list_opt.Rule         = Empty | statement_list;
            declaration_statement.Rule      = local_variable_declaration + semi /*| local_constant_declaration*/ + semi;
            local_variable_declaration.Rule = local_variable_type /*+ local_variable_declarators*/;
            local_variable_type.Rule        = member_access | "var"; // | builtin_type; //to fix the conflict, changing to member-access here
            local_variable_declarator.Rule  = identifier | identifier + "=" + initializer_value;
            //local_variable_declarators.Rule = MakePlusRule(local_variable_declarators, comma, local_variable_declarator);
            //local_constant_declaration.Rule = "const" + type_ref /*+ constant_declarators*/;
            //embedded_statement
            embedded_statement.Rule = block | semi /*empty_statement*/ | statement_expression + semi | selection_statement
                                      | iteration_statement /* | jump_statement | try_statement | checked_statement | unchecked_statement
                                                             | lock_statement | using_statement | yield_statement*/;
            block.Rule = Lbr + statement_list_opt + Rbr;
            //selection (if and switch)
            selection_statement.Rule = if_statement /*| switch_statement*/;
            if_statement.Rule        = ToTerm("if") + Lpar + expression + Rpar + embedded_statement + else_clause_opt;
            else_clause_opt.Rule     = Empty /*| PreferShiftHere()*/ + "else" + embedded_statement;
            iteration_statement.Rule = while_statement | do_statement | for_statement /*| foreach_statement*/;
            while_statement.Rule     = "while" + parenthesized_expression + embedded_statement;
            do_statement.Rule        = "do" + embedded_statement + "while" + parenthesized_expression + semi;
            for_statement.Rule       = "for" + Lpar + for_initializer_opt + semi + for_condition_opt + semi + for_iterator_opt + Rpar + embedded_statement;
            for_initializer_opt.Rule = Empty | local_variable_declaration | statement_expression_list;
            for_condition_opt.Rule   = Empty | expression;
            for_iterator_opt.Rule    = Empty | statement_expression_list;
            break_statement.Rule     = "break" + semi;
            continue_statement.Rule  = "continue" + semi;
            return_statement.Rule    = "return" + expression_opt + semi;
            identifier_opt.Rule      = Empty | identifier;

            resource_acquisition.Rule = local_variable_declaration | expression;

            statement_expression.Rule = object_creation_expression
                                        | member_access | member_access + assignment_operator + expression
                                        | pre_incr_decr_expression | post_incr_decr_expression
            ;
            statement_expression_list.Rule = MakePlusRule(statement_expression_list, comma, statement_expression);
            incr_or_decr_opt.Rule          = Empty | ToTerm("++") | "--";
            incr_or_decr.Rule = ToTerm("++") | "--";

            //B.2.6. Namespaces
            this.Root = block;
            qualified_identifier.Rule = MakePlusRule(qualified_identifier, dot, identifier);

            base_type_list.Rule = MakePlusRule(base_type_list, comma, qual_name_with_targs);

            new_opt.Rule = Empty | "new";

            //_skipTokensInPreview.UnionWith(new Terminal[] { dot, identifier, comma, ToTerm("::"), comma, ToTerm("["), ToTerm("]") });
        }
Esempio n. 23
0
        public AnalizadorTree()
            : base(caseSensitive: false)
        {
            //Comentarios
            CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "##", "\n", "\r\n");
            CommentTerminal COMENTARIO_MULT   = new CommentTerminal("comentario_mult", "{--", "--}");

            NonGrammarTerminals.Add(COMENTARIO_SIMPLE);
            NonGrammarTerminals.Add(COMENTARIO_MULT);

            //Palabras Reservadas
            MarkReservedWords("importar");
            MarkReservedWords("__constructor");
            MarkReservedWords("super");
            MarkReservedWords("self");
            MarkReservedWords("publico");
            MarkReservedWords("privado");
            MarkReservedWords("protegido");
            MarkReservedWords("/**Sobreescribir**/");
            MarkReservedWords("metodo");
            MarkReservedWords("funcion");
            MarkReservedWords("clase");
            MarkReservedWords("si");
            MarkReservedWords("si_no_si");
            MarkReservedWords("si_no");
            MarkReservedWords("elegir");
            MarkReservedWords("caso");
            MarkReservedWords("defecto");
            MarkReservedWords("para");
            MarkReservedWords("hacer");
            MarkReservedWords("mientras");
            MarkReservedWords("repetir");
            MarkReservedWords("hasta");
            MarkReservedWords("loop");
            MarkReservedWords("nuevo");
            MarkReservedWords("return");
            MarkReservedWords("salir");
            MarkReservedWords("continuar");
            MarkReservedWords("true");
            MarkReservedWords("false");
            MarkReservedWords("void");
            MarkReservedWords("entero");
            MarkReservedWords("decimal");
            MarkReservedWords("caracter");
            MarkReservedWords("cadena");
            MarkReservedWords("booleano");
            MarkReservedWords("out_String");
            MarkReservedWords("parseInt");
            MarkReservedWords("parseDouble");
            MarkReservedWords("intToStr");
            MarkReservedWords("doubleToStr");
            MarkReservedWords("doubleToInt");
            MarkReservedWords("imprimir");

            //Palabras reservadas
            var importar      = ToTerm("importar");
            var constructor   = ToTerm("__constructor");
            var super         = ToTerm("super");
            var self          = ToTerm("self");
            var publico       = ToTerm("publico");
            var privado       = ToTerm("privado");
            var protegido     = ToTerm("protegido");
            var sobreescribir = ToTerm("/**Sobreescribir**/");
            var metodo        = ToTerm("metodo");
            var funcion       = ToTerm("funcion");
            var clase         = ToTerm("clase");
            var si            = ToTerm("si");
            var sinosi        = ToTerm("si_no_si");
            var sino          = ToTerm("si_no");
            var selector      = ToTerm("elegir");
            var caso          = ToTerm("caso");
            var defecto       = ToTerm("defecto");
            var para          = ToTerm("para");
            var hacer         = ToTerm("hacer");
            var mientras      = ToTerm("mientras");
            var repetir       = ToTerm("repetir");
            var hasta         = ToTerm("hasta");
            var loop          = ToTerm("loop");
            var nuevo         = ToTerm("nuevo");
            var retornar      = ToTerm("return");
            var quiebre       = ToTerm("salir");
            var continuar     = ToTerm("continuar");
            var verdadero     = ToTerm("true");
            var falso         = ToTerm("false");
            var vacio         = ToTerm("void");
            var num           = ToTerm("entero");
            var dec           = ToTerm("decimal");
            var caracter      = ToTerm("caracter");
            var str           = ToTerm("cadena");
            var boolean       = ToTerm("booleano");
            var outStr        = ToTerm("out_String");
            var parseInt      = ToTerm("parseInt");
            var parseDouble   = ToTerm("parseDouble");
            var intToStr      = ToTerm("intToStr");
            var doubleToStr   = ToTerm("doubleToStr");
            var doubleToInt   = ToTerm("doubleToInt");
            var mostrar       = ToTerm("imprimir");

            //Signos
            var asignar = ToTerm("=>");
            var apar    = ToTerm("(");
            var cpar    = ToTerm(")");
            var acor    = ToTerm("[");
            var ccor    = ToTerm("]");
            var coma    = ToTerm(",");
            var punto   = ToTerm(".");
            var dosp    = ToTerm(":");

            //No Terminales
            var INICIO           = new NonTerminal("INICIO");
            var IMPORTACIONES    = new NonTerminal("IMPORTACIONES");
            var IMPORTAR         = new NonTerminal("IMPORTAR");
            var LISTA_ARCHIVOS   = new NonTerminal("LISTA_ARCHIVOS");
            var ARCHIVO          = new NonTerminal("ARCHIVO");
            var CLASES           = new NonTerminal("CLASES");
            var CLASE            = new NonTerminal("CLASE");
            var BCUERPO          = new NonTerminal("BCUERPO");
            var CUERPO           = new NonTerminal("CUERPO");
            var METODO           = new NonTerminal("METODO");
            var VISIBILIDAD      = new NonTerminal("VISIBILIDAD");
            var DECLARACIONES    = new NonTerminal("DECLARACIONES");
            var LISTA_IDS        = new NonTerminal("IDS");
            var BLOQUE           = new NonTerminal("BLOQUE");
            var LISTA_SENTENCIAS = new NonTerminal("SENTENCIAS");
            var SENTENCIA        = new NonTerminal("SENTENCIA");
            var DECLARAR         = new NonTerminal("DECLARAR");
            var asignarR         = new NonTerminal("asignarR");
            var CONTROL          = new NonTerminal("CONTROL");
            var IF1              = new NonTerminal("IF1");
            var IF2              = new NonTerminal("IF2");
            var IF3              = new NonTerminal("IF3");
            var IF4              = new NonTerminal("IF4");
            var IF5              = new NonTerminal("IF5");
            var SWITCH           = new NonTerminal("SWITCH");
            var CASOS            = new NonTerminal("CASOS");
            var BCASO            = new NonTerminal("BCASO");
            var CASO             = new NonTerminal("CASO");
            var ECASO            = new NonTerminal("ECASO");
            var DEFECTO          = new NonTerminal("DEFECTO");
            var WHILE            = new NonTerminal("WHILE");
            var DO_WHILE         = new NonTerminal("DO_WHILE");
            var FOR              = new NonTerminal("FOR");
            var LOOP             = new NonTerminal("LOOP");
            var REPEAT           = new NonTerminal("REPEAT");
            var BANDERA          = new NonTerminal("BANDERA");
            var EXP              = new NonTerminal("EXP");
            var EXPS             = new NonTerminal("EXPS");
            var ACCESO           = new NonTerminal("ACCESO");
            var TACCESO          = new NonTerminal("TACCESO");
            var TIPO             = new NonTerminal("TIPO");
            var LLAMADA          = new NonTerminal("LLAMADA");
            var TPROC            = new NonTerminal("TPROC");
            var CUERPOS          = new NonTerminal("CUERPOS");
            var VARIABLES        = new NonTerminal("VARIABLES");
            var RETORNO          = new NonTerminal("RETORNO");
            var INTERRUMPIR      = new NonTerminal("INTERRUMPIR");
            var CONTINUAR        = new NonTerminal("CONTINUAR");
            var LISTA_PARAMETROS = new NonTerminal("LISTA_PARAMETROS");
            var PARAMETRO        = new NonTerminal("PARAMETRO");
            var PARAM            = new NonTerminal("PARAM");
            var DECLARACION      = new NonTerminal("DECLARACION");
            var ASIGNACION       = new NonTerminal("ASIGNACION");
            var DIMENSION        = new NonTerminal("DIMENSION");
            var NATIVAS          = new NonTerminal("NATIVAS");
            var CADENA           = new NonTerminal("CADENA");
            var IMPRIMIR         = new NonTerminal("IMPRIMIR");
            var EXCEPTION        = new NonTerminal("EXCEPTION");
            var Fasignar         = new NonTerminal("Fasignar");
            var DIM              = new NonTerminal("DIM");
            var DIM2             = new NonTerminal("DIM");
            var INDICES          = new NonTerminal("INDICES");
            var AID              = new NonTerminal("AID");
            var Tasignar         = new NonTerminal("EXP");
            var CRECE            = new NonTerminal("CRECE");
            var ARR              = new NonTerminal("ARR");
            var A        = new NonTerminal("A");
            var NARREGLO = new NonTerminal("NARREGLO");
            var DARREGLO = new NonTerminal("NARREGLO");
            var NUMEROS  = new NonTerminal("INDICES");
            var NUEVO    = new NonTerminal("NUEVO");
            var SUPER    = new NonTerminal("SUPER");
            var ESTE     = new NonTerminal("ESTE");

            //Terminales Expresiones Regulares
            RegexBasedTerminal archivo = new RegexBasedTerminal("archivo", "[a-zA-Z][0-9a-zA-Z]*.(tree|olc)");
            RegexBasedTerminal ruta    = new RegexBasedTerminal("ruta", "C://([a-zA-Z][0-9a-zA-Z]*/)*[a-zA-Z][0-9a-zA-Z]*.(tree|olc)");
            RegexBasedTerminal url     = new RegexBasedTerminal("url", "http://([a-zA-Z][0-9a-zA-Z]*/)*[a-zA-Z][0-9a-zA-Z]*.(tree|olc)");
            NumberLiteral      numero  = TerminalFactory.CreateCSharpNumber("numero");
            IdentifierTerminal id      = TerminalFactory.CreateCSharpIdentifier("id");
            var tstring = new StringLiteral("cadena", "\"", StringOptions.AllowsDoubledQuote);
            var tchar   = new StringLiteral("caracter", "'", StringOptions.AllowsDoubledQuote);

            //No Terminal Inicial
            this.Root = INICIO;

            //Producciones
            INICIO.Rule = IMPORTACIONES + CLASES
                          | CLASES;

            IMPORTACIONES.Rule = MakeStarRule(IMPORTACIONES, IMPORTAR);

            IMPORTAR.Rule = importar + LISTA_ARCHIVOS + Eos;

            LISTA_ARCHIVOS.Rule = MakeStarRule(LISTA_ARCHIVOS, coma, ARCHIVO);

            ARCHIVO.Rule = ruta
                           | archivo
                           | url;

            CLASES.Rule = MakeStarRule(CLASES, CLASE);

            CLASE.Rule = clase + id + acor + id + ccor + dosp + Eos + BCUERPO
                         | clase + id + acor + ccor + dosp + Eos + BCUERPO;

            BCUERPO.Rule = Indent + CUERPOS + Dedent;

            CUERPOS.Rule = MakeStarRule(CUERPOS, CUERPO);

            CUERPO.Rule = VISIBILIDAD + DECLARACION + Eos
                          | METODO
                          | constructor + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE
                          | DECLARACION + Eos
                          | ASIGNACION + Eos;

            METODO.Rule = sobreescribir + Eos + VISIBILIDAD + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE
                          | VISIBILIDAD + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE
                          | sobreescribir + Eos + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE
                          | TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE;

            VISIBILIDAD.Rule = publico
                               | privado
                               | protegido;

            LISTA_PARAMETROS.Rule = MakeStarRule(LISTA_PARAMETROS, coma, PARAMETRO);

            PARAMETRO.Rule = TIPO + id + ARR;

            ARR.Rule = MakeStarRule(ARR, A);

            A.Rule = acor + ccor;

            DECLARACION.Rule = TIPO + LISTA_IDS + asignarR
                               | TIPO + LISTA_IDS
                               | TIPO + DARREGLO;

            DARREGLO.Rule = id + NUMEROS;

            NUMEROS.Rule = MakeStarRule(NUMEROS, DIM2);

            DIM2.Rule = acor + numero + ccor;

            asignarR.Rule = asignar + EXP;

            ASIGNACION.Rule = ACCESO + asignar + EXP;

            INDICES.Rule = MakeStarRule(INDICES, DIM);

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

            BLOQUE.Rule = Indent + LISTA_SENTENCIAS + Dedent;

            LISTA_SENTENCIAS.Rule = MakeStarRule(LISTA_SENTENCIAS, SENTENCIA);

            SENTENCIA.Rule = DECLARACION + Eos
                             | self + punto + ASIGNACION + Eos
                             | ASIGNACION + Eos
                             | CONTROL
                             | ACCESO + Eos
                             | INTERRUMPIR + Eos
                             | CONTINUAR + Eos
                             | RETORNO + Eos
                             | NATIVAS + Eos
                             | IMPRIMIR + Eos
                             | SUPER + Eos;

            SUPER.Rule = super + punto + ASIGNACION
                         | super + punto + ACCESO
                         | super + acor + EXPS + ccor;

            IMPRIMIR.Rule = mostrar + acor + EXP + ccor
                            | outStr + acor + EXP + ccor;

            NATIVAS.Rule = parseInt + acor + EXP + ccor
                           | parseDouble + acor + EXP + ccor
                           | intToStr + acor + EXP + ccor
                           | doubleToStr + acor + EXP + ccor
                           | doubleToInt + acor + EXP + ccor;

            INTERRUMPIR.Rule = quiebre;

            CONTINUAR.Rule = continuar;

            RETORNO.Rule = retornar + EXP;

            LLAMADA.Rule = id + acor + EXPS + ccor;

            CONTROL.Rule = IF1
                           | IF2
                           | IF3
                           | IF5
                           | SWITCH
                           | WHILE
                           | DO_WHILE
                           | FOR
                           | LOOP
                           | REPEAT;

            IF1.Rule = si + EXP + dosp + Eos + BLOQUE;

            IF2.Rule = si + EXP + dosp + Eos + BLOQUE + sino + dosp + Eos + BLOQUE;

            IF3.Rule = si + EXP + dosp + Eos + BLOQUE + IF4;

            IF5.Rule = si + EXP + dosp + Eos + BLOQUE + IF4 + sino + dosp + Eos + BLOQUE;

            IF4.Rule = IF4 + sinosi + EXP + dosp + Eos + BLOQUE
                       | sinosi + EXP + dosp + Eos + BLOQUE;

            SWITCH.Rule = selector + caso + EXP + dosp + Eos + BCASO;

            BCASO.Rule = Indent + CASOS + DEFECTO + Dedent
                         | Indent + CASOS + Dedent;

            CASOS.Rule = MakeStarRule(CASOS, CASO);

            CASO.Rule = EXP + dosp + Eos + BLOQUE;

            DEFECTO.Rule = defecto + dosp + Eos + BLOQUE;

            WHILE.Rule = mientras + EXP + dosp + Eos + BLOQUE;

            DO_WHILE.Rule = hacer + dosp + Eos + BLOQUE + mientras + EXP + Eos;

            REPEAT.Rule = repetir + dosp + Eos + BLOQUE + hasta + EXP + Eos;

            Fasignar.Rule = DECLARACION
                            | ASIGNACION;

            FOR.Rule = para + acor + Fasignar + dosp + EXP + dosp + EXP + ccor + dosp + Eos + BLOQUE;

            LOOP.Rule = loop + dosp + Eos + BLOQUE;

            TPROC.Rule = funcion + TIPO + ARR
                         | metodo;

            TIPO.Rule = vacio
                        | num
                        | dec
                        | caracter
                        | str
                        | boolean
                        | id;

            NARREGLO.Rule = id + INDICES;

            EXP.Rule = EXP + EXP + ToTerm("or")
                       | EXP + EXP + ToTerm("and")
                       | EXP + EXP + ToTerm("xor")
                       | EXP + EXP + ToTerm("==")
                       | EXP + EXP + ToTerm("!=")
                       | EXP + EXP + ToTerm(">")
                       | EXP + EXP + ToTerm("<")
                       | EXP + EXP + ToTerm(">=")
                       | EXP + EXP + ToTerm("<=")
                       | EXP + EXP + ToTerm("+")
                       | EXP + EXP + ToTerm("-")
                       | EXP + EXP + ToTerm("*")
                       | EXP + EXP + ToTerm("/")
                       | EXP + EXP + ToTerm("pow")
                       | apar + EXP + cpar
                       | acor + EXP + ccor
                       | EXP + ToTerm("-")
                       | EXP + ToTerm("not")
                       | CRECE
                       | NUEVO
                       | LLAMADA
                       | NATIVAS
                       | super + punto + ACCESO
                       | self + punto + ACCESO
                       | ACCESO
                       | numero
                       | tstring
                       | tchar
                       | BANDERA;

            BANDERA.Rule = falso
                           | verdadero;

            NUEVO.Rule = nuevo + id + acor + EXPS + ccor;

            ACCESO.Rule = MakeStarRule(ACCESO, punto, TACCESO);

            TACCESO.Rule = LLAMADA
                           | id
                           | NARREGLO;

            DIM.Rule = acor + EXP + ccor;

            EXPS.Rule = MakeStarRule(EXPS, coma, EXP);

            CRECE.Rule = EXP + ToTerm("++")
                         | EXP + ToTerm("--");

            //Definir Asociatividad
            RegisterOperators(1, Associativity.Left, "or");                             //OR,NOR
            RegisterOperators(2, Associativity.Left, "and");                            //AND,NAND
            RegisterOperators(3, Associativity.Left, "xor");                            //XOR
            RegisterOperators(4, Associativity.Right, "not");                           //NOT
            RegisterOperators(5, Associativity.Left, "==", "!=", ">", "<", ">=", "<="); //MAYORQUES,MENORQUES,IGUAL,DIFERENTE
            RegisterOperators(6, Associativity.Left, "+", "-");                         //MAS,MENOS
            RegisterOperators(7, Associativity.Left, "*", "/");                         //POR,DIVIDIR,MOD
            RegisterOperators(8, Associativity.Right, "-");                             //UNARIO
            RegisterOperators(9, Associativity.Left, "pow");                            //POTENCIA
            RegisterOperators(10, Associativity.Left, "++", "--");

            //Manejo de Errores Lexicos y Sintacticos
            SENTENCIA.ErrorRule = SyntaxError + SENTENCIA;
            CUERPO.ErrorRule    = SyntaxError + CUERPO;
            CASOS.ErrorRule     = SyntaxError + CASO;

            //Eliminacion de caracters, no terminales que son estorbos
            this.MarkPunctuation("(", ")", ":", "=>", ",", ".", "[", "]", "://", "/");
            this.MarkPunctuation("clase", "si", "si_no_si", "si_no", "elegir", "caso", "defecto", "hacer", "mientras", "loop", "repetir", "para", "return", "continuar", "salir");
            this.MarkTransient(AID, asignarR, IMPORTACIONES, IMPORTAR, ARCHIVO, TACCESO, SENTENCIA, DIM, DIM2, CONTROL, TIPO, DEFECTO);
        }
Esempio n. 24
0
        public Gramatica() : base(caseSensitive: true)
        {
            #region ER
            var numero                = TerminalFactory.CreateCSharpNumber("numero");
            IdentifierTerminal id     = new IdentifierTerminal("id");
            StringLiteral      cadena = TerminalFactory.CreateCSharpString("cadena");
            var caracter              = TerminalFactory.CreateCSharpChar("caracter");
            #endregion

            #region Terminales
            /*  OPERADORES ARITMETICOS  */
            var mas   = ToTerm("+");
            var menos = ToTerm("-");
            var por   = ToTerm("*");
            var div   = ToTerm("/");
            /*  OPERADORES COMPARAR   */
            var igual       = ToTerm("==");
            var menor       = ToTerm("<");
            var mayor       = ToTerm(">");
            var menor_igual = ToTerm("<=");
            var mayor_igual = ToTerm(">=");
            var diferente   = ToTerm("!=");

            /*  OPERADORES LOGICOS
             * var or = ToTerm("||");
             * var and = ToTerm("&&");
             * var not = ToTerm("!");
             * var nand = ToTerm("!&&");
             * var nor = ToTerm("!||");
             * var xor = ToTerm("|&"); */
            /*  TIPOS DE DATOS  */
            var tipo_cadena   = ToTerm("cadena");
            var tipo_caracter = ToTerm("caracter");
            var tipo_entero   = ToTerm("entero");
            var tipo_doble    = ToTerm("doble");
            var tipo_bool     = ToTerm("boolean");
            /*  SENTENCIAS DE CONTROL   */
            var sentencia_si       = ToTerm("si");
            var sentencia_sino     = ToTerm("sino");
            var sentencia_para     = ToTerm("para");
            var sentencia_mientras = ToTerm("mientras");
            var sentencia_hacer    = ToTerm("hacer");

            #endregion

            #region No Terminales
            NonTerminal S           = new NonTerminal("S"),
                        PROGRAMA    = new NonTerminal("PROGRAMA"),
                        SENTENCIA   = new NonTerminal("SENTENCIA"),
                        CONDICION   = new NonTerminal("CONDICION"),
                        INICIO_PARA = new NonTerminal("INICIO PARA"),
                        FIN_PARA    = new NonTerminal("FIN PARA"),
                        SI          = new NonTerminal("SI"),
                        SINO        = new NonTerminal("SINO"),
                        PARA        = new NonTerminal("PARA"),
                        MIENTRAS    = new NonTerminal("MIENTRAS"),
                        HACER       = new NonTerminal("HACER"),
                        L_ID        = new NonTerminal("LST ID"),
                        ASIGNACION  = new NonTerminal("ASIGNACION"),
                        COMPARACION = new NonTerminal("COMPARACION"),
                        DECLARACION = new NonTerminal("DECLARAR"),
                        COMPARAR    = new NonTerminal("COMPARAR"),
                        TIPO        = new NonTerminal("TIPO"),
                        E           = new NonTerminal("E");

            #endregion

            #region Gramatica
            S.Rule = PROGRAMA;

            PROGRAMA.Rule = MakePlusRule(PROGRAMA, SENTENCIA);

            SENTENCIA.Rule = SI | PARA | MIENTRAS | HACER | ASIGNACION;

            /*
             * si ( CONDICION ) ¿ SENTENCIA ? sino ¿ SENTENCIA ?
             * para ( INICIO_PARA ; FIN_PARA; CONDICION) ¿ SENTENCIA ?
             * mientras ( CONDICION ) ¿ SENTENCIA ?
             * hacer ¿ SENTENCIA ? mientras ( CONDICION ) $
             */
            SI.Rule = sentencia_si + ToTerm("(") + COMPARACION + ToTerm(")") +
                      ToTerm("¿") + SENTENCIA + ToTerm("?") +
                      sentencia_sino + ToTerm("¿") + SENTENCIA + ToTerm("?");

            PARA.Rule = sentencia_para + ToTerm("(") + ASIGNACION + ToTerm(";") + COMPARACION + ToTerm(";") + COMPARACION + ToTerm(")") +
                        ToTerm("¿") + SENTENCIA + ToTerm("?");

            MIENTRAS.Rule = sentencia_mientras + ToTerm("(") + COMPARACION + ToTerm(")") +
                            ToTerm("¿") + SENTENCIA + ToTerm("?");

            HACER.Rule = sentencia_hacer + ToTerm("¿") + SENTENCIA + ToTerm("?") +
                         sentencia_mientras + ToTerm("(") + COMPARACION + ToTerm(")") + ToTerm("$");

            /*
             * CONDICION -> COMPARACION
             * INICIO_PARA -> ASIGNACION
             * FIN_PARA  -> COMPARACION
             */
            ASIGNACION.Rule = DECLARACION + ToTerm("=") + E + ToTerm("$");

            DECLARACION.Rule = TIPO + id;

            COMPARACION.Rule = E + COMPARAR + E;

            TIPO.Rule = tipo_cadena | tipo_caracter | tipo_doble | tipo_entero | tipo_bool;

            COMPARAR.Rule = igual | menor | mayor | menor_igual | mayor_igual | diferente;

            E.Rule = E + mas + E
                     | E + menos + E
                     | E + por + E
                     | E + div + E
                     | ToTerm("(") + E + ToTerm(")")
                     | numero
                     | id
                     | cadena
                     | caracter;

            #endregion

            #region Preferencias
            this.Root = S;

            this.RegisterOperators(20, Associativity.Left, mas, menos);
            this.RegisterOperators(30, Associativity.Left, por, div);

            this.MarkPunctuation("(", ")", ",", ";", "=", "¿", "?", "$");

            this.MarkTransient(S, SENTENCIA, TIPO);

            #endregion
        }
Esempio n. 25
0
        private void InitializeSyntax()
        {
            #region Identifiers
            var id_literal     = TerminalFactory.CreateCSharpIdentifier("IDENTIFICADOR");
            var number_literal = TerminalFactory.CreateCSharpNumber("NUMERO");
            var string_literal = TerminalFactory.CreateCSharpString("CADENA");
            var true_literal   = ToTerm("TRUE", "LOGICO_TRUE");
            var false_literal  = ToTerm("FALSE", "LOGICO_FALSE");
            #endregion

            #region NonTerminal
            NonTerminal program = new NonTerminal("PROGRAMA");

            NonTerminal define_dec  = new NonTerminal("DEFINIR");
            NonTerminal define_list = new NonTerminal("DEFINICIONES");

            NonTerminal import_dec  = new NonTerminal("IMPORTAR");
            NonTerminal import_list = new NonTerminal("IMPORTACIONES");

            NonTerminal member      = new NonTerminal("MIEMBRO");
            NonTerminal member_list = new NonTerminal("MIEMBROS");

            NonTerminal var_dec            = new NonTerminal("VARIABLE");
            NonTerminal var_type           = new NonTerminal("TIPO");
            NonTerminal var_dec_list       = new NonTerminal("VARIABLES");
            NonTerminal var_dec_list_names = new NonTerminal("LISTA_VARIABLES");
            NonTerminal var_dec_asign      = new NonTerminal("VARIABLE_DECLARACION");

            NonTerminal function_dec  = new NonTerminal("FUNCION");
            NonTerminal function_type = new NonTerminal("TIPO_FUNCION");
            NonTerminal parameters    = new NonTerminal("PARAMETROS");
            NonTerminal parameter     = new NonTerminal("PARAMETRO");

            NonTerminal var_asign = new NonTerminal("ASIGNACION_VARIABLE");

            NonTerminal print = new NonTerminal("MOSTRAR");

            NonTerminal statements = new NonTerminal("SENTENCIAS");
            NonTerminal statement  = new NonTerminal("SENTENCIA");
            NonTerminal op         = new NonTerminal("OPERANDO");
            NonTerminal ar         = new NonTerminal("OPERACION");
            NonTerminal operand    = new NonTerminal("OPERANDO");
            NonTerminal ao         = new NonTerminal("AR_OP");
            NonTerminal expression = new NonTerminal("EXPRESION");
            NonTerminal co         = new NonTerminal("COMPARADOR");
            NonTerminal bo         = new NonTerminal("OPERADOR_BOOLEANO");
            NonTerminal scope      = new NonTerminal("AMBITO");
            NonTerminal if_block   = new NonTerminal("SI");
            NonTerminal else_dec   = new NonTerminal("SINO");
            #endregion

            #region Gramaticas

            #region Program
            NonTerminal program_member = new NonTerminal("MIEMBRO_PROGRAMA");

            program.Rule = MakeStarRule(program, program_member);

            program_member.Rule = import_dec + ";" | define_dec + ";" | var_dec + ToTerm(";") | function_dec;


            #endregion

            #region Import
            import_dec.Rule = "Importar" + string_literal;
            #endregion

            #region Definir
            define_dec.Rule = "Definir" + string_literal
                              | "Definir" + number_literal;
            #endregion

            #region Funciones

            function_dec.Rule = ToTerm("Vacio") + id_literal + ToTerm("(") + parameters + ToTerm(")") + scope
                                | var_type + id_literal + ToTerm("(") + parameters + ToTerm(")") + scope;

            function_type.Rule = var_type | ToTerm("Vacio");

            parameters.Rule = MakeStarRule(parameters, ToTerm(","), parameter);

            parameter.Rule = var_type + id_literal;

            NonTerminal func_call        = new NonTerminal("LLAMADA_FUNCION");
            NonTerminal func_call_params = new NonTerminal("PARAMETROS_LLAMADA");

            func_call.Rule        = id_literal + ToTerm("(") + func_call_params + ToTerm(")");
            func_call_params.Rule = MakeStarRule(func_call_params, ToTerm(","), expression);

            NonTerminal func_return = new NonTerminal("RETORNO")
            {
                Rule = "Retorno" + expression
                       | "Retorno"
            };

            #endregion

            #region Variables
            var_dec.Rule = var_type + var_dec_list_names
                           | var_type + var_dec_list_names + ToTerm("=") + expression;

            var_type.Rule = ToTerm("Int") | ToTerm("Char") | ToTerm("Bool") | ToTerm("String") | ToTerm("Double");

            var_dec_list_names.Rule = MakePlusRule(var_dec_list_names, ToTerm(","), id_literal);

            var_asign.Rule = id_literal + ToTerm("=") + expression;
            #endregion

            #region Expresion
            op.Rule = string_literal
                      | number_literal
                      | id_literal
                      | true_literal
                      | false_literal
                      | func_call;

            ar.Rule = ar + ToTerm("+") + ar
                      | ar + ToTerm("-") + ar
                      | ar + ToTerm("*") + ar
                      | ar + ToTerm("/") + ar
                      | ar + ToTerm("^") + ar
                      | ar + ToTerm("~") + ar
                      | ar + ToTerm("%") + ar
                      | ToTerm("(") + ar + ToTerm(")")
                      | ToTerm("-") + ar
                      | op;

            ao.Rule = ToTerm("+")
                      | ToTerm("-")
                      | ToTerm("/")
                      | ToTerm("*");

            expression.Rule = expression + bo + expression
                              | ToTerm("!") + operand
                              | operand;

            operand.Rule = ar
                           | ar + co + ar;

            bo.Rule = ToTerm("&&") | ToTerm("||") | ToTerm("|&");

            co.Rule = ToTerm(">") | ToTerm(">=") | ToTerm("<") | ToTerm("<=") | ToTerm("==") | ToTerm("!=");

            #endregion

            #region print
            print.Rule = ToTerm("Mostrar") + ToTerm("(") + func_call_params + ToTerm(")");
            #endregion

            #region If Else
            if_block.Rule = ToTerm("Si") + "(" + expression + ")" + scope
                            | ToTerm("Si") + "(" + expression + ")" + scope + else_dec;

            else_dec.Rule = ToTerm("Sino") + scope;
            #endregion

            #region While
            NonTerminal while_block = new NonTerminal("MIENTRAS")
            {
                Rule = "Mientras" + ToTerm("(") + expression + ToTerm(")") + scope
            };
            #endregion

            #region Repetir
            NonTerminal repeat_block = new NonTerminal("REPETIR")
            {
                Rule = ToTerm("Hasta") + ToTerm("(") + expression + ToTerm(")") + scope
            };
            #endregion

            #region Para
            NonTerminal for_var_asign = new NonTerminal("VARIABLE")
            {
                Rule = ToTerm("Double") + id_literal + "=" + expression
            };

            NonTerminal for_var_action = new NonTerminal("ACCION_FOR")
            {
                Rule = ToTerm("++") | ToTerm("--")
            };

            NonTerminal for_block = new NonTerminal("PARA")
            {
                Rule = ToTerm("Para") + ToTerm("(") + for_var_asign + ";" + expression + ";" + for_var_action + ToTerm(")") + scope
            };
            #endregion

            #region Break
            NonTerminal break_stmt = new NonTerminal("DETENER")
            {
                Rule = ToTerm("Detener")
            };
            #endregion

            #region Continue
            NonTerminal continue_stmt = new NonTerminal("CONTINUAR")
            {
                Rule = ToTerm("Continuar")
            };
            #endregion

            #region Selecciona
            NonTerminal switch_block = new NonTerminal("SELECCIONA");
            NonTerminal switch_body  = new NonTerminal("CASOS");

            NonTerminal case_block = new NonTerminal("CASO");
            NonTerminal def_block  = new NonTerminal("DEFECTO");
            NonTerminal case_list  = new NonTerminal("LISTA_CASOS");

            switch_block.Rule = "Selecciona" + ToTerm("(") + expression + ToTerm(")") + switch_body;

            case_block.Rule = expression + ToTerm(":") + statements;

            case_list.Rule = MakePlusRule(case_list, case_block);

            switch_body.Rule = ToTerm("{") + case_list + def_block + ToTerm("}")
                               | ToTerm("{") + case_list + ToTerm("}");

            def_block.Rule = "Defecto" + ToTerm(":") + statements;
            #endregion

            #region Statements
            scope.Rule = ToTerm("{") + statements + ToTerm("}");

            statements.Rule = MakeStarRule(statements, statement);

            statement.Rule = var_dec + ";"
                             | var_asign + ";"
                             | if_block
                             | switch_block
                             | while_block
                             | repeat_block
                             | for_block
                             | func_call + ";"
                             | func_return + ";"
                             | print + ";"
                             | continue_stmt + ";"
                             | break_stmt + ";";

            statement.ErrorRule = SyntaxError + ";" | SyntaxError + "}";
            #endregion
            #endregion

            #region Preferencias
            MarkReservedWords("Importar", "Definir", "Int", "String", "Bool", "Char", "Double", "Vacio", "Si", "Sino", "true", "false", "Retorno", "Continuar", "Detener", "Mientras", "Para");

            MarkTransient(scope, member, member_list, statement, var_type, for_var_action);

            RegisterBracePair("(", ")");
            RegisterBracePair("{", "}");

            RegisterOperators(1, Associativity.Left, ToTerm("+"), ToTerm("-"));
            RegisterOperators(2, Associativity.Left, ToTerm("/"), ToTerm("*"), ToTerm("%"));
            RegisterOperators(3, Associativity.Left, ToTerm("^"));
            //comparissons
            RegisterOperators(4, Associativity.Left, ToTerm("<"), ToTerm(">"), ToTerm("<="), ToTerm(">="), ToTerm("~"));
            //booleans
            RegisterOperators(5, Associativity.Left, ToTerm("||"));
            RegisterOperators(6, Associativity.Left, ToTerm("|&"));
            RegisterOperators(7, Associativity.Left, ToTerm("&&"));
            RegisterOperators(8, Associativity.Right, ToTerm("!"));
            RegisterOperators(9, Associativity.Left, ToTerm("("), ToTerm(")"));

            Root = program;
            #endregion
        }
Esempio n. 26
0
        public Gramatica() : base(false) //no es case sensitive
        {
            #region Terminales
            #region Comentarios
            CommentTerminal comentarioLinea  = new CommentTerminal("comentarioLinea", "$$", "\n", "\r\n");
            CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "$#", "#$");
            base.NonGrammarTerminals.Add(comentarioLinea);
            base.NonGrammarTerminals.Add(comentarioBloque);
            #endregion

            #region ExpresionesRegulares
            IdentifierTerminal id = new IdentifierTerminal("id");
            //NumberLiteral number = new NumberLiteral("number");
            var           number   = TerminalFactory.CreateCSharpNumber("number");
            StringLiteral cadena   = new StringLiteral("cadena", "\"", StringOptions.AllowsAllEscapes);
            StringLiteral caracter = new StringLiteral("caracter", "\'", StringOptions.IsChar);
            #endregion

            #region PalabrasReservadas
            KeyTerm miEntero    = ToTerm("entero"),
                    miDecimal   = ToTerm("decimal"),
                    miCadena    = ToTerm("cadena"),
                    miCaracter  = ToTerm("caracter"),
                    miBooleano  = ToTerm("booleano"),
                    miVacio     = ToTerm("vacio"),
                    miPrincipal = ToTerm("principal", "miPrincipal"),
                    miRetorno   = ToTerm("retorno"),
                    miRomper    = ToTerm("romper"),
                    miDefecto   = ToTerm("defecto"),
                    miContinuar = ToTerm("continuar"),
                    miIf        = ToTerm("si"),
                    miElse      = ToTerm("sino"),
                    miDo        = ToTerm("hacer"),
                    miWhile     = ToTerm("mientras"),
                    miFor       = ToTerm("repetir"),
                    miHasta     = ToTerm("hasta"),
                    miPrint     = ToTerm("imprimir"),
                    miVerdadero = ToTerm("verdadero", "miVerdadero"),
                    miFalso     = ToTerm("falso", "miFalso")
            ;

            MarkReservedWords("entero", "decimal", "cadena", "caracter",
                              "booleano", "vacio", "principal", "retorno", "defecto",
                              "continuar", "si", "sino", "hacer", "mientras", "repetir",
                              "hasta", "imprimir", "verdadero", "falso");

            #endregion

            #region Simbolos
            Terminal parizq        = ToTerm("("),
                     parder        = ToTerm(")"),
                     llaveizq      = ToTerm("{"),
                     llaveder      = ToTerm("}"),
                     mas           = ToTerm("+"),
                     menos         = ToTerm("-"),
                     por           = ToTerm("*"),
                     div           = ToTerm("/"),
                     potencia      = ToTerm("^"),
                     modulo        = ToTerm("%"),
                     coma          = ToTerm(","),
                     punto         = ToTerm("."),
                     ptComa        = ToTerm(";"),
                     igual         = ToTerm("="),
                     masMas        = ToTerm("++"),
                     menosMenos    = ToTerm("--"),
                     miOr          = ToTerm("||"),
                     miAnd         = ToTerm("&&"),
                     not           = ToTerm("!"),
                     igualIgual    = ToTerm("=="),
                     diferente     = ToTerm("!="),
                     mayorQue      = ToTerm(">"),
                     mayorIgualQue = ToTerm(">="),
                     menorQue      = ToTerm("<"),
                     menorIgualQue = ToTerm("<=")
            ;
            #endregion

            #endregion

            #region NoTerminales
            NonTerminal S                  = new NonTerminal("S"),
                        CUERPO             = new NonTerminal("CUERPO"),
                        CAMPOS             = new NonTerminal("CAMPOS"),
                        METODO             = new NonTerminal("METODO"),
                        SENTENCIAS         = new NonTerminal("SENTENCIAS"),
                        LISTA_SENTENCIA    = new NonTerminal("LISTA_SENTENCIA"),
                        DECLARACION        = new NonTerminal("DECLARACION"),
                        ASIGNACION         = new NonTerminal("ASIGNACION"),
                        LISTA_IDS          = new NonTerminal("LISTA_IDS"),
                        LISTA_PARAM        = new NonTerminal("LISTA_PARAM"),
                        PARAMETRO          = new NonTerminal("PARAMETRO"),
                        LISTA_ATRI         = new NonTerminal("LISTA_ATRI"),
                        ATRIBUTO           = new NonTerminal("ATRIBUTO"),
                        SENTENCIA          = new NonTerminal("SENTENCIA"),
                        SENTENCIA_IF       = new NonTerminal("SENTENCIA_IF"),
                        SENTENCIA_WHILE    = new NonTerminal("SENTENCIA_WHILE"),
                        SENTENCIA_BREAK    = new NonTerminal("SENTENCIA_BREAK"),
                        SENTENCIA_CONTINUE = new NonTerminal("SENTENCIA_CONTINUE"),
                        SENTENCIA_RETURN   = new NonTerminal("SENTENCIA_RETURN"),
                        SENTENCIA_PRINT    = new NonTerminal("SENTENCIA_PRINT"),
                        SENTENCIA_CLASE    = new NonTerminal("SENTENCIA_CLASE"),
                        LLAMADA            = new NonTerminal("LLAMADA"),
                        ACCESO             = new NonTerminal("ACCESO"),
                        EXP                = new NonTerminal("EXP"),
                        EXP_ARIT           = new NonTerminal("EXP_ARIT"),
                        EXP_REL            = new NonTerminal("EXP_REL"),
                        EXP_LOG            = new NonTerminal("EXP_LOG"),
                        LISTA_ARG          = new NonTerminal("LISTA_ARG"),
                        TIPO               = new NonTerminal("TIPO"),
                        TIPO_PRIM          = new NonTerminal("TIPO_PRIM")
            ;
            #endregion

            #region GramaticaAntigua
            //NonTerminal S = new NonTerminal("S"),
            //            I = new NonTerminal("I"),
            //            CUERPO = new NonTerminal("CUERPO"),
            //            DECLARACION_GLOBAL = new NonTerminal("DECLARACION_GLOBAL"),
            //            LISTA_IDS = new NonTerminal("LISTA_IDS"),
            //            METODO = new NonTerminal("METODO"),
            //            MT_ENCABEZADO = new NonTerminal("MT_ENCABEZADO"),
            //            MT_CUERPO = new NonTerminal("MT_CUERPO"),
            //            SENTENCIA = new NonTerminal("SENTENCIA"),
            //            ASIGNACION = new NonTerminal("ASIGNACION"),
            //            DECLARACION_LOCAL = new NonTerminal("DECLARACION_LOCAL"),
            //            MT_LLAMADA = new NonTerminal("MT_LLAMADA"),
            //            //PLOT = new NonTerminal("PLOT"),
            //            //IMG = new NonTerminal("IMG"),
            //            MT_RETURN = new NonTerminal("MT_RETURN"),
            //            E = new NonTerminal("E")//,
            //MT_PARAMETROS = new NonTerminal("MT_PARAMETROS"),
            //FUNCION = new NonTerminal("FUNCION"),
            //FUNC_CUERPO = new NonTerminal("FUNC_CUERPO"),
            //SENTENCIA2 = new NonTerminal("SENTENCIA2"),
            //FUNC_RETURN = new NonTerminal("FUNC_RETURN"),
            //CONSTANTES = new NonTerminal("CONSTANTES"),
            //DIMENSION = new NonTerminal("DIMENSION"),
            //MAIN = new NonTerminal("MAIN"),
            //MAIN_CUERPO = new NonTerminal("MAIN_CUERPO"),
            //SENTENCIA3 = new NonTerminal("SENTENCIA3")
            ;
            #endregion

            S.Rule = CUERPO;

            CUERPO.Rule = MakePlusRule(CUERPO, CAMPOS);

            CAMPOS.Rule = METODO
                          | DECLARACION + ptComa;
            //| id
            //| SENTENCIA_CLASE
            ;

            METODO.Rule = TIPO + id + parizq + LISTA_PARAM + parder + SENTENCIAS
                          | id + id + parizq + LISTA_PARAM + parder + SENTENCIAS
                          | TIPO + id + parizq + parder + SENTENCIAS
                          | id + id + parizq + parder + SENTENCIAS
                          | miPrincipal + parizq + parder + SENTENCIAS
            ;

            LISTA_PARAM.Rule = MakePlusRule(LISTA_PARAM, coma, PARAMETRO);

            PARAMETRO.Rule = TIPO + id;

            //Lista de atributos
            //atributo

            SENTENCIAS.Rule = llaveizq + LISTA_SENTENCIA + llaveder;

            LISTA_SENTENCIA.Rule = MakePlusRule(LISTA_SENTENCIA, SENTENCIA);

            SENTENCIA.Rule = DECLARACION + ptComa

                             /*| ASIGNACION + ptComa
                              | ACCESO + ptComa*/
                             | LLAMADA + ptComa
                             | SENTENCIA_IF
                             /*| SENTENCIA_WHILE*/
                             | SENTENCIA_RETURN + ptComa

                             /*| SENTENCIA_BREAK + ptComa
                              | SENTENCIA_CONTINUE + ptComa*/
                             | SENTENCIA_PRINT + ptComa
                             //| SENTENCIA_CLASE + ptComa
            ;

            DECLARACION.Rule = TIPO + LISTA_IDS + "=" + EXP
                               | TIPO + LISTA_IDS
                               | id + id
            ;

            /*ASIGNACION.Rule = LISTA_IDS + "=" + EXP
             | id + "." + id + "=" + EXP
             |                ;*/

            LISTA_IDS.Rule = MakePlusRule(LISTA_IDS, coma, id);

            SENTENCIA_IF.Rule = miIf + parizq + EXP + parder + SENTENCIAS
                                | miIf + parizq + EXP + parder + SENTENCIAS + miElse + SENTENCIAS
            ;

            /*SENTENCIA_WHILE.Rule = miWhile + parizq + EXP + parder + SENTENCIAS
             *  ;*/

            SENTENCIA_RETURN.Rule = miRetorno + EXP
                                    | miRetorno;

            /*SENTENCIA_BREAK.Rule = miRomper;
             *
             * SENTENCIA_CONTINUE.Rule = miContinuar;*/

            SENTENCIA_PRINT.Rule = miPrint + parizq + EXP + parder;

            //Pendiente sentencia struct

            LLAMADA.Rule = id + parizq + LISTA_ARG + parder
                           | id + parizq + parder
            ;

            /*ACCESO.Rule = id + "." + id;*/

            EXP.Rule = EXP_ARIT                //YAPP
                       | EXP_LOG               //YAP
                       | EXP_REL               //YAP
                       | TIPO_PRIM             //YAPP
                                               // | ACCESO
                       | parizq + EXP + parder //YAP
                       | LLAMADA               //YAP
            ;

            EXP_LOG.Rule = EXP + miOr + EXP
                           | EXP + miAnd + EXP
                           | not + EXP
            ;

            EXP_REL.Rule = EXP + igualIgual + EXP
                           | EXP + diferente + EXP
                           | EXP + menorQue + EXP
                           | EXP + mayorQue + EXP
                           | EXP + menorIgualQue + EXP
                           | EXP + mayorIgualQue + EXP
            ;

            EXP_ARIT.Rule = menos + EXP            //YAPP
                            | EXP + mas + EXP      //YAPP
                            | EXP + menos + EXP    //YAPP
                            | EXP + por + EXP      //YAPP
                            | EXP + div + EXP      //YAPP
                            | EXP + modulo + EXP   //YAPP
                            | EXP + potencia + EXP //YAPP
                            | EXP + menosMenos
                            | EXP + masMas
            ;

            TIPO_PRIM.Rule = number //YAPP
                             | cadena
                             | caracter
                             | miVerdadero
                             | miFalso
                             | id
            ;

            LISTA_ARG.Rule = MakeStarRule(LISTA_ARG, coma, EXP);

            TIPO.Rule = miBooleano
                        | miCaracter
                        | miCadena
                        | miEntero //YA
                        | miDecimal
                        | miVacio
            ;

            this.Root = S;


            #region Precedencia
            RegisterOperators(1, Associativity.Right, igual);
            RegisterOperators(2, Associativity.Left, miOr);
            RegisterOperators(3, Associativity.Left, miAnd);
            RegisterOperators(4, Associativity.Left, igualIgual, diferente);
            RegisterOperators(5, Associativity.Left, menorQue, menorIgualQue, mayorQue, mayorIgualQue);
            RegisterOperators(6, Associativity.Left, mas, menos);
            RegisterOperators(7, Associativity.Left, por, div, modulo);
            RegisterOperators(8, Associativity.Right, potencia);
            RegisterOperators(9, Associativity.Right, masMas, menosMenos, not);


            MarkPunctuation(parizq, parder, llaveder, llaveizq, ptComa, coma, igual, punto);
            #endregion
        }
Esempio n. 27
0
        public Language()
            : base(false)
        {
            CommentTerminal LINE_COMMENT  = new CommentTerminal("LINE_COMMENT", ">>", "\n", "\r\n");
            CommentTerminal BLOCK_COMMENT = new CommentTerminal("BLOCK_COMMENT", "<-", "->");

            NonGrammarTerminals.Add(BLOCK_COMMENT);
            NonGrammarTerminals.Add(LINE_COMMENT);

            ////----------------------------------Terminals with precedence
            KeyTerm increase         = ToTerm("++");
            KeyTerm decrease         = ToTerm("--");
            KeyTerm plus             = ToTerm("+");
            KeyTerm minus            = ToTerm("-");
            KeyTerm by               = ToTerm("*");
            KeyTerm divided          = ToTerm("/");
            KeyTerm power            = ToTerm("^");
            KeyTerm lessThan         = ToTerm("<");
            KeyTerm greaterThan      = ToTerm(">");
            KeyTerm lessThanEqual    = ToTerm("<=");
            KeyTerm greaterThanEqual = ToTerm(">=");
            KeyTerm doubleEqual      = ToTerm("==");
            KeyTerm different        = ToTerm("!=");
            KeyTerm not              = ToTerm("!");
            KeyTerm and              = ToTerm("&&");
            KeyTerm or               = ToTerm("||");

            ////----------------------------------precedence
            this.RegisterOperators(1, Associativity.Left, or);
            this.RegisterOperators(2, Associativity.Left, and);
            this.RegisterOperators(3, Associativity.Left, not);
            this.RegisterOperators(4, Associativity.Left, doubleEqual, different, lessThan, lessThanEqual, greaterThan, greaterThanEqual);
            this.RegisterOperators(5, Associativity.Left, plus, minus);
            this.RegisterOperators(6, Associativity.Left, by, divided);
            this.RegisterOperators(7, Associativity.Left, power);
            //Regex
            var integer  = new RegexBasedTerminal("int", "[0-9]+");
            var tdouble  = TerminalFactory.CreateCSharpNumber("double");
            var String   = TerminalFactory.CreateCSharpString("string");
            var caracter = TerminalFactory.CreateCSharpChar("char");
            var boolean  = new RegexBasedTerminal("bool", "(true)|(false)");
            var iden     = TerminalFactory.CreateCSharpIdentifier("id");
            var hexa     = new RegexBasedTerminal("hexa", "^(\\#)[0-9A-F]+$");
            //Non terminals
            var START               = new NonTerminal("START");
            var BODY                = new NonTerminal("BODY");
            var DECLARATION         = new NonTerminal("DECLARATION");
            var DECLARATION2        = new NonTerminal("DECLARATION2");
            var ASSIGNATION         = new NonTerminal("ASSIGNATION");
            var ASSIGN2             = new NonTerminal("ASSIGN2");
            var INDEX               = new NonTerminal("INDEX");
            var DATATYPE            = new NonTerminal("DATATYPE");
            var OBJECT              = new NonTerminal("OBJECT");
            var ASSIGN              = new NonTerminal("ASSIGN");
            var ARRAY               = new NonTerminal("ARRAY");
            var ARRAY2              = new NonTerminal("ARRAY2");
            var ARRAYASIGN          = new NonTerminal("ARRAYASIGN");
            var ARRAYASIGN2         = new NonTerminal("ARRAYASIGN2");
            var ARRAYASIGN3         = new NonTerminal("ARRAYASIGN3");
            var ARRAYLIST           = new NonTerminal("ARRAYLIST");
            var NATIVE              = new NonTerminal("NATIVE");
            var PRINT               = new NonTerminal("PRINT");
            var SHOW                = new NonTerminal("SHOW");
            var IF                  = new NonTerminal("IF");
            var ELSE                = new NonTerminal("ELSE");
            var FOR                 = new NonTerminal("FOR");
            var REPEAT              = new NonTerminal("REPEAT");
            var WHILE               = new NonTerminal("WHILE");
            var VARMANAGMENT        = new NonTerminal("VARMANAGMENT");
            var UPDATE              = new NonTerminal("UPDATE");
            var ESINGLE             = new NonTerminal("ESINGLE");
            var E                   = new NonTerminal("E");
            var ID                  = new NonTerminal("ID");
            var IDPLUS              = new NonTerminal("IDPLUS");
            var ARRAYS              = new NonTerminal("ARRAYS");
            var DOWHILE             = new NonTerminal("DOWHILE");
            var SWITCH              = new NonTerminal("SWITCH");
            var CASE                = new NonTerminal("CASE");
            var DEFAULT             = new NonTerminal("DEFAULT");
            var CASELIST            = new NonTerminal("CASELIST");
            var FUNCTION            = new NonTerminal("FUNCTION");
            var FUNCTIONARGS        = new NonTerminal("FUNCTIONARGS");
            var VISIBILITY          = new NonTerminal("VISIBILITY");
            var OVERRIDE            = new NonTerminal("OVERRIDE");
            var PARAMLIST           = new NonTerminal("PARAMLIST");
            var PARAM               = new NonTerminal("PARAM");
            var OPTIONAL            = new NonTerminal("OPTIONAL");
            var RETURN              = new NonTerminal("RETURN");
            var RETOPTION           = new NonTerminal("RETOPTION");
            var LISTMETHODS         = new NonTerminal("LISTMETHODS");
            var CLASS               = new NonTerminal("CLASS");
            var EXTENDS             = new NonTerminal("EXTENDS");
            var EXTENDSLIST         = new NonTerminal("EXTENDSLIST");
            var CALLFUNC            = new NonTerminal("CALLFUNC");
            var ADDFIGURE           = new NonTerminal("ADDFIGURE");
            var GEOMETRICAS         = new NonTerminal("GEOMETRICAS");
            var COLOR               = new NonTerminal("COLOR");
            var FIGURE              = new NonTerminal("FIGURE");
            var MAIN                = new NonTerminal("MAIN");
            var CLASSIMPLEMENTATION = new NonTerminal("CLASSIMPLEMENTATION");
            var CFUNCLIST           = new NonTerminal("CFUNCLIST");
            var LISTCLASSMETHODS    = new NonTerminal("LISTCLASSMETHODS");
            var LISTCLASSMETHODS2   = new NonTerminal("LISTCLASSMETHODS2");
            var LISTOBJECTS         = new NonTerminal("LISTCLASSMETHODS2");

            ////----------------------------------Innecesary nodes
            this.MarkPunctuation(".", "(", ")", "{", "}", "[", "]", ";", "=", ",", "importar", "if", "for", "repeat", "mientras", "show", "hacer", "comprobar", "salir", "caso", ":", "print", "defecto", "clase", "addfigure", "main", "return");
            this.MarkTransient(DECLARATION2, LISTCLASSMETHODS2, CLASSIMPLEMENTATION, BODY, ASSIGN2, COLOR, ARRAY2, ARRAYASIGN, ARRAYASIGN2, ARRAYASIGN3, NATIVE, VARMANAGMENT, ESINGLE, ASSIGN, ARRAY, ADDFIGURE, RETOPTION);
            //----------------------------------Grammar
            START.Rule = MakePlusRule(START, CLASS);
            CLASS.Rule = "clase" + iden + EXTENDSLIST + "{" + CLASSIMPLEMENTATION + "}";

            CLASS.ErrorRule = SyntaxError + "}";
            CLASS.ErrorRule = SyntaxError + ";";

            CLASSIMPLEMENTATION.Rule = MakeStarRule(CLASSIMPLEMENTATION, LISTCLASSMETHODS);
            EXTENDSLIST.Rule         = MakeStarRule(EXTENDSLIST, ToTerm(","), EXTENDS);
            EXTENDS.Rule             = ToTerm("importar") + ID;
            LISTMETHODS.Rule         = MakePlusRule(LISTMETHODS, BODY);
            BODY.Rule = ID + ";" | FIGURE | ADDFIGURE | DECLARATION | ASSIGNATION | UPDATE + ";" | PRINT | SHOW | IF | FOR | REPEAT | WHILE | DOWHILE | SWITCH | OPTIONAL + ";" | Empty | CALLFUNC;
            //methods inside a function
            DECLARATION.Rule = DATATYPE + DECLARATION2 + ";";

            DECLARATION.ErrorRule = SyntaxError + ";";

            DECLARATION2.Rule = LISTOBJECTS | ToTerm("array") + ARRAYS;
            LISTOBJECTS.Rule  = MakePlusRule(LISTOBJECTS, ToTerm(","), OBJECT);
            ARRAYS.Rule       = ID + ARRAY;
            ASSIGN.Rule       = ToTerm("=") + E | Empty;
            ASSIGNATION.Rule  = ID + ASSIGN2 + ";";

            ASSIGNATION.ErrorRule = SyntaxError + ";";


            ASSIGN2.Rule = ToTerm("=") + E | "[" + E + "]" + ASSIGN2;
            PRINT.Rule   = ToTerm("print") + "(" + E + ")" + ";";

            PRINT.ErrorRule = SyntaxError + ";";

            SHOW.Rule = ToTerm("show") + "(" + E + "," + E + ")" + ";";

            SHOW.ErrorRule = SyntaxError + ";";

            IF.Rule = ToTerm("if") + "(" + E + ")" + "{" + LISTMETHODS + "}" + ELSE;

            IF.ErrorRule = SyntaxError + "}";
            IF.ErrorRule = SyntaxError + ";";

            ELSE.Rule = ToTerm("else") + IF | ToTerm("else") + "{" + LISTMETHODS + "}" | Empty;
            FOR.Rule  = ToTerm("for") + "(" + VARMANAGMENT + E + ";" + UPDATE + ")" + "{" + LISTMETHODS + "}";

            FOR.ErrorRule = SyntaxError + "}";
            FOR.ErrorRule = SyntaxError + ";";

            REPEAT.Rule = ToTerm("repeat") + "(" + E + ")" + "{" + LISTMETHODS + "}";

            REPEAT.ErrorRule = SyntaxError + "}";
            REPEAT.ErrorRule = SyntaxError + ";";

            VARMANAGMENT.Rule = DECLARATION | ASSIGNATION;
            UPDATE.Rule       = ESINGLE + increase | ESINGLE + decrease;
            WHILE.Rule        = ToTerm("mientras") + "(" + E + ")" + "{" + LISTMETHODS + "}";

            WHILE.ErrorRule = SyntaxError + "}";
            WHILE.ErrorRule = SyntaxError + ";";

            DOWHILE.Rule = ToTerm("hacer") + "{" + LISTMETHODS + "}" + ToTerm("mientras") + "(" + E + ")" + ";";

            DOWHILE.ErrorRule = SyntaxError + "}";
            DOWHILE.ErrorRule = SyntaxError + ";";

            SWITCH.Rule        = ToTerm("comprobar") + "(" + E + ")" + "{" + CASELIST + DEFAULT + "}";
            SWITCH.ErrorRule   = SyntaxError + "}";
            SWITCH.ErrorRule   = SyntaxError + ";";
            CASELIST.Rule      = MakePlusRule(CASELIST, CASE);
            CASE.Rule          = ToTerm("caso") + E + ":" + LISTMETHODS + ToTerm("salir") + ";";
            DEFAULT.Rule       = ToTerm("defecto") + ":" + LISTMETHODS + ToTerm("salir") + ";" | Empty;
            OPTIONAL.Rule      = RETURN | ToTerm("continue");
            RETURN.Rule        = ToTerm("return") + RETOPTION;
            RETOPTION.Rule     = Empty | E;
            CALLFUNC.Rule      = iden + "(" + CFUNCLIST + ")" + ";";
            CFUNCLIST.Rule     = MakeStarRule(CFUNCLIST, ToTerm(","), E);
            CALLFUNC.ErrorRule = SyntaxError + ";";
            ADDFIGURE.Rule     = ToTerm("addfigure") + "(" + GEOMETRICAS + ")" + ";";
            GEOMETRICAS.Rule   = ToTerm("circle") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + ")"
                                 | ToTerm("triangle") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + "," + E + "," + E + ")"
                                 | ToTerm("square") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + ")"
                                 | ToTerm("line") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + ")";
            GEOMETRICAS.ErrorRule = SyntaxError + ";";

            COLOR.Rule  = Empty | E; //it can be a string or id
            FIGURE.Rule = ToTerm("figure") + "(" + E + ")" + ";";
            //Methods inside a class
            LISTCLASSMETHODS.Rule  = VISIBILITY + LISTCLASSMETHODS2 | MAIN;
            LISTCLASSMETHODS2.Rule = DECLARATION | FUNCTION;
            MAIN.Rule     = ToTerm("main") + "(" + ")" + "{" + LISTMETHODS + "}";
            FUNCTION.Rule = iden + FUNCTIONARGS + "(" + PARAMLIST + ")" + "{" + LISTMETHODS + "}";

            FUNCTION.ErrorRule = SyntaxError + "}";
            FUNCTION.ErrorRule = SyntaxError + ";";


            FUNCTIONARGS.Rule = DATATYPE + OVERRIDE | ToTerm("array") + DATATYPE + INDEX + OVERRIDE | ToTerm("void");
            VISIBILITY.Rule   = Empty | ToTerm("publico") | ToTerm("privado");
            OVERRIDE.Rule     = Empty | ToTerm("override");
            PARAMLIST.Rule    = MakeStarRule(PARAMLIST, ToTerm(","), PARAM);
            PARAM.Rule        = iden + iden | DATATYPE + iden;
            //datatypes
            DATATYPE.Rule = ToTerm("int") | "bool" | "string" | "double" | "char" | iden;
            OBJECT.Rule   = ID + ASSIGN;
            //Making arrays
            ARRAY.Rule       = "=" + ARRAYASIGN | Empty;
            ARRAYASIGN.Rule  = ToTerm("{") + ARRAYASIGN2 + "}";
            ARRAYASIGN2.Rule = ARRAYASIGN3 | ARRAYLIST;
            ARRAYASIGN3.Rule = ARRAYASIGN | MakePlusRule(ARRAYASIGN3, ToTerm(","), ARRAYASIGN);
            ARRAYLIST.Rule   = MakePlusRule(ARRAYLIST, ToTerm(","), E);
            //Making EXP
            E.Rule = E + plus + E
                     | E + minus + E
                     | E + by + E
                     | E + divided + E
                     | E + power + E
                     | E + doubleEqual + E
                     | E + different + E
                     | E + lessThan + E
                     | E + greaterThan + E
                     | E + lessThanEqual + E
                     | E + greaterThanEqual + E
                     | E + or + E
                     | E + and + E
                     | not + E
                     | ESINGLE
                     | ToTerm("(") + E + ")"
                     | minus + E;

            ESINGLE.Rule = NATIVE | ID | ToTerm("new") + iden + "(" + CFUNCLIST + ")";
            INDEX.Rule   = INDEX + ToTerm("[") + E + "]" | Empty;
            ID.Rule      = iden + IDPLUS;
            IDPLUS.Rule  = INDEX | Empty | "(" + CFUNCLIST + ")" | "." + ID;
            NATIVE.Rule  = integer | caracter | String | boolean | tdouble;
            this.Root    = START;
        }
Esempio n. 28
0
        public QAsmGrammar()
        {
            NumberLiteral         = TerminalFactory.CreateCSharpNumber(NUMBER_LITERAL);
            NumberLiteral.Options = NumberOptions.AllowSign;

            Identifier    = new IdentifierTerminal("identifier", @"_", "_");
            StringLiteral = new StringLiteral(STRING_LITERAL, "\"", StringOptions.AllowsAllEscapes);

            NonGrammarTerminals.Add(new CommentTerminal("line-comment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"));

            MarkPunctuation("[", "]", ";", "::", ":", "&", ".", "(", ")", ",", "{", "}", "@");
            RegisterOperators(1, "+", "-");
            RegisterOperators(2, "*", "/");
            RegisterBracePair("[", "]");
            RegisterBracePair("{", "}");
            RegisterKeyTerms();
            CreateNonTerminals();

            directives.Rule  = MakeStarRule(directives, null, directive);
            directive.Rule   = instruction | declareFunction;
            instruction.Rule = iConst | iExtern | iLet | iIf | iBool | iRet | iMov | iAdd | iCalld;

            #region Instructions
            iConst.Rule  = kConst + variableQualifier + "," + constExpr + ";";
            iExtern.Rule = kExtern + variableQualifier + ";";
            iLet.Rule    = kLet + variableQualifier + ";";
            iBool.Rule   = kBool + valueAccessor + ";";
            iRet.Rule    = kRet + ";" | kRet + valueAccessor + ";";
            iMov.Rule    = kMov + destinationOperand + "," + valueAccessor + ";";
            iAdd.Rule    = kAdd + destinationOperand + "," + valueAccessor + ";";
            iCalld.Rule  = kCall + valueAccessor + "," + callparamsList + ";" |
                           kCall + valueAccessor + ";";
            #endregion

            #region CodeBlocks
            declareFunction.Rule = Identifier + "(" + paramsList + ")" + codeBlock;
            paramsList.Rule      = MakeStarRule(paramsList, ToTerm(","), variableQualifier);
            codeBlock.Rule       = ToTerm("[") + directives + ToTerm("]");
            iIf.Rule             = kIf + codeBlock + codeBlock + ToTerm(";");
            #endregion

            variableQualifier.Rule = Identifier + typeAccessor | Identifier;
            typeAccessor.Rule      = ToTerm(":") + builtinType | ToTerm(":") + Identifier;
            builtinType.Rule       = kByte | kWord | kDword | kQword | kString;
            constExpr.Rule         = NumberLiteral | StringLiteral | boolLiteral;
            boolLiteral.Rule       = kTrue | kFalse;
            functionPointer.Rule   = Identifier + "::" + Identifier;
            variableHandle.Rule    = ToTerm("&") + Identifier;
            valueAccessor.Rule     = memoryAccessor | variableHandle | Identifier | NumberLiteral | boolLiteral | functionPointer;
            memoryAccessor.Rule    = ToTerm("@") + "(" + valueDisplacementOptional + ")" + typeAccessor |
                                     ToTerm("@") + "(" + valueDisplacementOptional + ")";
            valueDisplacementOptional.Rule = valueAccessor + binOp + NumberLiteral | valueAccessor;
            destinationOperand.Rule        = memoryAccessor | variableQualifier;
            binOp.Rule          = ToTerm("+") | ToTerm("-");
            callparamsList.Rule = MakePlusRule(callparamsList, ToTerm(","), valueAccessor);

            // Marks all the rules that are able to be reduced, reducing the depth of the parsetree
            MarkTransient(directive, builtinType, instruction, valueAccessor, boolLiteral, destinationOperand, binOp);

            SyntaxParser = new Parser(this);
        }
Esempio n. 29
0
        public ReportingLanguage() : base(false)
        {
            // 1. Terminals

            var numberLiteral = TerminalFactory.CreateCSharpNumber("Number");

            var boolean = new ConstantTerminal("Boolean");

            boolean.Add("true", true);
            boolean.Add("false", false);
            boolean.Priority = 10;


            var nil = new ConstantTerminal("Null");

            nil.Add("null", null);
            nil.Add("nothing", null);
            nil.Priority = 10;

            var identifier = new IdentifierTerminal("Identifier");

            var stringLiteral = new StringLiteral("String", "'", StringFlags.AllowsDoubledQuote);

            stringLiteral.AddStartEnd("\"", StringFlags.AllowsAllEscapes);

            Terminal dot     = Symbol(".", "dot");
            Terminal less    = Symbol("<");
            Terminal greater = Symbol(">");
            Terminal LCb     = Symbol("(");
            Terminal RCb     = Symbol(")");
            Terminal RFb     = Symbol("}");
            Terminal LFb     = Symbol("{");
            Terminal comma   = Symbol(",");
//            Terminal LSb = Symbol("[");
//            Terminal RSb = Symbol("]");
            var exclamationMark = Symbol("!");

            Terminal and = Symbol("and");

            and.Priority = 10;

            Terminal or = Symbol("or");

            or.Priority = 10;

            var UserSection      = Symbol("User");
            var GlobalSection    = Symbol("Globals");
            var ParameterSection = Symbol("Parameters");
            var FieldsSection    = Symbol("Fields");

            // 2. Non-terminals

            var FieldRef             = new NonTerminal("FieldRef");
            var userSectionStmt      = new NonTerminal("UserSectionStmt");
            var globalSectionStmt    = new NonTerminal("GlobalSectionStmt");
            var parameterSectionStmt = new NonTerminal("ParameterSectionStmt");
            var fieldsSectionStmt    = new NonTerminal("FieldsSectionStmt");

            var QualifiedName      = new NonTerminal("QualifiedName");
            var FunctionExpression = new NonTerminal("FunctionExpression");

            var Condition   = new NonTerminal("Condition");
            var Conditional = new NonTerminal("IfThen");

            var Expr = new NonTerminal("Expr");

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


            var ExprList = new NonTerminal("ExprList");
            var BinExpr  = new NonTerminal("BinExpr", typeof(BinExprNode));

            var ProgramLine = new NonTerminal("ProgramLine");
            var Program     = new NonTerminal("Program", typeof(StatementListNode));

            // 3. BNF rules

            #region Reporting
            userSectionStmt.Rule = UserSection + exclamationMark + Symbol("UserId")
                                   | UserSection + exclamationMark + Symbol("Language");

            globalSectionStmt.Rule = GlobalSection + exclamationMark + Symbol("PageNumber")
                                     | GlobalSection + exclamationMark + Symbol("TotalPages")
                                     | GlobalSection + exclamationMark + Symbol("ExecutionTime")
                                     | GlobalSection + exclamationMark + Symbol("ReportFolder")
                                     | GlobalSection + exclamationMark + Symbol("ReportName");


            parameterSectionStmt.Rule = ParameterSection + exclamationMark + identifier;

            fieldsSectionStmt.Rule = FieldsSection + exclamationMark + identifier;
            #endregion

            Expr.Rule = Symbol("null")
                        | boolean
                        | nil
                        | stringLiteral
                        | numberLiteral
                        | QualifiedName
                        | FunctionExpression
                        | LCb + Expr + RCb
                        | LFb + QualifiedName + RFb
                        | Conditional
                        | BinExpr
                        //| Expr + BinOp + Expr
                        //| LUnOp + Expr

                        | parameterSectionStmt
                        | globalSectionStmt
                        | userSectionStmt
                        | fieldsSectionStmt;



            ExprList.Rule = MakePlusRule(ExprList, comma, Expr);

            BinOp.Rule = Symbol("+") | "-" | "*" | "%" | "^" | "&" | "|" | "/"
                         | "&&" | "||" | "==" | "!=" | greater | less
                         | ">=" | "<=" | "is" | "<>"
                         | "=" //| "+=" | "-="
                         | "." | and | or;

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

            FunctionExpression.Rule = QualifiedName + LCb + ExprList.Q() + RCb;

            QualifiedName.Rule = identifier
                                 | QualifiedName + dot + identifier
                                 | parameterSectionStmt + "!" + identifier
                                 | "#" + identifier;

            Condition.Rule = LCb + Expr + RCb;

            Conditional.Rule = "if" + Condition + "then" + Expr |
                               "if" + Condition + "then" + Expr + "else" + Expr |
                               "if" + Condition + "then" + Expr + "otherwise" + Expr;



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

            ProgramLine.Rule = Expr + NewLine;

            Program.Rule = MakeStarRule(Program, ProgramLine);
            this.Root    = Program;                // Set grammar root

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

            #endregion

            RegisterPunctuation("(", ")", "[", "]", "{", "}", ",", ";");
            MarkTransient(Expr, BinOp);

            //automatically add NewLine before EOF so that our BNF rules work correctly when there's no final line break in source
            this.SetLanguageFlags(LanguageFlags.NewLineBeforeEOF
                                  | LanguageFlags.SupportsInterpreter
                                  | LanguageFlags.AutoDetectTransient
                                  | LanguageFlags.CreateAst);
        }
Esempio n. 30
0
        public CeciliaGrammar()
        {
            #region Lexical rules
            // keywords
            var BoolKeyword      = new KeyTerm("bool", "bool");
            var CharKeyword      = new KeyTerm("char", "char");
            var StringKeyword    = new KeyTerm("string", "string");
            var ObjectKeyword    = new KeyTerm("object", "object");
            var ByteKeyword      = new KeyTerm("byte", "byte");
            var ShortKeyword     = new KeyTerm("short", "short");
            var IntKeyword       = new KeyTerm("int", "int");
            var LongKeyword      = new KeyTerm("long", "long");
            var UbyteKeyword     = new KeyTerm("ubyte", "ubyte");
            var UShortKeyword    = new KeyTerm("ushort", "short");
            var UIntKeyword      = new KeyTerm("uint", "int");
            var ULongKeyword     = new KeyTerm("ulong", "long");
            var HalfKeyword      = new KeyTerm("half", "half");
            var FloatKeyword     = new KeyTerm("float", "float");
            var DoubleKeyword    = new KeyTerm("double", "double");
            var DecimalKeyword   = new KeyTerm("decimal", "decimal");
            var NamespaceKeyword = new KeyTerm("namespace", "namespace");
            var PublicKeyword    = new KeyTerm("public", "public");
            var PrivateKeyword   = new KeyTerm("private", "private");
            var InternalKeyword  = new KeyTerm("internal", "internal");
            var UsingKeyword     = new KeyTerm("using", "using");
            var VarKeyword       = new KeyTerm("var", "var");
            var ConstKeyword     = new KeyTerm("const", "const");
            var SwitchKeyword    = new KeyTerm("switch", "switch");
            var LoopKeyword      = new KeyTerm("loop", "loop");
            var MacroKeyword     = new KeyTerm("macro", "macro");
            var TrueKeyword      = new KeyTerm("true", "true");
            var FalseKeyword     = new KeyTerm("false", "false");
            var DefaultKeyword   = new KeyTerm("default", "default");
            var ReturnKeyword    = new KeyTerm("return", "return");

            //symbols
            var LParen      = ToTerm("(");
            var RParen      = ToTerm(")");
            var LBracket    = ToTerm("[");
            var RBracket    = ToTerm("]");
            var LBrace      = ToTerm("{");
            var RBrace      = ToTerm("}");
            var Exclamation = ToTerm("!");
            var Dollar      = ToTerm("$");
            var Percent     = ToTerm("%");
            var Caret       = ToTerm("^");
            var Ampersand   = ToTerm("&");
            var Asterisk    = ToTerm("*");
            var Minus       = ToTerm("-");
            var Plus        = ToTerm("+");
            var Equals      = ToTerm("=");
            var Bar         = ToTerm("|");
            var Backslash   = ToTerm("\\");
            var Colon       = ToTerm(":");
            var SemiColon   = ToTerm(";");
            var DoubleQuote = ToTerm("\"");
            var SingleQuote = ToTerm("\'");
            var LessThan    = ToTerm("<");
            var GreaterThan = ToTerm(">");
            var Comma       = ToTerm(",");
            var Dot         = ToTerm(".");
            var Question    = ToTerm("?");
            var Hash        = ToTerm("#");
            var Slash       = ToTerm("/");

            var BarBar                 = ToTerm("||");
            var AmpAmp                 = ToTerm("&&");
            var MinusMinus             = ToTerm("--");
            var PlusPlus               = ToTerm("++");
            var QuestionQuestion       = ToTerm("??");
            var EqualsEquals           = ToTerm("==");
            var ExclamationEquals      = ToTerm("!=");
            var Arrow                  = ToTerm("=>");
            var LessThanEqual          = ToTerm("<=");
            var GreaterThanEqual       = ToTerm(">=");
            var LessThanLessThan       = ToTerm("<<");
            var GreaterThanGreaterThan = ToTerm(">>");
            var PlusEqual              = ToTerm("+=");
            var MinusEqual             = ToTerm("-=");
            var AsteriskEqual          = ToTerm("*=");
            var SlashEqual             = ToTerm("/=");
            var BarEqual               = ToTerm("|=");
            var CaretEqual             = ToTerm("^=");

            var LessThanLessThanEqual       = ToTerm("<<=");
            var GreaterThanGreaterThanEqual = ToTerm(">>=");

            var SemicolonOpt = new NonTerminal("semicolonOpt");
            SemicolonOpt.Rule = SemiColon.Q();

            var Identifier    = TerminalFactory.CreateCSharpIdentifier("identifier");
            var NumberLiteral = TerminalFactory.CreateCSharpNumber("NumberLiteral");
            var StringLiteral = TerminalFactory.CreateCSharpString("string_literal");

            var SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n");
            NonGrammarTerminals.Add(SingleLineComment);
            #endregion

            #region non terminals
            // program and namespace
            var Program                     = new NonTerminal("program");
            var UsingDirectives             = new NonTerminal("using_directives");
            var UsingDirective              = new NonTerminal("using_directive");
            var QualifiedIdentifier         = new NonTerminal("qualified_identifier");
            var NamespaceMemberDeclarations = new NonTerminal("namespace_member_declarations");
            var NamespaceMemberDeclaration  = new NonTerminal("namespace_member_declaration");
            var NamespaceDeclaration        = new NonTerminal("namespace_declaration");
            var NamespaceDeclarations       = new NonTerminal("namespace_declarations");

            // member declaration
            var TypeDeclaration     = new NonTerminal("type_declaration");
            var AllMemberModifiers  = new NonTerminal("all_member_modifiers");
            var AllMemberModifier   = new NonTerminal("all_member_modifier");
            var MemberDeclaration   = new NonTerminal("member_declaration");
            var ConstantDeclaration = new NonTerminal("constant_declaration");
            var VariableDeclaration = new NonTerminal("variable_declaration");
            var MacroDeclaration    = new NonTerminal("macro_declaration");
            var VariableDeclarators = new NonTerminal("variable_declarators");
            var VariableDeclarator  = new NonTerminal("variable_declarator");
            var TypeAnnotation      = new NonTerminal("type_annotation");
            var TypeAnnotationOpt   = new NonTerminal("type_annotationOpt");

            // types
            var Type               = new NonTerminal("type");
            var EmbeddedType       = new NonTerminal("embedded_type");
            var NumberType         = new NonTerminal("number_type");
            var IntegralNumberType = new NonTerminal("integral_number_type");
            var FloatingNumberType = new NonTerminal("floating_number_type");
            var OtherBaseType      = new NonTerminal("other_base_type");
            var SpecialSupportType = new NonTerminal("special_support_type");
            var UserDefinitionType = new NonTerminal("user_definition_type");

            // expression
            var Expression                = new NonTerminal("expression");
            var ConditionalExpression     = new NonTerminal("conditional_expression");
            var ConditionalExpressionBody = new NonTerminal("conditional_expression_body");
            var BinOpExpression           = new NonTerminal("bin_op_expression");
            var BinOp = new NonTerminal("bin_op");
            var AssignmentExpression = new NonTerminal("assignment_expression");
            var UnaryExpression      = new NonTerminal("unary_expression");
            var UnaryOperator        = new NonTerminal("unary_operator");
            var PrimaryExpression    = new NonTerminal("primary_expression");
            var AssignmentOperator   = new NonTerminal("assignment_operator");

            // loop expression
            var LoopExpression = new NonTerminal("loop_expression");
            var LoopCondition  = new NonTerminal("loop_condition");

            // return expression
            var ReturnExpression = new NonTerminal("return_expression");

            // switch expression
            var SwitchExpression = new NonTerminal("switch_expression");
            var SwitchSection    = new NonTerminal("switch_section");
            var SwitchLabel      = new NonTerminal("switch_label");

            // function expression
            var FunctionExpression    = new NonTerminal("function_expression");
            var FunctionSignature     = new NonTerminal("function_signature");
            var FunctionParameterList = new NonTerminal("function_parameter_list");
            var FunctionParameter     = new NonTerminal("function_parameter");
            var FunctionBody          = new NonTerminal("function_body");
            var Block = new NonTerminal("block");

            var ExpressonList     = new NonTerminal("expression_list");
            var ExpressionListOpt = new NonTerminal("expression_listOpt");

            // member access
            var IndexBracket    = new NonTerminal("index_bracket");
            var IndexBracketOpt = new NonTerminal("index_bracketOpt");
            IndexBracketOpt.Rule = MakeStarRule(IndexBracketOpt, IndexBracket);
            var MemberAccess            = new NonTerminal("member_access");
            var MemberAccessSegmentsOpt = new NonTerminal("member_access_segmentsOpt");
            var MemberAccessSegment     = new NonTerminal("member_access_segment");

            // literal
            var Literal        = new NonTerminal("literal");
            var BooleanLiteral = new NonTerminal("boolean_literal");

            #endregion

            #region operators punctuation delimiter
            RegisterOperators(1, BarBar);
            RegisterOperators(2, AmpAmp);
            RegisterOperators(3, Bar);
            RegisterOperators(4, Caret);
            RegisterOperators(5, Ampersand);
            RegisterOperators(6, EqualsEquals, ExclamationEquals);
            RegisterOperators(7, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual);
            RegisterOperators(8, GreaterThanGreaterThan, LessThanLessThan);
            RegisterOperators(9, Plus, Minus);
            RegisterOperators(10, Asterisk, Slash, Percent);
            RegisterOperators(-1, QuestionQuestion);
            RegisterOperators(-2, Question);
            RegisterOperators(-3, Equals, PlusEqual, MinusEqual, AsteriskEqual, SlashEqual, BarEqual, CaretEqual, GreaterThanGreaterThanEqual, LessThanLessThanEqual);

            MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":");
            MarkTransient(NamespaceMemberDeclaration, MemberDeclaration, Literal, BinOp, PrimaryExpression);

            AddTermsReportGroup("assignment",
                                Equals,
                                PlusEqual, MinusEqual,
                                AsteriskEqual, SlashEqual,
                                SlashEqual, BarEqual, CaretEqual,
                                GreaterThanGreaterThanEqual, LessThanLessThanEqual);
            AddTermsReportGroup("unary operator", Plus, Minus, Exclamation);
            AddToNoReportGroup(Comma, SemiColon);
            AddToNoReportGroup(VarKeyword, ConstKeyword, PlusPlus, MinusMinus, LBrace, RBrace);
            #endregion

            #region Syntax rules
            // program and namespace
            Program.Rule =
                UsingDirectives
                + NamespaceDeclarations;
            UsingDirectives.Rule     = MakeStarRule(UsingDirectives, null, UsingDirective);
            UsingDirective.Rule      = UsingKeyword + QualifiedIdentifier + SemicolonOpt;
            QualifiedIdentifier.Rule =
                MakeStarRule(QualifiedIdentifier, Dot, Identifier);
            NamespaceDeclaration.Rule =
                NamespaceKeyword + QualifiedIdentifier + Block + SemicolonOpt;
            NamespaceDeclarations.Rule =
                MakeStarRule(NamespaceDeclarations, null, NamespaceDeclaration);
            NamespaceMemberDeclarations.Rule =
                MakeStarRule(NamespaceMemberDeclarations, NamespaceMemberDeclaration);
            NamespaceMemberDeclaration.Rule =
                NamespaceDeclaration | TypeDeclaration;
            Block.Rule = LBrace + UsingDirectives + NamespaceMemberDeclarations + RBrace;

            // member declaration
            TypeDeclaration.Rule    = AllMemberModifiers + MemberDeclaration;
            AllMemberModifiers.Rule =
                MakeStarRule(AllMemberModifiers, AllMemberModifier);
            AllMemberModifier.Rule =
                PublicKeyword | PrivateKeyword | InternalKeyword;

            MemberDeclaration.Rule   = ConstantDeclaration | VariableDeclaration | MacroDeclaration;
            ConstantDeclaration.Rule = ConstKeyword + VariableDeclarators;
            VariableDeclaration.Rule = VarKeyword + VariableDeclarators;
            MacroDeclaration.Rule    = MacroKeyword + VariableDeclarators;
            VariableDeclarators.Rule = MakePlusRule(VariableDeclarators, Comma, VariableDeclarator);

            VariableDeclarator.Rule = Identifier + TypeAnnotationOpt + Equals + Expression + SemicolonOpt;
            TypeAnnotation.Rule     = Colon + Type;
            TypeAnnotationOpt.Rule  = TypeAnnotation.Q();

            // types
            Type.Rule         = EmbeddedType | UserDefinitionType;
            EmbeddedType.Rule = NumberType | OtherBaseType | SpecialSupportType;
            NumberType.Rule   =
                IntegralNumberType
                | FloatingNumberType
                | DecimalKeyword;
            IntegralNumberType.Rule =
                ByteKeyword
                | UbyteKeyword
                | ShortKeyword
                | UShortKeyword
                | IntKeyword
                | UIntKeyword
                | LongKeyword
                | ULongKeyword;
            FloatingNumberType.Rule =
                HalfKeyword | FloatKeyword | DoubleKeyword;
            OtherBaseType.Rule =
                BoolKeyword | CharKeyword;
            SpecialSupportType.Rule =
                StringKeyword | ObjectKeyword;
            UserDefinitionType.Rule = QualifiedIdentifier;

            #region expressions
            Expression.Rule =
                FunctionExpression
                | BinOpExpression
                | PrimaryExpression

                /*| AssignmentExpression
                 | SwitchExpression
                 | LoopExpression
                 | ReturnExpression*/
                | ConditionalExpression;

            ConditionalExpression.Rule =
                Expression + ConditionalExpressionBody;
            ConditionalExpressionBody.Rule =
                PreferShiftHere() + Question + Expression + Colon + Expression;

            // bin op expression
            BinOpExpression.Rule =
                Expression + BinOp + Expression;
            BinOp.Rule =
                BarBar
                | AmpAmp
                | Bar
                | Caret
                | Ampersand
                | EqualsEquals
                | ExclamationEquals
                | GreaterThan
                | LessThan
                | GreaterThanEqual
                | LessThanEqual
                | GreaterThanGreaterThan
                | Plus
                | Minus
                | Asterisk
                | Slash
                | Percent
                | Equals
                | PlusEqual
                | MinusEqual
                | AsteriskEqual
                | SlashEqual
                | BarEqual
                | CaretEqual
                | GreaterThanGreaterThanEqual
                | LessThanLessThanEqual
                | QuestionQuestion;

            // primary expresson
            PrimaryExpression.Rule =
                Literal
                | UnaryExpression
                | MemberAccess;

            // literal
            Literal.Rule = NumberLiteral | StringLiteral | TrueKeyword | FalseKeyword;

            UnaryExpression.Rule =
                UnaryOperator + PrimaryExpression;
            UnaryOperator.Rule =
                Plus
                | Minus
                | Exclamation
                | Asterisk;

            MemberAccess.Rule            = Identifier + MemberAccessSegmentsOpt;
            MemberAccessSegmentsOpt.Rule = MakeStarRule(MemberAccessSegmentsOpt, MemberAccessSegment);
            MemberAccessSegment.Rule     =
                Dot + Identifier;

            // function expression
            FunctionExpression.Rule =
                FunctionSignature + Arrow + FunctionBody;
            FunctionSignature.Rule =
                LParen + FunctionParameterList + RParen
                | Identifier;
            FunctionParameterList.Rule =
                MakeStarRule(FunctionParameterList, Comma, FunctionParameter);
            FunctionParameter.Rule =
                Identifier + TypeAnnotationOpt;
            FunctionBody.Rule =
                Expression | Block;
            ExpressionListOpt.Rule = ExpressonList.Q();
            ExpressonList.Rule     = MakePlusRule(ExpressonList, Expression);
            #endregion

            #endregion

            Root = Program;
        }