public static NumberLiteral CreateZodiacNumber(string name) { NumberLiteral term = new NumberLiteral(name); term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.UInt32 }; //term.DefaultFloatType = TypeCode.Double; //default return term; }
public E2Grammar() { LineTerminators = "\r\n"; var program = new NonTerminal("Program"); var directiveList = new NonTerminal("DirectiveList"); var directive = new NonTerminal("Directive"); var directiveName = new IdentifierTerminal("DirectiveName"); var directiveBody = new NonTerminal("DirectiveBody"); var statementList = new NonTerminal("StatementList"); var statement = new NonTerminal("Statement"); var assignment = new NonTerminal("Assignment"); var expression = new NonTerminal("Expression"); var parenExpression = new NonTerminal("ParenExpression"); var methodCall = new NonTerminal("MethodCall"); var argumentList = new NonTerminal("ArgumentList"); var argumentTail = new NonTerminal("ArgumentTail"); var @operator = new NonTerminal("Operator"); var operation = new NonTerminal("Operation"); var identifier = new IdentifierTerminal("Identifier"); var @string = new StringLiteral("String", "\""); var number = new NumberLiteral("Number"); var ifStatement = new NonTerminal("IfStatement"); var whileStatement = new NonTerminal("WhileStatement"); var comment = new CommentTerminal("comment", "#", new[] {"\n"}); var dcom = new CommentTerminal("commentCheat", "@", new[] {"\n"}); Root = program; NonGrammarTerminals.Add(comment); NonGrammarTerminals.Add(dcom); RegisterBracePair("{", "}"); program.Rule = /* directiveList + */statementList; //directiveList.Rule = MakePlusRule(directiveList, null, directive); //directiveBody.Rule = new CommentTerminal() //directive.Rule = ToTerm("@") + directiveName + directiveBody; statementList.Rule = MakePlusRule(statementList, null, statement); statement.Rule = methodCall | assignment; expression.Rule = operation | @string | number | methodCall | identifier; parenExpression.Rule = ToTerm("(") + expression + ")"; methodCall.Rule = expression + ":" + identifier + "(" + argumentList + ")"; argumentList.Rule = MakeStarRule(argumentList, ToTerm(","), expression); operation.Rule = expression + @operator + expression; @operator.Rule = ToTerm("+") | "-" | "*" | "/" | "&" | "|"; assignment.Rule = identifier + "=" + expression; ifStatement.Rule = ToTerm("if") + parenExpression + "{" + statementList + "}"; whileStatement.Rule = ToTerm("while") + parenExpression + "{" + statementList + "}"; }
public ExpressionGrammar() { var Number = new NumberLiteral("Number"); var Var = new IdentifierTerminal("Var"); var conditional_expression = new NonTerminal("conditional_expression"); //conditional_expression.Rule = expression + PreferShiftHere() + qmark + expression + colon + expression; //NonTerminal DataType = new NonTerminal("DataType"); NonTerminal DecSt = new NonTerminal("DecSt"); DecSt.Rule = "int" + Var + "=" + Number + ";" | "int" + Var + ";"; NonTerminal PrintSt = new NonTerminal("PrintSt"); PrintSt.Rule = "cout <<" + Var; //NonTerminal IF = new NonTerminal("IF"); //IF.Rule = "if( + ; NonTerminal stmt = new NonTerminal("stmt"); stmt.Rule = PrintSt | DecSt; NonTerminal stmt1 = new NonTerminal("stmt"); stmt1.Rule = "begin{" + stmt + "}end;"; this.Root = DecSt; }
//#AS:2012/12/08: grammar is case-insensitive public CameraControlGrammar() : base(caseSensitive: false) { var program = new NonTerminal("program"); var cameraSize = new NonTerminal("cameraSize"); var cameraPosition = new NonTerminal("cameraPosition"); var commandList = new NonTerminal("commandList"); var command = new NonTerminal("command"); var direction = new NonTerminal("direction"); var number = new NumberLiteral("number"); this.Root = program; //Grammar production rules in bnf form // <Program> ::= <CameraSize> <CameraPosition> <CommandList> program.Rule = cameraSize + cameraPosition + commandList; // <CameraSize> ::= "set" "camera" "size" ":" <number> "by" <number> "pixels" "." cameraSize.Rule = ToTerm("set") + "camera" + "size" + ":" + number + "by" + number + "pixels" + "."; // <CameraPosition> ::= "set" "camera" "position" ":" <number> "," <number> "." cameraPosition.Rule = ToTerm("set") + "camera" + "position" + ":" + number + "," + number + "."; // <CommandList> ::= <Command>+ commandList.Rule = MakePlusRule(commandList, null, command); // <Command> ::= "move" <number> "pixels" <Direction> "." command.Rule = ToTerm("move") + number + "pixels" + direction + "."; // <Direction> ::= "up" | "down" | "left" | "right" direction.Rule = ToTerm("up") | "down" | "left" | "right"; //#AS:2012/12/08: these symbols are defined as puntuation, so they will not be included in the ast this.MarkPunctuation("set", ("camera"), "size", ":", "by", "pixels", ".", "position", ",", "move"); }
public JsonGrammar() { //Terminals var jstring = new StringLiteral("string", "\""); var jnumber = new NumberLiteral("number"); var comma = ToTerm(","); //Nonterminals var jobject = new NonTerminal("Object"); var jobjectBr = new NonTerminal("ObjectBr"); var jarray = new NonTerminal("Array"); var jarrayBr = new NonTerminal("ArrayBr"); var jvalue = new NonTerminal("Value"); var jprop = new NonTerminal("Property"); //Rules jvalue.Rule = jstring | jnumber | jobjectBr | jarrayBr | "true" | "false" | "null"; jobjectBr.Rule = "{" + jobject + "}"; jobject.Rule = MakeStarRule(jobject, comma, jprop); jprop.Rule = jstring + ":" + jvalue; jarrayBr.Rule = "[" + jarray + "]"; jarray.Rule = MakeStarRule(jarray, comma, jvalue); //Set grammar root this.Root = jvalue; MarkPunctuation("{", "}", "[", "]", ":", ","); this.MarkTransient(jvalue, jarrayBr, jobjectBr); }//constructor
public KISGrammer() { var number = new NumberLiteral("number"); var text = new StringLiteral("string", "\""); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; var identifier = new IdentifierTerminal("identifier"); var comment = new CommentTerminal("comment", "#", "\n", "\r"); base.NonGrammarTerminals.Add(comment); var Code = new NonTerminal("code"); var Statments = new NonTerminal("statments"); var Value = new NonTerminal("value"); var ValueString = TerminalFactory.CreateCSharpString("valuestring"); var SetStmt = new NonTerminal("setstmt"); var CallStmt = new NonTerminal("callstmt"); var FnStmt = new NonTerminal("fnstmt"); var CallPath = new NonTerminal("callpath"); var CallPerams = new NonTerminal("callperams"); var fullstop = new NonTerminal("fullstop"); var comma = new NonTerminal("comma"); var openb = new NonTerminal("openb"); var closeb = new NonTerminal("closeb"); openb.Rule = "{"; closeb.Rule = "}"; fullstop.Rule = "."; comma.Rule = ","; CallPath.Rule = MakePlusRule(CallPath, fullstop, identifier); CallPerams.Rule = MakePlusRule(CallPerams, comma, Value); var Semicolon = ToTerm(";"); //StateMents: SetStmt.Rule = identifier + "=" + Value + Semicolon; CallStmt.Rule = (CallPath | identifier) + "(" + (CallPerams | Empty) + ")" + Semicolon; FnStmt.Rule = "function" + identifier + "(" + (CallPerams | Empty) + ")"; Statments.Rule = SetStmt | CallStmt | FnStmt | openb | closeb | Empty; var Exspr = new NonTerminal("exspr"); var Operator = new NonTerminal("operator"); var ExsprStmt = new NonTerminal("exsprstmt"); Operator.Rule = ToTerm("/") | "*" | "-" | "+"; ExsprStmt.Rule = Value + Operator + Value; Exspr.Rule = MakePlusRule(Exspr, Operator, ExsprStmt); Value.Rule = number | ValueString | identifier | "true" | "false" | Exspr /* | text */; Code.Rule = MakePlusRule(Code, NewLine, Statments); LanguageFlags = LanguageFlags.NewLineBeforeEOF; //code := Statment {statment} this.Root = Code; }
public void TestNumber_SignedDoesNotMatchSinglePlus() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); parser = TestHelper.CreateParser(number); token = parser.ParseInput("+"); Assert.IsTrue(token.IsError(), "Parsed single '+' as a number value."); }
public void TestNumber_SignedMatchesNegativeCorrectly() { Parser parser; Token token; var number = new NumberLiteral("number", NumberOptions.AllowSign); parser = TestHelper.CreateParser(number); token = parser.ParseInput("-500"); Assert.AreEqual(-500, token.Value, "Negative number was parsed incorrectly; expected: {0}, scanned: {1}", "-500", token.Value); }
public PowerPCGrammar() : base(false) { var number = new NumberLiteral("number", NumberOptions.Default); var REGCHAR = ToTerm("r"); REGCHAR.AllowAlphaAfterKeyword = true; var register = new NonTerminal("register"); register.Rule = REGCHAR + number; var program = new NonTerminal("program"); var statementList = new NonTerminal("statementList"); var statement = new NonTerminal("statement"); var comma = ","; var li = new NTerminal("li"); var add = new NTerminal("add"); var addi = new NTerminal("addi"); var addc = new NTerminal("addc"); var and = new NTerminal("and"); var andc = new NTerminal("andc"); var andi = new NTerminal("andi"); var andis = new NTerminal("andis"); var cmp = new NTerminal("cmp"); var sub = new NTerminal("sub"); var subi = new NTerminal("subi"); var print = new NTerminal("print"); li.Rule = li.term + register + comma + number; add.Rule = add.term + register + comma + register + comma + register; addi.Rule = addi.term + register + comma + register + comma + number; addc.Rule = addc.term + register + comma + register + comma + register; and.Rule = and.term + register + comma + register + comma + register; andc.Rule = andc.term + register + comma + register + comma + register; andi.Rule = andi.term + register + comma + register + comma + number; andis.Rule = andis.term + register + comma + register + comma + number; cmp.Rule = cmp.term + register + comma + register; sub.Rule = sub.term + register + comma + register + comma + register; subi.Rule = subi.term + register + comma + register + comma + number; print.Rule = print.term | print.term + register | print.term + register + "..." + register; program.Rule = statementList; statementList.Rule = MakeStarRule(statementList, NewLine, statement); this.MarkPunctuation(comma, ";", "..."); foreach (NTerminal n in NTerminal.termList) { if (statement.Rule == null) statement.Rule = n.keyTerm; else statement.Rule = statement.Rule | n.keyTerm; MarkPunctuation(n.term); } this.Root = program; }
private NumberLiteral CreateNumberLiteral(string name) { var term = new NumberLiteral(name); term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 }; term.DefaultFloatType = TypeCode.Double; term.AddPrefix("0x", NumberOptions.Hex); term.AddSuffix("l", TypeCode.Int64, TypeCode.UInt64); term.AddSuffix("f", TypeCode.Single); term.AddSuffix("d", TypeCode.Double); return term; }
//http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf section 9.4.4 public static NumberLiteral CreateCSharpNumber(string name) { NumberLiteral term = new NumberLiteral(name); term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.UInt32, TypeCode.Int64, TypeCode.UInt64 }; term.DefaultFloatType = TypeCode.Double; term.AddPrefix("0x", NumberOptions.Hex); term.AddSuffix("u", TypeCode.UInt32, TypeCode.UInt64); term.AddSuffix("l", TypeCode.Int64, TypeCode.UInt64); term.AddSuffix("ul", TypeCode.UInt64); term.AddSuffix("f", TypeCode.Single); term.AddSuffix("d", TypeCode.Double); term.AddSuffix("m", TypeCode.Decimal); return term; }
public static NumberLiteral CreateJavaNumber(string name) { var term = new NumberLiteral(name, NumberOptions.AllowStartEndDot) { DefaultIntTypes = new[] { TypeCode.Int32 }, DefaultFloatType = TypeCode.Double }; term.AddPrefix("0x", NumberOptions.Hex); term.AddSuffix("l", TypeCode.Int64); term.AddSuffix("f", TypeCode.Single); term.AddSuffix("d", TypeCode.Double); return term; }
public LinearProgrammingGrammar() { var comment = new CommentTerminal("comment", "#", "\n", "\r"); NonGrammarTerminals.Add(comment); var identifier = new IdentifierTerminal("appIdentifier"); var variable = new IdentifierTerminal("variable"); var number = new NumberLiteral("number", NumberOptions.AllowSign); var lpProgram = new NonTerminal("lpApp"); var lpAppName = new NonTerminal("lpAppName"); var lpModel = new NonTerminal("lpModel"); var lpGoal = new NonTerminal("lpGoal"); var lpPolynomial = new NonTerminal("lpPolynomial"); var lpConstraints = new NonTerminal("lpConstraints"); var lpConstraint = new NonTerminal("lpConstraints"); var lpOperator = new NonTerminal("lpOperator", "lp Operation symbol"); var lpBinOp = new NonTerminal("lpBinOp", "lp Binary Operation symbol"); var lpMonomial = new NonTerminal("Monomial"); var lpNumber = new NonTerminal("lpNumber"); lpProgram.Rule = lpAppName + "{" + lpModel + "}" + ";"; lpAppName.Rule = ToTerm("lpmodel") + identifier; lpModel.Rule = lpGoal + ToTerm("subject to") +":" + lpConstraints; lpGoal.Rule = ToTerm("max") + lpPolynomial | ToTerm("min") + lpPolynomial; lpConstraints.Rule = MakePlusRule(lpConstraints, null, lpConstraint); //ReduceHere(); lpConstraint.Rule = lpPolynomial + lpOperator + lpPolynomial + ";"; lpOperator.Rule = ToTerm("<") | "==" | ">" | "<=" | ">="; lpPolynomial.Rule = lpMonomial | lpMonomial + lpBinOp + lpPolynomial | lpNumber | lpNumber + lpBinOp + lpPolynomial; lpMonomial.Rule = variable | lpNumber + ToTerm("*") + variable; lpBinOp.Rule = ToTerm("+") | "-"; lpNumber.Rule = number | lpBinOp + number; MarkReservedWords("max", "min", "lpmodel", "subject to"); // ReduceIf(""); Root = lpProgram; }
public void GeneralTest() { NumberLiteral number = new NumberLiteral("Number"); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; SetTerminal(number); TryMatch("123"); CheckType(typeof(int)); Assert.IsTrue((int)_token.Value == 123, "Failed to read int value"); TryMatch("123.4"); Assert.IsTrue(Math.Abs(Convert.ToDouble(_token.Value) - 123.4) < 0.000001, "Failed to read float value"); //100 digits string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; TryMatch(sbig); Assert.IsTrue(_token.Value.ToString() == sbig, "Failed to read big integer value"); }//method
public Portugol() : base(false) { LanguageFlags = LanguageFlags.CreateAst; var numero = new NumberLiteral("Numero", NumberOptions.AllowSign); var identificador = new IdentifierTerminal("Identificador"); var expressao = new NonTerminal("Expressao", typeof (AstNode)); var termo = new NonTerminal("Termo", typeof (AstNode)); var chamadaFuncao = new NonTerminal("Chamada funcao", typeof (ChamadaDeFuncao)); var operacaoBinaria = new NonTerminal("Operacao binaria", typeof (OperacaoBinaria)); var operacaoComParentese = new NonTerminal("Operacao com parentese", typeof (AstNode)); var se = new NonTerminal("Se", typeof (CondicaoSe)); var operador = new NonTerminal("Operador", typeof(AstNode)); var operadorLogico = new NonTerminal("Operador logico", typeof (AstNode)); var argumentos = new NonTerminal("Argumentos", typeof (AstNode)); var sePart = new NonTerminal("Se parte", typeof (AstNode)); var entaoPart = new NonTerminal("Entao parte", typeof (AstNode)); var senaoPart = new NonTerminal("Senao parte", typeof (AstNode)); NonGrammarTerminals.Add(new CommentTerminal("comment1", "/*", "*/")); expressao.Rule = operacaoBinaria | operacaoComParentese | se | chamadaFuncao | termo; termo.Rule = numero; operacaoComParentese.Rule = ToTerm("(") + expressao + ")"; operacaoBinaria.Rule = expressao + operador + expressao; operador.Rule = ToTerm("+") | "-" | "*" | "/" | "^" | "%" | "=" | "<" | ">" | "<=" | ">=" | "<>" | "E" | "OU"; sePart.Rule = ToTerm("Se"); entaoPart.Rule = ToTerm("Entao"); senaoPart.Rule = ToTerm("Senao"); se.Rule = sePart + expressao + entaoPart + expressao + senaoPart + expressao; argumentos.Rule = MakePlusRule(argumentos, ToTerm(","), expressao); chamadaFuncao.Rule = identificador | identificador + "(" + argumentos + ")"; RegisterOperators(1, "E", "OU"); RegisterOperators(5, "=", "<", ">", "<=", ">=", "<>"); RegisterOperators(10, "+", "-"); RegisterOperators(20, "*", "/", "%", "^"); MarkPunctuation("(", ")"); RegisterBracePair("(", ")"); MarkTransient(expressao, operador, termo, operadorLogico, operacaoComParentese); Root = expressao; LanguageFlags = LanguageFlags.CreateAst; }
public void AllowNullEqualityComparison(string op) { var nullVal = new NullLiteral (); var numberVal = new NumberLiteral (42); var left = new BinaryOperation (op, nullVal, numberVal); var right = new BinaryOperation (op, numberVal, nullVal); var leftType = left.Walk (new TypeChecker ()); var rightType = right.Walk (new TypeChecker ()); Assert.AreEqual (SpecType.Boolean, leftType.Type); Assert.AreEqual (SpecType.Boolean, rightType.Type); }
public NumericalSchemeGrammar() { this.GrammarComments = ""; //Symbols var whitespace = new NonTerminal("WhiteSpace", Empty | " " | "\t"); // Comments var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var multiLineComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(multiLineComment); //Terminals var semicolon = ToTerm(";", "Semicolon"); var ofString = new StringLiteral("String", "\""); var ofNumber = new NumberLiteral("Number", NumberOptions.AllowSign); var ofIdentifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); var ofArrayTerm = new IdentifierTerminal("SchemeTerm", "(),|*.+-/%^~!&"); //Non-terminals var ofValue = new NonTerminal("Value"); var ofDictionary = new NonTerminal("Dictionary"); var ofDictionaryContent = new NonTerminal("DictionaryContent"); var ofDictionaryContentWrapper = new NonTerminal("DictionaryContentWrapper"); var ofDictEntry = new NonTerminal("DictEntry"); var ofArrayEntry = new NonTerminal("ArrayEntry"); var ofArray = new NonTerminal("Array"); var ofArrayWrapper = new NonTerminal("ArrayWrapper"); //BNF ofValue.Rule = ofIdentifier | ofArrayTerm | ofString | ofNumber; ofDictEntry.Rule = ofArrayWrapper | ofDictionary; ofDictionaryContent.Rule = MakeStarRule(ofDictionaryContent, whitespace, ofDictEntry); ofDictionaryContentWrapper.Rule = "{" + ofDictionaryContent + "}"; ofDictionary.Rule = ofIdentifier + whitespace + ofDictionaryContentWrapper; ofArrayEntry.Rule = ofValue; ofArray.Rule = MakeStarRule(ofArray, whitespace, ofArrayEntry); ofArrayWrapper.Rule = ofArray + semicolon; //Set grammar root this.Root = ofDictionaryContent; MarkPunctuation("{", "}"); MarkTransient(ofValue, ofDictionaryContentWrapper); }
public void TestNumber_General() { Parser parser; Token token; NumberLiteral number = new NumberLiteral("Number"); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; parser = TestHelper.CreateParser(number); token = parser.ParseInput("123"); CheckType(token, typeof(int)); Assert.IsTrue((int)token.Value == 123, "Failed to read int value"); token = parser.ParseInput("123.4"); Assert.IsTrue(Math.Abs(Convert.ToDouble(token.Value) - 123.4) < 0.000001, "Failed to read float value"); //100 digits string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; token = parser.ParseInput(sbig); Assert.IsTrue(token.Value.ToString() == sbig, "Failed to read big integer value"); }//method
/// <summary> /// 使うな /// </summary> public Kbtter3QueryGrammar() : base() { //コメント var comment = new CommentTerminal("Comment", "/*", "*/"); NonGrammarTerminals.Add(comment); //リテラル var number = new NumberLiteral("Number", NumberOptions.AllowSign | NumberOptions.AllowStartEndDot); var str = new StringLiteral("String", "\""); var regex = new RegexLiteral("Regex", '/', '\\'); var ident = new IdentifierTerminal("Identifer"); //非終端 var Value = new NonTerminal("Value"); var Term = new NonTerminal("Term"); var Expression = new NonTerminal("Expression"); var BinExpression = new NonTerminal("BinExpression"); var ParExpression = new NonTerminal("ParExpression"); var PostfixExpression = new NonTerminal("PostfixExpression"); var Operator = new NonTerminal("Operator"); //非終端定義 Value.Rule = number | str | ident | regex | "null" | "true" | "false"; Term.Rule = Value | ParExpression; Operator.Rule = ToTerm("==") | "!=" | ">" | "<" | ">=" | "<=" | "match" | "&&" | "||" | "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | "."; BinExpression.Rule = Expression + Operator + Expression; PostfixExpression.Rule = (ToTerm("+") + Term) | ("-" + Term) | ("!" + Term); Expression.Rule = BinExpression | Term | PostfixExpression; ParExpression.Rule = ToTerm("(") + Expression + ")"; RegisterOperators(10, "."); RegisterOperators(9, "*", "/", "%"); RegisterOperators(8, "+", "-"); RegisterOperators(7, ">", "<", ">=", "<=", "match"); RegisterOperators(6, "==", "!="); RegisterOperators(5, "&"); RegisterOperators(4, "^"); RegisterOperators(3, "|"); RegisterOperators(2, "&&"); RegisterOperators(1, "||"); Root = Expression; MarkPunctuation("(", ")"); MarkTransient(Expression, ParExpression, Value, Operator, Term); }
public ExpressionGrammar() { this.GrammarComments = @"Arithmetical expressions for dynamic geometry."; // 1. Terminals var number = new NumberLiteral("number"); var identifier = new IdentifierTerminal("identifier"); // 2. Non-terminals var Expr = new NonTerminal("Expr"); var Term = new NonTerminal("Term"); var BinExpr = new NonTerminal("BinExpr"); var ParExpr = new NonTerminal("ParExpr"); var UnExpr = new NonTerminal("UnExpr"); var UnOp = new NonTerminal("UnOp"); var BinOp = new NonTerminal("BinOp", "operator"); var PropertyAccess = new NonTerminal("PropertyAccess"); var FunctionCall = new NonTerminal("FunctionCall"); var CommaSeparatedIdentifierList = new NonTerminal("PointArgumentList"); var ArgumentList = new NonTerminal("ArgumentList"); // 3. BNF rules Expr.Rule = Term | UnExpr | BinExpr; Term.Rule = number | identifier | ParExpr | FunctionCall | PropertyAccess; UnExpr.Rule = UnOp + Term; UnOp.Rule = ToTerm("-"); BinExpr.Rule = Expr + BinOp + Expr; BinOp.Rule = ToTerm("+") | "-" | "*" | "/" | "^"; PropertyAccess.Rule = identifier + "." + identifier; FunctionCall.Rule = identifier + "(" + ArgumentList + ")"; ArgumentList.Rule = Expr | CommaSeparatedIdentifierList; ParExpr.Rule = "(" + Expr + ")"; CommaSeparatedIdentifierList.Rule = MakePlusRule(CommaSeparatedIdentifierList, ToTerm(","), identifier); this.Root = Expr; // 4. Operators precedence RegisterOperators(1, "+", "-"); RegisterOperators(2, "*", "/"); RegisterOperators(3, Associativity.Right, "^"); MarkPunctuation("(", ")", ".", ","); MarkTransient(Term, Expr, BinOp, UnOp, ParExpr, ArgumentList, CommaSeparatedIdentifierList); }
public FreightGrammar() : base(caseSensitive: false) { // define all the non-terminals var program = new NonTerminal("program"); var statementList = new NonTerminal("statementList"); var statement = new NonTerminal("statement"); var ifStatement = new NonTerminal("ifStatement",typeof(FreightLanguage.code_generation.IfStatementNode)); var freightDeclaration = new NonTerminal("freightDeclaration"); var setVariable = new NonTerminal("setVariable"); var orderLoop = new NonTerminal("orderLoop"); var expression = new NonTerminal("expression",typeof(FreightLanguage.code_generation.ExpressionNode)); var variable = new IdentifierTerminal("variable"); //variable.AddKeywords("set", "to", "if", "freight", "cost", "is", "loop", "through", "order"); var binaryOperator = new NonTerminal("binaryOperator"); // define the grammar //<BinaryOperator> ::= "+" | "-" | "*" | "/" | "<" | ">" | "<=" | ">=" | "is" binaryOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "<" | ">" | "<=" | ">=" | "is"; //<Program> ::= <StatementList> <FreightDeclaration> program.Rule = statementList + freightDeclaration; //<StatementList> ::= <Statement>* statementList.Rule = MakeStarRule(statementList, null, statement); //<Statement> ::= <SetVariable> ";" | <IfStatement> | <OrderLoop> | <Expression> ";" statement.Rule = setVariable + ";" | ifStatement | orderLoop | expression + ";"; //<SetVariable> ::= "set" <variable> "to" <Expression> setVariable.Rule = ToTerm("set") + variable + "to" + expression; //<IfStatement> ::= "if" <Expression> "[" <StatementList> "]" ifStatement.Rule = ToTerm("if") + expression + "[" + statementList + "]"; //<OrderLoop> ::= "loop" "through" "order" "[" <StatementList> "]" orderLoop.Rule = ToTerm("loop") + "through" + "order" + "[" + statementList + "]"; //<FreightDeclaration> ::= "freight" "cost" "is" <Expression> ";" freightDeclaration.Rule = ToTerm("freight") + "cost" + "is" + expression + ";"; //<Expression> ::= <number> | <variable> | <string> |<Expression> <BinaryOperator> <Expression> | "(" <Expression> ")" var number = new NumberLiteral("number"); //TEST number.DefaultIntTypes = number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; var stringLiteral = new StringLiteral("stringType", "\""); expression.Rule = number | variable | stringLiteral | expression + binaryOperator + expression | "(" + expression + ")"; this.Root = program; MarkPunctuation("[", "]", ";"); }
public LiteralRules(PieGrammar grammar) { this.grammar = grammar; NumberLiteral = new NumberLiteral("number_literal", NumberOptions.AllowStartEndDot) { // Define types to assign if the parser can't determine. DefaultIntTypes = new[] { TypeCode.Int32 }, DefaultFloatType = TypeCode.Double }; // The pre and post fixes for different number types and formats. NumberLiteral.AddPrefix("0x", NumberOptions.Hex); NumberLiteral.AddSuffix("b", TypeCode.Byte); NumberLiteral.AddSuffix("B", TypeCode.Byte); NumberLiteral.AddSuffix("s", TypeCode.Int16); NumberLiteral.AddSuffix("S", TypeCode.Int16); NumberLiteral.AddSuffix("u", TypeCode.UInt32); NumberLiteral.AddSuffix("U", TypeCode.UInt32); NumberLiteral.AddSuffix("us", TypeCode.UInt16); NumberLiteral.AddSuffix("US", TypeCode.UInt16); NumberLiteral.AddSuffix("l", TypeCode.Int64); NumberLiteral.AddSuffix("L", TypeCode.Int64); NumberLiteral.AddSuffix("ul", TypeCode.UInt64); NumberLiteral.AddSuffix("UL", TypeCode.UInt64); NumberLiteral.AddSuffix("F", TypeCode.Single); NumberLiteral.AddSuffix("f", TypeCode.Single); NumberLiteral.AddSuffix("d", TypeCode.Double); NumberLiteral.AddSuffix("D", TypeCode.Double); NumberLiteral.AddSuffix("m", TypeCode.Decimal); NumberLiteral.AddSuffix("M", TypeCode.Decimal); StringLiteral = new StringLiteral("string_literal", "\"", StringOptions.AllowsAllEscapes); CharLiteral = new StringLiteral("char_literal", "'", StringOptions.IsChar); BoolLiteral = new NonTerminal("bool_literal"); BoolLiteral.Rule = grammar.Keywords.True | grammar.Keywords.False; Null = grammar.ToTerm("null", "null_literal"); }
public Example() { //1. Terminals Terminal num = new NumberLiteral("number"); MarkReservedWords("not="); //2. Non-Terminals var Expr = new NonTerminal("expr"); var BinOp = new NonTerminal("binOp", "operator"); var unOp = new NonTerminal("unOp","operator"); var BinExpr = new NonTerminal("binExpr"); var unExpr = new NonTerminal("unExpr"); var exitLoop = new NonTerminal("exitLoop"); var program = new NonTerminal("program"); //3. BNF rules Expr.Rule = num | BinExpr | unExpr | "(" + Expr + ")"; BinOp.Rule = ToTerm("=") | "!=" | "not="; BinOp.Precedence = 20; unOp.Rule = ToTerm("not") | "!"; unOp.Precedence = 10; exitLoop.Rule = ToTerm("exit") + "when" + Expr; BinExpr.Rule = Expr + BinOp + Expr; unExpr.Rule = unOp + Expr; program.Rule = Expr + program | exitLoop + program | Empty; this.Root = program; //4. Set operator precendence and associativity RegisterOperators(20, Associativity.Left, "=", "not=", "!="); RegisterOperators(10, Associativity.Left, "not","!"); //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree MarkReservedWords("not"); MarkPunctuation("(", ")", ","); RegisterBracePair("(", ")"); MarkTransient(Expr, BinOp, unOp); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF | LanguageFlags.CreateAst; }
//http://www.microsoft.com/downloads/details.aspx?FamilyId=6D50D709-EAA4-44D7-8AF3-E14280403E6E&displaylang=en section 2 public static NumberLiteral CreateVbNumber(string name) { NumberLiteral term = new NumberLiteral(name); term.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 }; //term.DefaultFloatType = TypeCode.Double; it is default term.AddPrefix("&H", NumberOptions.Hex); term.AddPrefix("&O", NumberOptions.Octal); term.AddSuffix("S", TypeCode.Int16); term.AddSuffix("I", TypeCode.Int32); term.AddSuffix("%", TypeCode.Int32); term.AddSuffix("L", TypeCode.Int64); term.AddSuffix("&", TypeCode.Int64); term.AddSuffix("D", TypeCode.Decimal); term.AddSuffix("@", TypeCode.Decimal); term.AddSuffix("F", TypeCode.Single); term.AddSuffix("!", TypeCode.Single); term.AddSuffix("R", TypeCode.Double); term.AddSuffix("#", TypeCode.Double); term.AddSuffix("US", TypeCode.UInt16); term.AddSuffix("UI", TypeCode.UInt32); term.AddSuffix("UL", TypeCode.UInt64); return term; }
/// <summary> /// 新しいインスタンスを以下略 /// </summary> public Kb10uyConfigGrammar() : base() { var Number = new NumberLiteral("Number"); var String = new StringLiteral("String", "\"", StringOptions.AllowsAllEscapes); var CommentLine = new CommentTerminal("Comment", "#", "\n", "\r"); var CommentBlock = new CommentTerminal("Comment", "#<", ">"); //数値設定 Number.DefaultIntTypes = new[] { TypeCode.Int32 }; Number.DefaultFloatType = TypeCode.Double; String.EscapeChar = '\\'; NonGrammarTerminals.Add(CommentBlock); NonGrammarTerminals.Add(CommentLine); var Value = new NonTerminal("Value"); var Values = new NonTerminal("Value\'s\'"); var ValueSet = new NonTerminal("Array"); var Property = new NonTerminal("Property"); var Prefix = new NonTerminal("Prefix"); var Node = new NonTerminal("Node"); var Nodes = new NonTerminal("Nodes"); //var PropertySet = new NonTerminal("PropertySet"); var Group = new NonTerminal("Group"); var ConfigRoot = new NonTerminal("Root"); Value.Rule = Number | String | ValueSet; Values.Rule = MakeStarRule(Values, ToTerm(","), Value); ValueSet.Rule = ToTerm("[") + Values + "]"; Prefix.Rule = ToTerm("Number") | "String" | "Array" ; Property.Rule = Prefix + ":" + String + "=" + Value + ";"; Node.Rule = Property | Group; Nodes.Rule = MakeStarRule(Nodes, Node); Group.Rule = String + ":" + "{" +Nodes+ "}"; ConfigRoot.Rule = MakeStarRule(ConfigRoot, Group); Root = ConfigRoot; MarkPunctuation("[", "]", ",", "{", "}",":",";","="); }
public SimpleEvaluatorGrammar() { // Терминальные символы Number = new NumberLiteral("number", NumberOptions.IntOnly | NumberOptions.AllowSign); Number.DefaultIntTypes = new[] {TypeCode.Int32}; // Нетерминальные символы BinExpr = new NonTerminal("BinExpr"); UnaryExpr = new NonTerminal("UnExpr"); var expr = new NonTerminal("Expr"); var term = new NonTerminal("Term"); var parExpr = new NonTerminal("ParExpr"); var unOp = new NonTerminal("UnOp"); var binOp = new NonTerminal("BinOp"); // БНФ правила expr.Rule = term | UnaryExpr | BinExpr; term.Rule = Number | parExpr; parExpr.Rule = "(" + expr + ")"; UnaryExpr.Rule = unOp + term + ReduceHere(); unOp.Rule = ToTerm("+") | "-"; BinExpr.Rule = expr + binOp + expr; binOp.Rule = ToTerm("+") | "-" | "*" | "/"; // Корень грамматики Root = expr; // Приоритеты операций RegisterOperators(30, "+", "-"); RegisterOperators(40, "*", "/"); // Пунктуация MarkPunctuation("(", ")"); RegisterBracePair("(", ")"); MarkTransient(term, expr, binOp, unOp, parExpr); }
private NonTerminal WhenGrammar() { var starOperator = _("StarOperator", ToTerm("*")); var stringOperator = _("StringOperator", ToTerm("=") | "!="); var numberOperator = _("NumberOperator", ToTerm("=") | "!=" | ">" | ">=" | "<" | "<="); var headerName = new StringLiteral("Header ExpressionExtensions", "'", StringOptions.NoEscapes); var headerValue = new StringLiteral("Header Value", "'", StringOptions.NoEscapes); var headerCondition = _("HeaderCondition", ToTerm("HEADER") + headerName + stringOperator + headerValue); var requestHeaderCondition = _("RequestHeaderCondition", ToTerm("REQUEST") + headerCondition); var responseHeaderCondition = _("ResponseHeaderCondition", ToTerm("RESPONSE") + headerCondition); var statusCodeValue = new NumberLiteral("Status Code Value", NumberOptions.IntOnly); var statusCodeCondition = _("StatusCodeCondition", ToTerm("STATUS") + "CODE" + numberOperator + statusCodeValue); var requestSizeValue = new NumberLiteral("Request Size Value", NumberOptions.IntOnly); var requestSizeCondition = _("RequestSizeCondition", ToTerm("REQUEST") + "SIZE" + numberOperator + requestSizeValue); var responseSizeValue = new NumberLiteral("Response Size Value", NumberOptions.IntOnly); var responseSizeCondition = _("ResponseSizeCondition", ToTerm("RESPONSE") + "SIZE" + numberOperator + responseSizeValue); var urlValue = new StringLiteral("Url Value", "'", StringOptions.NoEscapes); var urlCondition = _("UrlCondition", ToTerm("URL") + stringOperator + urlValue); var machineValue = new StringLiteral("Machine Value", "'", StringOptions.NoEscapes); var machineCondition = _("MachineCondition", ToTerm("MACHINE") + stringOperator + machineValue); var expression = _("Expression"); var logicalOperator = _("LogicalOperator", ToTerm("AND") | ToTerm("OR")); var logicalOperation = _("LogicalOperation", expression + logicalOperator + expression); var parentheses = _("Parentheses", "(" + logicalOperation + ")"); _(expression, responseSizeCondition | requestSizeCondition | statusCodeCondition | requestHeaderCondition | responseHeaderCondition | urlCondition | machineCondition | logicalOperation | parentheses); return _("When", ToTerm("WHEN") + expression | ToTerm("WHEN") + starOperator); }
/// <summary> /// 使うな /// </summary> public Kbtter4CommandlineGrammar() : base() { var Number = new NumberLiteral("Number"); Number.DefaultIntTypes = new[] { TypeCode.Int32, TypeCode.Int64 }; Number.DefaultFloatType = TypeCode.Double; var String = new StringLiteral("String", "\"", StringOptions.AllowsAllEscapes); var Identifer = new IdentifierTerminal("Identifer"); var Value = new NonTerminal("Value"); var Parameter = new NonTerminal("Parameter"); var Parameters = new NonTerminal("Parameters"); var Command = new NonTerminal("Command"); Value.Rule = Number | String | "true" | "false"; Parameter.Rule = Identifer + "=>" + Value; Parameters.Rule = MakeStarRule(Parameters, ToTerm(","), Parameter); Command.Rule = Identifer + Parameters; Root = Command; MarkTransient(Parameters, Value); MarkPunctuation("=>"); }
//70 50' 44" N 1 13' 66" E public CoordinateGrammar() { #region Terminals var integer = new NumberLiteral("integer", NumberOptions.IntOnly); var point = ToTerm(".", "dot"); var lat = ToTerm("N", "north") | ToTerm("S", "south"); var lon = ToTerm("E", "east") | ToTerm("W", "west"); var minuteMarker = ToTerm("'", "minute"); var secondMarker = ToTerm("\"", "second"); #endregion #region Non-Terminals var decimalAmount = new NonTerminal("decimalAmount", typeof(DecimalAmountNode)); var minute = new NonTerminal("minute", typeof(MinuteNode)); var second = new NonTerminal("second", typeof(SecondNode)); var imperialMagnitude = new NonTerminal("decimalMagnitude", typeof (ImperialMagnitudeNode)); var imperialLatitude = new NonTerminal("imperialLatitude", typeof (ImperialLatitudeNode)); var imperialLongitude = new NonTerminal("imperialLongitude", typeof (ImperialLongitudeNode)); var imperialCoordinate = new NonTerminal("imperialCoordinate", typeof(ImperialCoordinateNode)); #endregion #region Rules decimalAmount.Rule = integer | integer + point + integer; minute.Rule = integer + minuteMarker; second.Rule = integer + secondMarker; imperialMagnitude.Rule = integer + minute + second; imperialLatitude.Rule = imperialMagnitude + lat; imperialLongitude.Rule = imperialMagnitude + lon; imperialCoordinate.Rule = imperialLatitude + imperialLongitude; #endregion Root = imperialCoordinate; }
public GramaticaCHISON() : base(false) { CommentTerminal blockComment = new CommentTerminal("block-comment", "/*", "*/"); CommentTerminal lineComment = new CommentTerminal("line-comment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); NonGrammarTerminals.Add(blockComment); NonGrammarTerminals.Add(lineComment); /* Reserved Words */ KeyTerm null_ = ToTerm("null"), true_ = ToTerm("true"), false_ = ToTerm("false"), in_ = ToTerm("in"), out_ = ToTerm("out"), int_ = ToTerm("int"), double_ = ToTerm("double"), string_ = ToTerm("string"), boolean_ = ToTerm("boolean"), date_ = ToTerm("date"), time_ = ToTerm("time"), counter_ = ToTerm("counter"), map_ = ToTerm("map"), list_ = ToTerm("list"), set_ = ToTerm("set"); MarkReservedWords("null", "true", "false", "in", "out", "int", "double", "string", "boolean", "date", "time", "counter", "map", "list", "set"); /* Symbols*/ KeyTerm equal = ToTerm("="), menorque = ToTerm("<"), mayorque = ToTerm(">"), leftCor = ToTerm("["), rightCor = ToTerm("]"), dollar = ToTerm("$"), comma = ToTerm(","), comilla = ToTerm("\""); var number = new NumberLiteral("number"); var stringliteral = new StringLiteral("stringliteral", "\"", StringOptions.IsTemplate); var stringcodigo = new StringLiteral("stringcodigo", "$", StringOptions.AllowsLineBreak); RegexBasedTerminal date = new RegexBasedTerminal("date", "\'[0-9]+-[0-9]+-[0-9]+\'"); RegexBasedTerminal time = new RegexBasedTerminal("time", "\'[0-9]+:[0-9]+:[0-9]+\'"); RegexBasedTerminal identifier = new RegexBasedTerminal("identifier", "([a-zA-ZñÑ]|_)([a-zA-ZñÑ]|[0-9]|_)*"); //RegexBasedTerminal date = new RegexBasedTerminal("date", "'[0-2][0-9]{3}-([0][0-9]|[1][0-2])-([0][0-9]|[1][0-9]|[2][0-9]|[3][0-1])'"); //RegexBasedTerminal time = new RegexBasedTerminal("time", "'([0][0-9]|[1][0-9]|[2][0-4]):[0-5][0-9]:[0-5][0-9]'"); //IdentifierTerminal fileName = new IdentifierTerminal("fileName", "!@#$%^*_'.?-", "!@#$%^*_'.?0123456789"); NonTerminal INICIO = new NonTerminal("INICIO"), ARCHIVO = new NonTerminal("ARCHIVO"), TYPE = new NonTerminal("TYPE"), TYPE_PRIMITIVE = new NonTerminal("TYPE_PRIMITIVE"), TYPE_COLLECTION = new NonTerminal("TYPE_COLLECTION"), INSTRUCCIONES = new NonTerminal("INSTRUCCIONES"), INSTRUCCION = new NonTerminal("INSTRUCCION"), BLOQUE = new NonTerminal("BLOQUE"), LISTA_BLOQUE = new NonTerminal("LISTA_BLOQUE"), VALOR = new NonTerminal("VALOR"), LISTA = new NonTerminal("LISTA"), VALORES = new NonTerminal("VALORES"); this.Root = INICIO; INICIO.Rule = ARCHIVO; ARCHIVO.Rule = dollar + BLOQUE + dollar | LISTA_BLOQUE | TYPE | TYPE_COLLECTION; TYPE.Rule = map_ | list_ | set_; TYPE_PRIMITIVE.Rule = int_ | double_ | string_ | boolean_ | date_ | time_; TYPE_COLLECTION.Rule = int_ | double_ | string_ | boolean_ | date_ | time_ | identifier | counter_ | map_ + menorque + TYPE_PRIMITIVE + comma + TYPE_COLLECTION + mayorque | list_ + menorque + TYPE_COLLECTION + mayorque | set_ + menorque + TYPE_COLLECTION + mayorque; LISTA_BLOQUE.Rule = MakePlusRule(LISTA_BLOQUE, comma, BLOQUE); BLOQUE.Rule = menorque + INSTRUCCIONES + mayorque; INSTRUCCIONES.Rule = MakePlusRule(INSTRUCCIONES, comma, INSTRUCCION); INSTRUCCION.Rule = stringliteral + equal + VALOR; VALOR.Rule = number | stringliteral | true_ | false_ | date | time | in_ | out_ | null_ | LISTA | BLOQUE | stringcodigo; LISTA.Rule = leftCor + VALORES + rightCor | leftCor + rightCor; VALORES.Rule = MakePlusRule(VALORES, comma, VALOR); }
public xformGrammar() : base(false) { CommentTerminal comentarioSimple = new CommentTerminal("comentarioSimple", "$$", "\n", "\r\n"); CommentTerminal comentarioMulti = new CommentTerminal("comentarioMulti", "$#", "#$"); base.NonGrammarTerminals.Add(comentarioMulti); base.NonGrammarTerminals.Add(comentarioSimple); RegexBasedTerminal DosPuntos = new RegexBasedTerminal("DosPUntos", ":"); //reservadas RegexBasedTerminal importar = new RegexBasedTerminal("importar", "importar"); //RegexBasedTerminal super = new RegexBasedTerminal("super", "super"); var super = ToTerm("super"); //RegexBasedTerminal sobreescribir = new RegexBasedTerminal("sobreescribir", "\\/\\*\\*Sobreescribir\\*\\*\\/"); //var sobreescribir = ToTerm("\\/\\*\\*Sobreescribir\\*\\*\\/"); var sobreescribir = ToTerm("/**Sobreescribir**/"); var constructor = ToTerm("__constructor"); RegexBasedTerminal metodo = new RegexBasedTerminal("metodo", "metodo"); RegexBasedTerminal principal = new RegexBasedTerminal("principal", "principal"); RegexBasedTerminal funcion = new RegexBasedTerminal("funcion", "funcion"); RegexBasedTerminal clase = new RegexBasedTerminal("clase", "clase"); RegexBasedTerminal retornar = new RegexBasedTerminal("retornar", "retornar "); RegexBasedTerminal imprimir = new RegexBasedTerminal("imprimir", "imprimir\\["); RegexBasedTerminal Rself = new RegexBasedTerminal("Rself", "self"); //RegexBasedTerminal Rsi = new RegexBasedTerminal("Rsi", "SI "); var Rsi = ToTerm("SI"); var nuevo = ToTerm("nuevo"); //RegexBasedTerminal Rsino = new RegexBasedTerminal("Rsino", "SI_NO "); var Rsino = ToTerm("SI_NO"); //RegexBasedTerminal Rsinosi = new RegexBasedTerminal("Rsinosi", "SI_NO_SI "); var Rsinosi = ToTerm("SI_NO_SI"); //RegexBasedTerminal Rsalir = new RegexBasedTerminal("Rsalir", "salir "); var Rsalir = ToTerm("salir"); //var Rsalir = ToTerm("salir "); RegexBasedTerminal Relegir = new RegexBasedTerminal("Relejir", "ELEGIR CASO "); RegexBasedTerminal Rcontinuar = new RegexBasedTerminal("Rcontinuar", "CONTINUAR "); //RegexBasedTerminal Rmientras = new RegexBasedTerminal("Rmientras", "MIENTRAS "); var Rmientras = ToTerm("mientras"); //RegexBasedTerminal Rhacer = new RegexBasedTerminal("Rhacer", "HACER "); var Rhacer = ToTerm("hacer"); RegexBasedTerminal Rrepetir = new RegexBasedTerminal("Rrepetir", "REPETIR "); RegexBasedTerminal Rhasta = new RegexBasedTerminal("Rhasta", "HASTA "); //RegexBasedTerminal RPara = new RegexBasedTerminal("Rpara", "Para"); var RPara = ToTerm("Para"); RegexBasedTerminal Rloop = new RegexBasedTerminal("Rloop", "loop "); RegexBasedTerminal metodoImprimir = new RegexBasedTerminal("metodoImprimir", "out_string\\["); RegexBasedTerminal RParseint = new RegexBasedTerminal("RParseint", "ParseInt\\["); RegexBasedTerminal RParseD = new RegexBasedTerminal("RParseD", "ParseDouble\\["); RegexBasedTerminal RintToSTR = new RegexBasedTerminal("RintToSTR", "intToSTR\\["); RegexBasedTerminal RdoubleToStr = new RegexBasedTerminal("RdoubleToStr", "doubleToStr\\["); RegexBasedTerminal RdoubleToInt = new RegexBasedTerminal("RdoubleToInt", "doubleToInt\\["); //Visibilidad RegexBasedTerminal publico = new RegexBasedTerminal("publico", "publico "); RegexBasedTerminal privado = new RegexBasedTerminal("privado", "privado "); RegexBasedTerminal protegido = new RegexBasedTerminal("protegido", "protegido "); //Tipos de Datos IdentifierTerminal ID = new IdentifierTerminal("ID"); RegexBasedTerminal REntero = new RegexBasedTerminal("REntero", "entero"); NumberLiteral Entero = new NumberLiteral("entero"); RegexBasedTerminal Rvoid = new RegexBasedTerminal("Rvoid", "void"); RegexBasedTerminal RDoble = new RegexBasedTerminal("RDoble", "decimal"); RegexBasedTerminal Doble = new RegexBasedTerminal("Doble", "[0-9]+\\.[0-9]{6}"); RegexBasedTerminal Rboolean = new RegexBasedTerminal("Rboolean", "booleano"); RegexBasedTerminal Verdadero = new RegexBasedTerminal("verdadero", "verdadero|true"); RegexBasedTerminal Falso = new RegexBasedTerminal("falso", "falso|false"); RegexBasedTerminal RCaracter = new RegexBasedTerminal("RCaracter", "caracter"); RegexBasedTerminal Caracter = new RegexBasedTerminal("Caracter", "\'([a-zA-Z0-9]|#(n|f|t)|#|\\[|\\])\'"); RegexBasedTerminal RCadena = new RegexBasedTerminal("RCadena", "cadena"); StringLiteral Cadena = new StringLiteral("Cadena", "\""); RegexBasedTerminal ruta = new RegexBasedTerminal("ruta", "http://([a-zA-Z0-9]|#(n|f|t)|#|\\[|\\|.|_])+"); //StringLiteral ruta = new StringLiteral("ruta", "http:"); //CommentTerminal ruta = new CommentTerminal("ruta", "http",","); //Relaciones RegexBasedTerminal Igual = new RegexBasedTerminal("igual", "=="); RegexBasedTerminal Diferente = new RegexBasedTerminal("Diferente", "!="); RegexBasedTerminal Menor = new RegexBasedTerminal("menor", "<"); RegexBasedTerminal Mayor = new RegexBasedTerminal("mayor", ">"); RegexBasedTerminal MenorQue = new RegexBasedTerminal("menor_que", "<="); RegexBasedTerminal MayorQue = new RegexBasedTerminal("mayor_que", ">="); //Logicos //RegexBasedTerminal Or = new RegexBasedTerminal("or", "or"); var Or = ToTerm("||"); //RegexBasedTerminal XOR = new RegexBasedTerminal("Xor", "xor"); //var XOR = ToTerm("xor"); //RegexBasedTerminal and = new RegexBasedTerminal("and", "and"); var and = ToTerm("&&"); //RegexBasedTerminal not = new RegexBasedTerminal("not", "NOT"); var not = ToTerm("!"); //Artimeticos RegexBasedTerminal suma = new RegexBasedTerminal("suma", "\\+"); RegexBasedTerminal resta = new RegexBasedTerminal("resta", "-"); RegexBasedTerminal multiplicacion = new RegexBasedTerminal("multi", "\\*"); RegexBasedTerminal division = new RegexBasedTerminal("div", "\\/"); RegexBasedTerminal potencia = new RegexBasedTerminal("power", "^"); RegexBasedTerminal modulo = new RegexBasedTerminal("modulo", "%"); RegexBasedTerminal aumentar = new RegexBasedTerminal("aumentar", "\\+\\+"); RegexBasedTerminal disminuir = new RegexBasedTerminal("disminuir", "--"); this.RegisterOperators(0, suma, resta); this.RegisterOperators(1, division, multiplicacion); this.RegisterOperators(2, potencia); this.RegisterOperators(3, aumentar, disminuir); this.RegisterOperators(4, Menor, Mayor, MenorQue, MayorQue, Igual, Diferente); //this.RegisterOperators(5, Or, not, XOR, and); NonTerminal RAIZ = new NonTerminal("S"), ENCABEZADO = new NonTerminal("Cabeza"), CUERPO = new NonTerminal("Cuerpo"), IMPORTACIONES = new NonTerminal("importaciones"), IMPORTACION = new NonTerminal("importacion"), Componentes = new NonTerminal("Componentes"), Componente = new NonTerminal("Componente"), Parametros = new NonTerminal("Parametros"), Parametro = new NonTerminal("Parametro"), Sentencias = new NonTerminal("Sentencias"), SENTENCIA = new NonTerminal("Sentencia"), DECLARACION = new NonTerminal("Declaracion"), ASIGNACION = new NonTerminal("Asignacion"), While = new NonTerminal("While"), Do_While = new NonTerminal("Do_While"), IF = new NonTerminal("If"), For = new NonTerminal("for"), Loop = new NonTerminal("Loop"), ELEGIR = new NonTerminal("Elegir"), Casos = new NonTerminal("Casos"), Caso = new NonTerminal("Caso"), SalidaC = new NonTerminal("SalidaC"), aINT = new NonTerminal("aINT"), aDou = new NonTerminal("aDou"), intASt = new NonTerminal("intASt"), douASt = new NonTerminal("douASt"), douAINt = new NonTerminal("douAINt"), Imprimir = new NonTerminal("Imprimir"), VISIBILIDAD = new NonTerminal("Visibilidad"), Contenido = new NonTerminal("Contenido"), Globales = new NonTerminal("Globales"), Global = new NonTerminal("Global"), Tipo = new NonTerminal("Tipo"), Retorno = new NonTerminal("Retorno"), FUNCIONES = new NonTerminal("Funciones"), Operacion = new NonTerminal("Operacion"), Operaciones = new NonTerminal("Operaciones"), Dimensiones = new NonTerminal("Dimensiones"), Dimension = new NonTerminal("Dimension"), Partes = new NonTerminal("Partes"), AsignacionesArreglo = new NonTerminal("AsignacionesArreglo"), AsignacionArreglo = new NonTerminal("AsignacionArreglo"), Condicion = new NonTerminal("Condicion"), Logica = new NonTerminal("Logica"), Relacional = new NonTerminal("Relacional"), Nombres = new NonTerminal("Nombres"), VALOR = new NonTerminal("Valor"), SINO = new NonTerminal("Sino"), Salir = new NonTerminal("Salir"), Repetir = new NonTerminal("Repetir"), SINOSI = new NonTerminal("SinoS"), LISTACUERPO = new NonTerminal("LISTACUERPO"), LLAMAR_SUPER = new NonTerminal("LLAMAR_SUPER"), LISTA_PARAMETROS = new NonTerminal("LISTA_PARAMETROS"), PRAGMA_SOBREESCRIBIR = new NonTerminal("PRAGMA_SOBREESCRIBIR"), OBJETO = new NonTerminal("OBJETO"), PARAMETROS_INSTANCIA = new NonTerminal("PARAMETROS_INSTANCIA"), AUMENTO_DECREMENTO = new NonTerminal("AUMENTO_DECREMENTO"), ELSE = new NonTerminal("ELSE"), CAD = new NonTerminal("CAD"); RAIZ.Rule = ENCABEZADO + LISTACUERPO | LISTACUERPO; ENCABEZADO.Rule = importar + "(" + IMPORTACIONES + ")"; IMPORTACIONES.Rule = IMPORTACIONES + "," + IMPORTACION | IMPORTACION; IMPORTACION.Rule = ID + "." + ID | Cadena | ruta; //LISTACUERPO.Rule = MakePlusRule(LISTACUERPO, Cuerpo); LISTACUERPO.Rule = CUERPO; CUERPO.Rule = MakeStarRule(LISTACUERPO, CUERPO); CUERPO.Rule = clase + ID + "[" + ID + "]:" + Partes //6 | clase + ID + "[]:" + Partes //4 | VISIBILIDAD + clase + ID + "[]:" + Partes //5 | VISIBILIDAD + clase + ID + "[" + ID + "]:" + Partes; //7 Partes.Rule = Globales + Componentes | Componentes; Globales.Rule = Globales + Global | Global; Global.Rule = Tipo + Nombres | VISIBILIDAD + Tipo + Nombres | Tipo + Nombres + "=>" + Operacion | VISIBILIDAD + Tipo + Nombres + "=>" + Operacion | Tipo + Nombres + Dimensiones | VISIBILIDAD + Tipo + Nombres + Dimensiones | Tipo + Nombres + "=>" + Operacion | VISIBILIDAD + Tipo + Nombres + "=>" + Operacion;; Nombres.Rule = Nombres + "," + ID | ID; Componentes.Rule = Componentes + Componente | Componente; //| sobreescribir Componente ; PRAGMA_SOBREESCRIBIR.Rule = sobreescribir | Empty; Componente.Rule = PRAGMA_SOBREESCRIBIR + ID + "[]:" + Sentencias //3 | PRAGMA_SOBREESCRIBIR + ID + "[" + Parametros + "]:" + Sentencias //5 | PRAGMA_SOBREESCRIBIR + constructor + "[]:" + Sentencias //3 | PRAGMA_SOBREESCRIBIR + constructor + "[" + Parametros + "]:" + Sentencias //5 | PRAGMA_SOBREESCRIBIR + Tipo + ID + "[]:" + Sentencias //4 | PRAGMA_SOBREESCRIBIR + Tipo + ID + "[" + Parametros + "]:" + Sentencias //6 | PRAGMA_SOBREESCRIBIR + VISIBILIDAD + ID + "[]:" + Sentencias //4 | PRAGMA_SOBREESCRIBIR + VISIBILIDAD + ID + "[" + Parametros + "]:" + Sentencias //6 | PRAGMA_SOBREESCRIBIR + VISIBILIDAD + Tipo + ID + "[]:" + Sentencias //5 | PRAGMA_SOBREESCRIBIR + VISIBILIDAD + Tipo + ID + "[" + Parametros + "]:" + Sentencias; //7 Sentencias.Rule = Sentencias + SENTENCIA | SENTENCIA; SENTENCIA.Rule = Retorno | Salir // Vamos a ver si la quitamos. | FUNCIONES | ASIGNACION | DECLARACION //| LLAMAR_SUPER | IF | For | While | Loop | Do_While | Imprimir | ELEGIR | Loop | SalidaC | aINT | aDou | douASt | intASt | douAINt //| Salir | AUMENTO_DECREMENTO //| Operacion ; //Poder hacer id++ o id -- en cuarquier lado prros :v . AUMENTO_DECREMENTO.Rule = ID + aumentar | ID + disminuir; DECLARACION.Rule = Tipo + Nombres | Tipo + Nombres + "=>" + Operacion | Tipo + Nombres + "=>" + nuevo + ID + "[" + PARAMETROS_INSTANCIA + "]" //objeto nombre => nuevo objeto[] /*| Tipo + Nombres + "=>" + nuevo + Tipo +"["+ Nombres + "]" | Tipo + Nombres + "=>" + nuevo + Tipo + "[" + "]" | Tipo + ID + Dimensiones + "=>" + nuevo + Tipo + "[" + "]" | Tipo + ID + Dimensiones + "=>" + nuevo + Tipo + "[" + Nombres +"]" */ | Tipo + ID + Dimensiones; LISTA_PARAMETROS.Rule = LISTA_PARAMETROS + "," + LISTA_PARAMETROS | Tipo + ID; ASIGNACION.Rule = ID + "=>" + Operacion | ID + Dimensiones + "=>" + Operacion | ID + "." + ID + "=>" + Operacion | ID + "=>" + nuevo + ID + "[" + PARAMETROS_INSTANCIA + "]" | ID + Dimensiones + "=>" + nuevo + ID + "[" + PARAMETROS_INSTANCIA + "]" | ID + "." + ID + "=>" + nuevo + ID + "[" + PARAMETROS_INSTANCIA + "]"; PARAMETROS_INSTANCIA.Rule = PARAMETROS_INSTANCIA + "," + ID | ID | ID + "." + ID | Empty; IF.Rule = Rsi + "[" + Condicion + "]" + DosPuntos + Sentencias + ELSE //7 //| Rsi + "[" + Condicion + "]" + DosPuntos + Sentencias + Sino//6 //| Rsi + "[" + Condicion + "]" + DosPuntos + Sentencias + SinoS//6 ; //| Rsi + "[" + Condicion + "]" + DosPuntos + Sentencias ;//5 ELSE.Rule = ELSE + ELSE | SINO | SINOSI | Empty; SINOSI.Rule = Rsinosi + "[" + Condicion + "]" + DosPuntos + Sentencias //7 | Rsinosi + "[" + Condicion + "]" + DosPuntos + Sentencias; //6 SINO.Rule = Rsino + DosPuntos + Sentencias; For.Rule = RPara + "[" + ID + "=>" + Operacion + DosPuntos + Condicion + DosPuntos + ID + aumentar + "]" + DosPuntos + Sentencias //12 | RPara + "[" + ID + "=>" + Operacion + DosPuntos + Condicion + DosPuntos + ID + disminuir + "]" + DosPuntos + Sentencias //12 | RPara + "[" + Tipo + ID + "=>" + Operacion + DosPuntos + Condicion + DosPuntos + ID + aumentar + "]" + DosPuntos + Sentencias //13 | RPara + "[" + Tipo + ID + "=>" + Operacion + DosPuntos + Condicion + DosPuntos + ID + disminuir + "]" + DosPuntos + Sentencias; //13 While.Rule = Rmientras + "[" + Condicion + "]" + DosPuntos + Sentencias; Do_While.Rule = Rhacer + DosPuntos + Sentencias + Rmientras + "[" + Condicion + "]"; Repetir.Rule = Rrepetir + DosPuntos + Sentencias + Rhasta + Condicion + "]"; Loop.Rule = Rloop + DosPuntos + Sentencias; SalidaC.Rule = metodoImprimir + Operacion + "]"; aINT.Rule = RParseint + Operacion + "]"; aDou.Rule = RParseD + Operacion + "]"; intASt.Rule = RintToSTR + Operacion + "]"; douASt.Rule = RdoubleToStr + Operacion + "]"; douAINt.Rule = RdoubleToInt + Operacion + "]"; Retorno.Rule = retornar + Operacion; Imprimir.Rule = imprimir + Operacion + "]"; Salir.Rule = Rsalir; LLAMAR_SUPER.Rule = super + Nombres + "]" | super + "]"; Condicion.Rule = Logica; //Condicion.Rule = MakePlusRule(Condicion, Logica); Logica.Rule = /*"{" + Relacional + Relacional + Or + "}" | "{" + Relacional + Relacional + and + "}" | "{" + Relacional + Relacional + XOR + "}" | "{" + Relacional + not + "}"*/ "{" + Logica + Logica + Or + "}" | "{" + Logica + Logica + and + "}" //| "{" + Logica + Logica + XOR + "}" | "{" + Logica + Logica + not + "}" | "{" + Logica + not + "}" | "{" + Relacional + not + "}" | Relacional; Relacional.Rule = "[" + Relacional + Relacional + Igual + "]" | "[" + Relacional + Relacional + Diferente + "]" | "[" + Relacional + Relacional + Menor + "]" | "[" + Relacional + Relacional + MenorQue + "]" | "[" + Relacional + Relacional + Mayor + "]" | "[" + Relacional + Relacional + MayorQue + "]" | Operacion; Operacion.Rule = "(" + Operacion + Operacion + suma + ")" | "(" + Operacion + Operacion + resta + ")" | "(" + Operacion + Operacion + division + ")" | "(" + Operacion + Operacion + multiplicacion + ")" | "(" + Operacion + Operacion + potencia + ")" | CAD; CAD.Rule = ID | ID + "[" + Operacion + "]" | ID + "." + ID | ID + Dimensiones + "." + ID | Rself + "." + ID | VALOR | SalidaC | aINT | aDou | intASt | douASt | douAINt; Dimensiones.Rule = Dimensiones + Dimension | Dimension; Dimension.Rule = "[" + Operacion + "]"; OBJETO.Rule = ID; Tipo.Rule = OBJETO | REntero | Rboolean | RCadena | RDoble | RCaracter | Rvoid; //| ID; VALOR.Rule = Entero | Verdadero | Falso | Caracter | Doble | Cadena; VISIBILIDAD.Rule = publico | privado | protegido; FUNCIONES.Rule = super + "[" + Operaciones + "]" | super + "[" + "]" | ID + "[" + Operaciones + "]" | ID + "[" + "]"; //| LLAMAR_SUPER; Operaciones.Rule = Operaciones + "," + Operacion | Operacion; ELEGIR.Rule = Relegir + "(" + Operacion + ")" + DosPuntos + Casos; Casos.Rule = Caso + Casos | Caso; Caso.Rule = Operacion + DosPuntos + Sentencias | "defecto" + DosPuntos + Sentencias; Parametros.Rule = Parametros + "," + Parametro | Parametro; Parametro.Rule = Tipo + ID; this.Root = RAIZ; RegisterOperators(1, FUNCIONES); RegisterOperators(2, ASIGNACION); }
public RefalGrammar() : base(true) // case sensitive { GrammarComments = "Refal-5 language interpreter based on Irony toolkit."; // Terminals var Number = new NumberLiteral("Number"); Number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; Number.AddPrefix("0x", NumberOptions.Hex); Number.AddSuffix("u", TypeCode.UInt32); Number.AddSuffix("l", TypeCode.Int64); Number.AddSuffix("ul", TypeCode.UInt64); Number.Options |= NumberOptions.IntOnly; var CharLiteral = new StringLiteral("Char", "'", StringOptions.AllowsAllEscapes); var StringLiteral = new StringLiteral("String", "\"", StringOptions.AllowsAllEscapes); var Identifier = new IdentifierTerminal("Identifier", "_-", ""); var LineComment = new CommentTerminal("LineComment", "*", "\n", "\r"); LineComment.ValidateToken += LineComment_ValidateToken; var BlockComment = new CommentTerminal("BlockComment", "/*", "*/"); NonGrammarTerminals.Add(LineComment); NonGrammarTerminals.Add(BlockComment); // Non-terminals var Program = new NonTerminal("Program", typeof(Program)); var Definition = new NonTerminal("Definition"); var Function = new NonTerminal("Function", typeof(DefinedFunction)); var External = new NonTerminal("External", typeof(AuxiliaryNode)); var IdentifierList = new NonTerminal("Identifier+", typeof(AuxiliaryNode)); var Block = new NonTerminal("Block", typeof(Block)); var Sentence = new NonTerminal("Sentence", typeof(Sentence)); var RSentence = new NonTerminal("RSentence", typeof(AuxiliaryNode)); var SentenceList = new NonTerminal("Sentence+", typeof(AuxiliaryNode)); var Pattern = new NonTerminal("Pattern", typeof(Pattern)); var PatternItem = new NonTerminal("PatternItem"); var PatternInParentheses = new NonTerminal("(Pattern)", typeof(ExpressionInBraces)); var Expression = new NonTerminal("Expression", typeof(Expression)); var ExpressionItem = new NonTerminal("ExpressionItem"); var ExpressionInParentheses = new NonTerminal("(Expression)", typeof(ExpressionInBraces)); var Var = new NonTerminal("Variable", Variable.CreateVariableNode); var VarPrefix = new NonTerminal("VariablePrefix"); var VarIndex = new NonTerminal("VariableIndex"); var Symbol = new NonTerminal("Symbol", LiteralValueNodeHelper.InitNode); var Call = new NonTerminal("Call", typeof(FunctionCall)); var FunctionName = new NonTerminal("FunctionName", typeof(AuxiliaryNode)); var WhereOrWithClause = new NonTerminal("WhereOrWithClause", typeof(Conditions)); var CommaOrAmpersand = new NonTerminal("CommaOrAmpersand"); var RWhereOrWithClause = new NonTerminal("RWhereOrWithClause", typeof(AuxiliaryNode)); var RExpressionOrWhereOrWithClause = new NonTerminal("RExpressionOrWhereOrWithClause"); var SemicolonOpt = new NonTerminal("[;]", Empty | ";"); var EntryOpt = new NonTerminal("[ENTRY]", Empty | "$ENTRY"); var Extern = new NonTerminal("Extern", ToTerm("$EXTRN") | "$EXTERN" | "$EXTERNAL"); // Rules Root = Program; Program.Rule = MakePlusRule(Program, Definition); Definition.Rule = Function | External; External.Rule = Extern + IdentifierList + ";"; IdentifierList.Rule = MakePlusRule(IdentifierList, ToTerm(","), Identifier); Function.Rule = EntryOpt + Identifier + Block + SemicolonOpt; Block.Rule = "{" + SentenceList + SemicolonOpt + "}"; SentenceList.Rule = MakePlusRule(SentenceList, ToTerm(";"), Sentence); Sentence.Rule = Pattern + RSentence; RSentence.Rule = "=" + Expression | WhereOrWithClause; Pattern.Rule = MakeStarRule(Pattern, PatternItem); PatternItem.Rule = Var | Symbol | PatternInParentheses; PatternInParentheses.Rule = "(" + Pattern + ")"; Expression.Rule = MakeStarRule(Expression, ExpressionItem); ExpressionItem.Rule = Call | Var | Symbol | ExpressionInParentheses; ExpressionInParentheses.Rule = "(" + Expression + ")"; Var.Rule = VarPrefix + "." + VarIndex; VarPrefix.Rule = ToTerm("e") | "s" | "t"; VarIndex.Rule = Number | Identifier; Symbol.Rule = StringLiteral | CharLiteral | Number | "True" | "False" | Identifier; Call.Rule = "<" + FunctionName + Expression + ">"; FunctionName.Rule = Identifier | "+" | "-" | "*" | "/"; WhereOrWithClause.Rule = CommaOrAmpersand + Expression + ":" + RWhereOrWithClause; CommaOrAmpersand.Rule = ToTerm(",") | "&"; RWhereOrWithClause.Rule = Block // with-clause | Pattern + RExpressionOrWhereOrWithClause; // where-clause RExpressionOrWhereOrWithClause.Rule = ToTerm("=") + Expression | WhereOrWithClause; // Punctuation, braces, transient terms, options MarkPunctuation("(", ")"); MarkPunctuation("{", "}"); MarkPunctuation("<", ">"); MarkPunctuation("=", ",", "&", ";"); RegisterBracePair("(", ")"); RegisterBracePair("<", ">"); RegisterBracePair("{", "}"); MarkTransient(Definition, PatternItem, ExpressionItem, SemicolonOpt, EntryOpt, Extern, CommaOrAmpersand, VarPrefix, VarIndex, RExpressionOrWhereOrWithClause); LanguageFlags = LanguageFlags.CreateAst | LanguageFlags.SupportsBigInt | LanguageFlags.TailRecursive; }
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("Int"); MarkReservedWords("Double"); MarkReservedWords("String"); MarkReservedWords("Char"); MarkReservedWords("Bool"); MarkReservedWords("Void"); MarkReservedWords("True"); MarkReservedWords("False"); MarkReservedWords("Import"); MarkReservedWords("Return"); MarkReservedWords("If"); MarkReservedWords("Else"); MarkReservedWords("Switch"); MarkReservedWords("Case"); MarkReservedWords("Break"); MarkReservedWords("Default"); MarkReservedWords("For"); MarkReservedWords("Do"); MarkReservedWords("While"); MarkReservedWords("Print"); MarkReservedWords("CompareTo"); MarkReservedWords("GetUser()"); //---------------------> (Opcional)Definir variables para palabras reservadas var entero = ToTerm("Int"); var doubl = ToTerm("Double"); var strin = ToTerm("String"); var caracter = ToTerm("Char"); var booleano = ToTerm("Bool"); var voi = ToTerm("Void"); var verdadero = ToTerm("True"); var falso = ToTerm("False"); var importacion = ToTerm("Import"); var retornar = ToTerm("Return"); var si = ToTerm("If"); var sino = ToTerm("Else"); var switc = ToTerm("Switch"); var caso = ToTerm("Case"); var brea = ToTerm("Break"); var defaul = ToTerm("Default"); var para = ToTerm("For"); var hacer = ToTerm("Do"); var mientras = ToTerm("While"); var imprime = ToTerm("Print"); var comparador = ToTerm("CompareTo"); var nombreUsuario = ToTerm("GetUser()"); //---------------------> (Opcional)Definir variables para signos y mas var coma = ToTerm(","); var pto = ToTerm("."); var pyc = ToTerm(";"); var dospts = ToTerm(":"); var apar = ToTerm("("); var cpar = ToTerm(")"); var alla = ToTerm("{"); var clla = ToTerm("}"); var acor = ToTerm("["); var ccor = ToTerm("]"); //------------------------> Operadores var mas = ToTerm("+"); var menos = ToTerm("-"); var multiplicacion = ToTerm("*"); var division = ToTerm("/"); var porcentaje = ToTerm("%"); var potencia = ToTerm("^"); var mayor = ToTerm(">"); var menor = ToTerm("<"); var menorigual = ToTerm("<="); var mayorigual = ToTerm(">="); var comparacion = ToTerm("=="); var diferente = ToTerm("!="); var or = ToTerm("||"); var and = ToTerm("&&"); var xor = ToTerm("|&"); var not = ToTerm("!"); var suma = ToTerm("+="); var resta = ToTerm("-="); var asignar = ToTerm("="); var disminuir = ToTerm("--"); var aumentar = ToTerm("++"); //---------------------> No Terminales var INICIO = new NonTerminal("INICIO"); var METODO = new NonTerminal("METODO"); var SENTENCIAS = new NonTerminal("SENTENCIAS"); var DECLARA = new NonTerminal("DECLARA"); var ASIGNACIONVAR = new NonTerminal("ASIGNACIONVAR"); var PARAMETROS = new NonTerminal("PARAMETROS"); var PARA = new NonTerminal("PARA"); var DECLARACIONES = new NonTerminal("DECLARACIONES"); var IF = new NonTerminal("IF"); var IFE = new NonTerminal("IFE"); var VARIOS = new NonTerminal("VARIOS"); var LLAMADA = new NonTerminal("LLAMADA"); var VALORES = new NonTerminal("VALORES"); var IMPRIMIR = new NonTerminal("IMPRIMIR"); var WHILE = new NonTerminal("WHILE"); var DOWHILE = new NonTerminal("DOWHILE"); var TIPO = new NonTerminal("TIPO"); var S = new NonTerminal("S"); var EXPRE = new NonTerminal("EXPRE"); var INCREMENTA = new NonTerminal("INCREMENTA"); var DECREMENTA = new NonTerminal("DECREMENTA"); var ASIGNACIONES = new NonTerminal("ASIGNACIONES"); var IMPORTACIONES = new NonTerminal("IMPORTACIONES"); var IMPORTACION = new NonTerminal("IMPORTACION"); var VAR = new NonTerminal("VAR"); var RETOR = new NonTerminal("RETOR"); var CLASES = new NonTerminal("CLASES"); var ARREGLOS = new NonTerminal("ARREGLOS"); var SWITCH = new NonTerminal("SWITCH"); var FOR = new NonTerminal("FOR"); var CASOS = new NonTerminal("CASOS"); var CASO = new NonTerminal("CASO"); var COMPARTO = new NonTerminal("COMPARTO"); //---------------------> Terminales NumberLiteral num = new NumberLiteral("num"); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); var tstring = new StringLiteral("tstring", "\"", StringOptions.AllowsDoubledQuote); var tchar = new StringLiteral("tchar", "'", StringOptions.AllowsDoubledQuote); //----------------------------------------------PRODUCCIONES----------------------------------------------------------- S.Rule = IMPORTACIONES + CLASES; IMPORTACIONES.Rule = MakeStarRule(IMPORTACIONES, IMPORTACION); IMPORTACION.Rule = importacion + tstring + pyc; CLASES.Rule = MakeStarRule(CLASES, INICIO); INICIO.Rule = DECLARA + dospts + TIPO + METODO; /* --------------------------------------------------------------------------------------- * * CREACION DE METODOS * * --------------------------------------------------------------------------------------- */ METODO.Rule = ASIGNACIONES + pyc | apar + PARAMETROS + cpar + alla + VARIOS + clla; /* --------------------------------------------------------------------------------------- * * DECLARACION DE VARIABLES * * --------------------------------------------------------------------------------------- */ TIPO.Rule = entero | caracter | booleano | doubl | strin | voi; ARREGLOS.Rule = id + acor + EXPRE + ccor; DECLARACIONES.Rule = DECLARA + dospts + TIPO + ASIGNACIONES; ASIGNACIONES.Rule = asignar + EXPRE | acor + EXPRE + ccor + asignar + alla + VALORES + clla | acor + EXPRE + ccor | acor + EXPRE + ccor + asignar + EXPRE | Empty; DECLARA.Rule = DECLARA + coma + id | id; ASIGNACIONVAR.Rule = id + asignar + EXPRE | id + asignar + alla + VALORES + clla | id + acor + EXPRE + ccor + asignar + EXPRE; PARAMETROS.Rule = PARAMETROS + coma + PARA | PARA | Empty; PARA.Rule = id + dospts + TIPO; /* --------------------------------------------------------------------------------------- * * SENTENCIAS * * --------------------------------------------------------------------------------------- */ IMPRIMIR.Rule = imprime + apar + EXPRE + cpar + pyc; VARIOS.Rule = MakeStarRule(VARIOS, SENTENCIAS); SENTENCIAS.Rule = DECLARACIONES + pyc | retornar + RETOR + pyc | IF | IFE | WHILE | DOWHILE | IMPRIMIR | INCREMENTA + pyc | DECREMENTA + pyc | LLAMADA + pyc | ASIGNACIONVAR + pyc | ARREGLOS | brea + pyc | SWITCH | FOR; LLAMADA.Rule = id + apar + VALORES + cpar; RETOR.Rule = EXPRE | Empty; VALORES.Rule = VALORES + coma + EXPRE | EXPRE | Empty; IF.Rule = si + apar + EXPRE + cpar + alla + VARIOS + clla; IFE.Rule = si + apar + EXPRE + cpar + alla + VARIOS + clla + sino + alla + VARIOS + clla; WHILE.Rule = mientras + apar + EXPRE + cpar + alla + VARIOS + clla; DOWHILE.Rule = hacer + alla + VARIOS + clla + mientras + apar + EXPRE + cpar; INCREMENTA.Rule = EXPRE + mas + mas; DECREMENTA.Rule = EXPRE + menos + menos; SWITCH.Rule = switc + apar + EXPRE + cpar + alla + CASOS + clla; CASOS.Rule = MakePlusRule(CASOS, CASO); CASO.Rule = caso + EXPRE + dospts + VARIOS + brea + pyc | defaul + dospts + VARIOS; FOR.Rule = para + apar + DECLARACIONES + pyc + EXPRE + pyc + EXPRE + cpar + alla + VARIOS + clla; COMPARTO.Rule = id + pto + comparador + apar + EXPRE + cpar; /* --------------------------------------------------------------------------------------- * * OPERACIONES ARITMETICAS Y RELACIONALES * * --------------------------------------------------------------------------------------- */ EXPRE.Rule = EXPRE + or + EXPRE | EXPRE + and + EXPRE | EXPRE + comparacion + EXPRE | EXPRE + diferente + EXPRE | EXPRE + mayor + EXPRE | EXPRE + mayorigual + EXPRE | EXPRE + menor + EXPRE | EXPRE + menorigual + EXPRE | EXPRE + mas + EXPRE | EXPRE + menos + EXPRE | EXPRE + multiplicacion + EXPRE | EXPRE + division + EXPRE | EXPRE + porcentaje + EXPRE | apar + EXPRE + cpar | num | menos + num | id | verdadero | falso | tstring | LLAMADA | INCREMENTA | DECREMENTA | tchar | ARREGLOS | COMPARTO | nombreUsuario; //---------------------> No Terminal Inicial this.Root = S; //---------------------> Definir Asociatividad RegisterOperators(1, Associativity.Left, or); //OR RegisterOperators(2, Associativity.Left, and); //AND RegisterOperators(3, Associativity.Left, comparacion, diferente); //IGUAL, DIFERENTE RegisterOperators(4, Associativity.Left, mayor, menor, mayorigual, menorigual); //MAYORQUES, MENORQUES RegisterOperators(5, Associativity.Left, mas, menos); //MAS, MENOS RegisterOperators(6, Associativity.Left, multiplicacion, division); //POR, DIVIDIR RegisterOperators(2, Associativity.Left, porcentaje); //POTENCIA RegisterOperators(7, Associativity.Right, "!"); //NOT //---------------------> Manejo de Errores /* SENTENCIAS.ErrorRule = SyntaxError + clla; * METODO.ErrorRule = SyntaxError + clla;*/ //CASOS.ErrorRule = SyntaxError + CASO;*/ //---------------------> Eliminacion de caracters, no terminales this.MarkPunctuation(apar, cpar, pyc, alla, clla, asignar, coma, dospts, acor, ccor, pto); // this.MarkPunctuation("print", "if", "else", "do", "while"); // this.MarkTransient(SENTENCIA); //this.MarkTransient(CASO); }
public Gramatica() : base(caseSensitive: false) { #region ER //Comentarios CommentTerminal comentlinea = new CommentTerminal("comentlinea", "//", "\n", "\r\n"); CommentTerminal comentmulti = new CommentTerminal("comentmulti", "{", "}"); CommentTerminal comentmulti2 = new CommentTerminal("comentmulti2", "(*", "*)"); //Tipos de datos primitivos NumberLiteral numero = new NumberLiteral("numero"); StringLiteral cadena = new StringLiteral("cadena", "'"); RegexBasedTerminal booleano = new RegexBasedTerminal("booleano", "true|false"); IdentifierTerminal id = new IdentifierTerminal("ID"); #endregion #region Terminales var menor = ToTerm("<"); var mayor = ToTerm(">"); var menorigual = ToTerm("<="); var mayorigual = ToTerm(">="); var igual = ToTerm("="); var desigual = ToTerm("<>"); var mas = ToTerm("+"); var menos = ToTerm("-"); var division = ToTerm("/"); var mult = ToTerm("*"); var mod = ToTerm("mod"); var pt = ToTerm("."); var ptcoma = ToTerm(";"); var parAbre = ToTerm("("); var parCierre = ToTerm(")"); var corAbre = ToTerm("["); var corCierre = ToTerm("]"); var dospt = ToTerm(":"); var asig = ToTerm(":="); var coma = ToTerm(","); //Palabras reservadas var robject = ToTerm("object"); var array = ToTerm("array"); var integer = ToTerm("integer"); var rbreak = ToTerm("break"); var rcontinue = ToTerm("continue"); var real = ToTerm("real"); var write = ToTerm("write"); var rstring = ToTerm("string"); var rboolean = ToTerm("boolean"); var writeln = ToTerm("writeln"); var and = ToTerm("and"); var or = ToTerm("or"); var not = ToTerm("not"); var type = ToTerm("type"); var rvar = ToTerm("var"); var begin = ToTerm("begin"); var end = ToTerm("end"); var rif = ToTerm("if"); var then = ToTerm("then"); var relse = ToTerm("else"); var rcase = ToTerm("case"); var of = ToTerm("of"); var rwhile = ToTerm("while"); var repeat = ToTerm("repeat"); var until = ToTerm("until"); var rfor = ToTerm("for"); var rdo = ToTerm("do"); var to = ToTerm("to"); var downto = ToTerm("downto"); var program = ToTerm("program"); var exit = ToTerm("exit"); var rconst = ToTerm("const"); var procedure = ToTerm("procedure"); var function = ToTerm("function"); var graficar = ToTerm("graficar_ts"); RegisterOperators(1, igual, desigual, mayor, menor, mayorigual, menorigual); RegisterOperators(2, mas, menos, or); RegisterOperators(3, mult, division, mod, and); RegisterOperators(4, Associativity.Right, not); NonGrammarTerminals.Add(comentlinea); NonGrammarTerminals.Add(comentmulti); NonGrammarTerminals.Add(comentmulti2); #endregion #region No Terminales NonTerminal S = new NonTerminal("S"), P = new NonTerminal("P"), L_AC = new NonTerminal("L_AC"), AC = new NonTerminal("AC"), L_CNT = new NonTerminal("L_CNT"), L_PROF = new NonTerminal("L_PROF"), MAIN = new NonTerminal("MAIN"), G_CNT = new NonTerminal("G_CNT"), G_TY = new NonTerminal("G_TY"), DECLAS = new NonTerminal("DECLAS"), L_TY = new NonTerminal("L_TY"), L_VR = new NonTerminal("L_VR"), CNT = new NonTerminal("CNT"), TY = new NonTerminal("TY"), VR = new NonTerminal("VR"), TYP = new NonTerminal("TYP"), OBJ = new NonTerminal("OBJ"), ARY = new NonTerminal("ARY"), L_DIM = new NonTerminal("L_DIM"), DIM = new NonTerminal("DIM"), L_DEF = new NonTerminal("L_DEF"), ASIG = new NonTerminal("ASIG"), ASID = new NonTerminal("ASID"), L_ID = new NonTerminal("L_ID"), TIPO = new NonTerminal("TIPO"), ZTIPO = new NonTerminal("ZTIPO"), PROF = new NonTerminal("PROF"), DEF = new NonTerminal("DEF"), PRO = new NonTerminal("PRO"), BEG = new NonTerminal("BEG"), L_PARAM = new NonTerminal("L_PARAM"), PARAM = new NonTerminal("PARAM"), FUN = new NonTerminal("FUN"), SPACE = new NonTerminal("SPACE"), L_EXP = new NonTerminal("L_EXP"), CALL = new NonTerminal("CALL"), EXPLOG = new NonTerminal("EXPLOG"), EXPRELA = new NonTerminal("EXPRELA"), EXPNUMERICA = new NonTerminal("EXPNUMERICA"), L_SENCU = new NonTerminal("L_SENCU"), SENCU = new NonTerminal("SENCU"), SEN = new NonTerminal("SEN"), COT = new NonTerminal("COT"), BRK = new NonTerminal("BRK"), IF = new NonTerminal("IF"), ELSE = new NonTerminal("ELSE"), L_SEN = new NonTerminal("L_SEN"), FAD = new NonTerminal("FAD"), CASE = new NonTerminal("CASE"), L_OPC = new NonTerminal("L_OPC"), LETC = new NonTerminal("LETC"), OPC = new NonTerminal("OPC"), ETC = new NonTerminal("ETC"), REP = new NonTerminal("REP"), WH = new NonTerminal("WH"), FOR = new NonTerminal("FOR"), WRT = new NonTerminal("WRT"), EXT = new NonTerminal("EXT"), GTS = new NonTerminal("GTS"), PC = new NonTerminal("PC"), L_AT = new NonTerminal("L_AT"), AT = new NonTerminal("AT"), ACCESS = new NonTerminal("ACCESS"), ACCID = new NonTerminal("ACCID"); #endregion #region Gramatica S.Rule = P; P.Rule = program + id + ptcoma + L_AC + MAIN | program + id + ptcoma + MAIN; P.ErrorRule = SyntaxError + ptcoma; //ERROR: Por si viniera un error ahí, ya no es para ejecutar recuerda L_AC.Rule = MakePlusRule(L_AC, AC); AC.Rule = G_CNT | G_TY | DECLAS | L_PROF; AC.ErrorRule = SyntaxError + ptcoma; //ERROR: por si no se recupero anteriormente G_CNT.Rule = rconst + L_CNT; L_CNT.Rule = MakePlusRule(L_CNT, CNT); CNT.Rule = id + igual + EXPLOG + ptcoma; CNT.ErrorRule = SyntaxError + ptcoma; //ERROR L_PROF.Rule = MakePlusRule(L_PROF, PROF); G_TY.Rule = type + L_TY; DECLAS.Rule = rvar + L_VR; L_TY.Rule = MakePlusRule(L_TY, TY); L_VR.Rule = MakePlusRule(L_VR, VR); TY.Rule = id + igual + TYP + ptcoma; TY.ErrorRule = SyntaxError + ptcoma; //ERROR VR.Rule = L_ID + dospt + ZTIPO + ptcoma | L_ID + dospt + ZTIPO + igual + EXPLOG + ptcoma; VR.ErrorRule = SyntaxError + ptcoma; //ERROR L_ID.Rule = MakePlusRule(L_ID, coma, id); TYP.Rule = OBJ | ARY; OBJ.Rule = robject + rvar + L_AT + end; L_AT.Rule = MakePlusRule(L_AT, AT); AT.Rule = L_ID + dospt + ZTIPO + ptcoma; ARY.Rule = array + corAbre + L_DIM + corCierre + of + ZTIPO; L_DIM.Rule = MakePlusRule(L_DIM, coma, DIM); DIM.Rule = numero + pt + pt + numero; MAIN.Rule = begin + L_SEN + end + pt; L_DEF.Rule = MakePlusRule(L_DEF, DEF); ASIG.Rule = ASID + asig + EXPLOG + PC; ASID.Rule = ASID + pt + id | id; TIPO.Rule = integer | rstring | rboolean | real; ZTIPO.Rule = TIPO | id; PROF.Rule = PRO | FUN; DEF.Rule = DECLAS | L_PROF; PRO.Rule = procedure + id + parAbre + L_PARAM + parCierre + ptcoma + SPACE | procedure + id + parAbre + parCierre + ptcoma + SPACE | procedure + id + ptcoma + SPACE; BEG.Rule = begin + L_SEN + end + PC; L_PARAM.Rule = MakePlusRule(L_PARAM, ptcoma, PARAM); PARAM.Rule = rvar + L_ID + dospt + ZTIPO | L_ID + dospt + ZTIPO; FUN.Rule = function + id + parAbre + L_PARAM + parCierre + dospt + ZTIPO + ptcoma + SPACE | function + id + parAbre + parCierre + dospt + ZTIPO + ptcoma + SPACE | function + id + dospt + ZTIPO + ptcoma + SPACE; SPACE.Rule = L_DEF + BEG | BEG; L_EXP.Rule = MakePlusRule(L_EXP, coma, EXPLOG); CALL.Rule = id + parAbre + L_EXP + parCierre + PC | id + parAbre + parCierre + PC; EXPLOG.Rule = EXPLOG + and + EXPLOG | EXPLOG + or + EXPLOG | not + EXPLOG //UNARIO | parAbre + EXPLOG + parCierre | EXPRELA; EXPRELA.Rule = EXPRELA + mayor + EXPRELA | EXPRELA + menor + EXPRELA | EXPRELA + mayorigual + EXPRELA | EXPRELA + menorigual + EXPRELA | EXPRELA + igual + EXPRELA | EXPRELA + desigual + EXPRELA | parAbre + EXPRELA + parCierre | booleano | EXPNUMERICA; EXPNUMERICA.Rule = EXPNUMERICA + mas + EXPNUMERICA | EXPNUMERICA + menos + EXPNUMERICA | EXPNUMERICA + mult + EXPNUMERICA | EXPNUMERICA + division + EXPNUMERICA | EXPNUMERICA + mod + EXPNUMERICA | parAbre + EXPNUMERICA + parCierre | menos + EXPNUMERICA //UNARIO | numero | cadena | ACCESS; ACCESS.Rule = ACCID | CALL; ACCID.Rule = ACCID + pt + id | id; L_SENCU.Rule = MakePlusRule(L_SENCU, SENCU); SENCU.Rule = SEN | BEG; SEN.Rule = ASIG | IF | CASE | WH | REP | FOR | BRK | COT | WRT | EXT | GTS | CALL; SEN.ErrorRule = SyntaxError + ptcoma | SyntaxError + end; //ERROR COT.Rule = rcontinue + PC; BRK.Rule = rbreak + PC; IF.Rule = rif + EXPLOG + then + SEN | rif + EXPLOG + then + SEN + ELSE | rif + EXPLOG + then + BEG | rif + EXPLOG + then + begin + L_SEN + end + ELSE; L_SEN.Rule = MakePlusRule(L_SEN, SEN); ELSE.Rule = relse + SEN | relse + BEG; FAD.Rule = to | downto; CASE.Rule = rcase + parAbre + id + parCierre + of + L_OPC + end + ptcoma | rcase + parAbre + id + parCierre + of + L_OPC + ELSE + end + ptcoma | rcase + id + of + L_OPC + end + ptcoma | rcase + id + of + L_OPC + ELSE + end + ptcoma; L_OPC.Rule = MakePlusRule(L_OPC, OPC); LETC.Rule = MakePlusRule(LETC, coma, ETC); OPC.Rule = LETC + dospt + SENCU; ETC.Rule = menos + numero | numero //con negativo | booleano | cadena; REP.Rule = repeat + L_SENCU + until + EXPLOG + PC; WH.Rule = rwhile + EXPLOG + rdo + SENCU; FOR.Rule = rfor + id + asig + EXPNUMERICA + FAD + EXPNUMERICA + rdo + SENCU; WRT.Rule = writeln + parAbre + L_EXP + parCierre + PC | write + parAbre + L_EXP + parCierre + PC; EXT.Rule = exit + parAbre + EXPLOG + parCierre + PC | exit + parAbre + parCierre + PC; GTS.Rule = graficar + parAbre + parCierre + PC; PC.Rule = ptcoma | Empty; #endregion #region Preferencias this.Root = S; #endregion }
public XSharpGrammar() { #region Terminals var number = new NumberLiteral("number") { DefaultIntTypes = new[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt } }; var str = new StringLiteral("str", "\""); var entityCollection = new IdentifierTerminal("entityCollection"); var entityName = new IdentifierTerminal("entityName"); var attribute = new IdentifierTerminal("attribute"); var guid = new StringLiteral("guid", "\""); var fetchXml = new StringLiteral("fetchXml", "|", StringOptions.AllowsLineBreak); var comment = new CommentTerminal("comment", "#", "\r", "\n"); NonGrammarTerminals.Add(comment); #endregion Terminals #region Non-terminals // ReSharper disable InconsistentNaming var Program = new NonTerminal("Program"); var StatementList = new NonTerminal("StatementList"); var StatementLine = new NonTerminal("StatementLine"); var Statement = new NonTerminal("Statement"); var CommandStatement = new NonTerminal("CommandStatement"); var UnaryCommand = new NonTerminal("UnaryCommand"); var BinaryCommand = new NonTerminal("BinaryCommand"); var AssignStatement = new NonTerminal("AssignStatement"); var QueryStatement = new NonTerminal("QueryStatement"); var OrdinalOperator = new NonTerminal("OrdinalOperator", "operator"); var FilterStatementList = new NonTerminal("FilterStatementList"); var FilterStatement = new NonTerminal("FilterStatement"); var FilterOperator = new NonTerminal("FilterOperator"); var FilterExpression = new NonTerminal("FilterExpression"); var CreateStatement = new NonTerminal("CreateStatement"); var CreateAndInitializeStatement = new NonTerminal("CreateAndInitializeStatement"); var ChangeStatement = new NonTerminal("ChangeStatement"); var SetStatementList = new NonTerminal("SetStatementList"); var SetStatement = new NonTerminal("SetStatement"); var ValueExpression = new NonTerminal("ValueExpression"); var BinaryOperator = new NonTerminal("BinaryOperator", "operator"); // ReSharper restore InconsistentNaming #endregion Non-terminals #region BNF rules Program.Rule = StatementList; StatementList.Rule = MakeStarRule(StatementList, StatementLine); StatementLine.Rule = Statement + NewLine | NewLine; Statement.Rule = ChangeStatement | AssignStatement | CommandStatement; ChangeStatement.Rule = "change" + entityCollection + "{" + NewLine + SetStatementList + "}"; CommandStatement.Rule = UnaryCommand + entityCollection | BinaryCommand + entityCollection + ToTerm("to") + entityCollection; AssignStatement.Rule = entityCollection + "<-" + QueryStatement | entityCollection + "<-" + CreateStatement | entityCollection + "<-" + CreateAndInitializeStatement; UnaryCommand.Rule = ToTerm("create") | "update" | "delete"; BinaryCommand.Rule = ToTerm("assign") | "merge"; QueryStatement.Rule = "find" + OrdinalOperator + entityName + "where" + FilterStatementList | "find" + OrdinalOperator + entityName + "called" + guid | fetchXml; OrdinalOperator.Rule = ToTerm("all") | "one"; FilterStatementList.Rule = MakeStarRule(FilterStatementList, FilterStatement); FilterStatement.Rule = FilterExpression | FilterExpression + FilterOperator; FilterOperator.Rule = ToTerm("and") | "or"; FilterExpression.Rule = attribute + BinaryOperator + ValueExpression; CreateStatement.Rule = "new" + entityName; CreateAndInitializeStatement.Rule = "new" + entityName + "called" + guid; SetStatementList.Rule = MakeStarRule(SetStatementList, SetStatement); SetStatement.Rule = "set" + attribute + "to" + ValueExpression + NewLine; BinaryOperator.Rule = ToTerm("=") | "!=" | "<" | ">" | "<=" | ">="; ValueExpression.Rule = str | number; Root = Program; #endregion #region Operators RegisterOperators(1, "and", "or"); #endregion Operators #region Punctuation and Transient Terms MarkPunctuation("{", "}"); MarkTransient(StatementLine, BinaryOperator, OrdinalOperator, FilterOperator, ValueExpression); LanguageFlags = LanguageFlags.NewLineBeforeEOF | LanguageFlags.CreateAst; #endregion Punctuation and Transient Terms }
public Grammar_Trad() : base(caseSensitive: false) { #region Lexical structure //COMENTARIOS CommentTerminal LINE_COMMENT = new CommentTerminal("LINE_COMMENT", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal MULTI_LINE_COMMENT = new CommentTerminal("MULTI_LINE_COMMENT", "(*", "*)"); CommentTerminal MULTI_LINE_COMMENT_LLAVE = new CommentTerminal("MULTI_LINE_COMMENT_LLAVE", "{", "}"); NonGrammarTerminals.Add(LINE_COMMENT); NonGrammarTerminals.Add(MULTI_LINE_COMMENT); NonGrammarTerminals.Add(MULTI_LINE_COMMENT_LLAVE); #endregion #region ER var REAL = new RegexBasedTerminal("REAL", "[0-9]+[.][0-9]+"); var NUMERO = new NumberLiteral("NUMERO"); //var IDENTIFIER = new IdentifierTerminal("IDENTIFIER", "[_a-zA-Z][_a-zA-Z0-9]"); var IDENTIFIER = TerminalFactory.CreateCSharpIdentifier("IDENTIFIER"); var CADENA = new StringLiteral("CADENA", "\'"); #endregion #region Terminales var PUNTO_COMA = ToTerm(";", "TK_PUNTO_COMA"); var PUNTO = ToTerm(".", "TK_PUNTO"); var COMA = ToTerm(",", "TK_COMA"); var DOS_PUNTOS = ToTerm(":", "TK_DOS_PUNTOS"); var PAR_IZQ = ToTerm("(", "TK_PAR_IZQ"); var PAR_DER = ToTerm(")", "TK_PAR_DER"); var COR_IZQ = ToTerm("[", "TK_COR_IZQ"); var COR_DER = ToTerm("]", "TK_COR_DER"); //Aritmethic var PLUS = ToTerm("+", "TK_PLUS"); var MIN = ToTerm("-", "TK_MIN"); var POR = ToTerm("*", "TK_POR"); var DIVI = ToTerm("/", "TK_DIVI"); var MODULE = ToTerm("%", "TK_MODULE"); //Logic var AND = ToTerm("and", "TK_AND"); var OR = ToTerm("or", "TK_OR"); var NOT = ToTerm("not", "TK_NOT"); //Relational var HIGHER = ToTerm(">", "TK_HIGHER"); var LESS = ToTerm("<", "TK_LESS"); var HIGHER_EQUAL = ToTerm(">=", "TK_HIGHER_EQUAL"); var LESS_EQUAL = ToTerm("<=", "TK_LESS_EQUAL"); var EQUALS = ToTerm("=", "TK_EQUALS"); var DISCTINCT = ToTerm("<>", "TK_DISCTINCT"); //Reservadas var RESERV_INT = ToTerm("integer", "RESERV_INT"); var RESERV_STR = ToTerm("string", "RESERV_STR"); var RESERV_REAL = ToTerm("real", "RESERV_REAL"); var RESERV_BOL = ToTerm("boolean", "RESERV_BOL"); var RESERV_VOID = ToTerm("void", "RESERV_VOID"); var RESERV_TYPE = ToTerm("type", "RESERV_TYPE"); var RESERV_OBJ = ToTerm("object", "RESERV_OBJ"); var RESERV_PROGRAM = ToTerm("program", "RESERV_PROGRAM"); var RESERV_VAR = ToTerm("var", "RESERV_VAR"); var RESERV_BEGIN = ToTerm("begin", "RESERV_BEGIN"); var RESERV_END = ToTerm("end", "RESERV_END"); var RESERV_CONST = ToTerm("const", "RESERV_CONST"); var RESERV_TRUE = ToTerm("true", "RESERV_TRUE"); var RESERV_FALSE = ToTerm("false", "RESERV_FALSE"); var RESERV_ARRAY = ToTerm("array", "RESERV_ARRAY"); var RESERV_OF = ToTerm("of", "RESERV_OF"); #region IF TERMINALES var RESERV_IF = ToTerm("if", "RESERV_IF"); var RESERV_THEN = ToTerm("then", "RESERV_THEN"); var RESERV_ELSE = ToTerm("else", "RESERV_ELSE"); #endregion #region CASE TERMINALES var RESERV_CASE = ToTerm("case", "RESERV_CASE"); #endregion #region WHILE TERMINALES var RESERV_WHILE = ToTerm("while", "RESERV_WHILE"); var RESERV_DO = ToTerm("do", "RESERV_DO"); #endregion #region REPEAT TERMINALES var RESERV_REPEAT = ToTerm("repeat", "RESERV_REPEAT"); var RESERV_UNTIL = ToTerm("until", "RESERV_UNTIL"); #endregion #region FOR TERMINALES var RESERV_FOR = ToTerm("for", "RESERV_FOR"); var RESERV_TO = ToTerm("to", "RESERV_TO"); var RESERV_DOWN = ToTerm("downto", "RESERV_DOWN"); var RESERV_BREAK = ToTerm("break", "RESERV_BREAK"); var RESERV_CONTINUE = ToTerm("continue", "RESERV_CONTINUE"); #endregion #region FUNCTION Y PROCEDURE TERMINALES var RESERV_FUNCTION = ToTerm("function", "RESERV_FUNCTION"); var RESERV_PROCEDURE = ToTerm("procedure", "RESERV_PROCEDURE"); #endregion #region FUNCIONES NATIVAS TERMINALES var RESERV_WRITE = ToTerm("write", "RESERV_WRITE"); var RESERV_WRITEN = ToTerm("writeln", "RESERV_WRITEN"); var RESERV_EXIT = ToTerm("exit", "RESERV_EXIT"); var RESERV_GRAF = ToTerm("graficar_ts", "RESERV_GRAFICAR"); #endregion RegisterOperators(1, Associativity.Left, PLUS, MIN); RegisterOperators(2, Associativity.Left, POR, DIVI); RegisterOperators(3, Associativity.Left, MODULE); RegisterOperators(4, Associativity.Left, HIGHER_EQUAL, LESS_EQUAL, LESS, HIGHER); RegisterOperators(5, Associativity.Left, EQUALS, DISCTINCT); RegisterOperators(6, Associativity.Left, AND, OR, NOT); RegisterOperators(7, Associativity.Left, PAR_IZQ, PAR_DER); #endregion #region No Terminales NonTerminal init = new NonTerminal("init"); NonTerminal INSTRUCTION = new NonTerminal("INSTRUCTION"); NonTerminal INSTRUCTIONS = new NonTerminal("INSTRUCTIONS"); NonTerminal INSTRUCTIONS_BODY = new NonTerminal("INSTRUCTIONS_BODY"); NonTerminal PROGRAM_BODY = new NonTerminal("PROGRAM_BODY", "PROGRAM_BODY"); NonTerminal start = new NonTerminal("start"); #region EXPRESION NonTerminal EXPRESION = new NonTerminal("EXPRESION", "EXPRESION"); NonTerminal DATA_TYPE = new NonTerminal("DATA_TYPE", "DATA_TYPE"); #endregion #region VAR Y CONST NonTerminal DECLARATION_LIST = new NonTerminal("DECLARATION_LIST", "DECLARATION_LIST"); NonTerminal VAR_DECLARATION = new NonTerminal("VAR_DECLARATION", "VAR_DECLARATION"); NonTerminal CONST_DECLARATION = new NonTerminal("CONST_DECLARATION", "CONST_DECLARATION"); NonTerminal DECLARATION = new NonTerminal("DECLARATION", "DECLARATION"); NonTerminal DECLARATION_BODY = new NonTerminal("DECLARATION_BODY", "DECLARATION_BODY"); NonTerminal MORE_ID = new NonTerminal("MORE_ID", "MORE_ID"); NonTerminal ASSIGNATION = new NonTerminal("ASSIGNATION", "ASSIGNATION"); NonTerminal VAR_ASSIGNATE = new NonTerminal("VAR_ASSIGNATE", "VAR_ASSIGNATE"); #endregion //NO ESTAN TERMINADOS #region ARRAY Y TYPES NO TERMINADO NonTerminal TYPE = new NonTerminal("TYPE", "TYPE"); NonTerminal TYPE_P = new NonTerminal("TYPE_P", "TYPE_P"); NonTerminal ARRAY = new NonTerminal("ARRAY", "ARRAY"); NonTerminal OBJECT = new NonTerminal("OBJECT", "OBJECT"); #endregion #region IF-THEN NO TERMINALES NonTerminal IFTHEN = new NonTerminal("IF-THEN", "IF-THEN"); NonTerminal IF_SENTENCE = new NonTerminal("IF_SENTENCE", "IF_SENTENCE"); NonTerminal ELIF = new NonTerminal("ELIF", "ELIF"); #endregion #region CASE NO TERMINALES NonTerminal SENTENCE_CASE = new NonTerminal("SENTENCE_CASE", "SENTENCE_CASE"); NonTerminal CASE_ELSE = new NonTerminal("CASE_ELSE", "CASE_ELSE"); NonTerminal CASES = new NonTerminal("CASES", "CASES"); NonTerminal CASE = new NonTerminal("CASE", "CASE"); #endregion #region WHILE DO NonTerminal WHILE = new NonTerminal("WHILE", "WHILE"); #endregion #region REPEAT UNTIL NonTerminal REPEAT_UNTIL = new NonTerminal("REPEAT_UNTIL", "REPEAT_UNTIL"); NonTerminal CONTINUE = new NonTerminal("CONTINUE", "CONTINUE"); #endregion #region FOR NonTerminal FOR = new NonTerminal("FOR", "FOR"); NonTerminal TODOWN = new NonTerminal("TODOWN", "TODOWN"); NonTerminal BREAK = new NonTerminal("BREAK", "BREAK"); #endregion #region FUNCIONES NATIVAS NO TERMINALES NonTerminal WRITE = new NonTerminal("WRITE", "WRITE"); NonTerminal WRHITE_PARAMETER = new NonTerminal("WRHITE_PARAMETER", "WRHITE_PARAMETER"); NonTerminal MORE_WRHITE_PARAMETER = new NonTerminal("WRHITE_PARAMETER", "WRHITE_PARAMETER"); NonTerminal EXIT = new NonTerminal("EXIT", "EXIT"); #endregion #region FUNCIONS NO TERMINALES NonTerminal FUNCTION_LIST = new NonTerminal("FUNCTION_LIST", "FUNCTION_LIST"); NonTerminal FUNCTION = new NonTerminal("FUNCTION", "FUNCTION"); NonTerminal PROCEDURE = new NonTerminal("PROCEDURE", "PROCEDURE"); NonTerminal PARAMETER = new NonTerminal("PARAMETER", "PARAMETER"); NonTerminal PARAMETER_BODY = new NonTerminal("PARAMETER_BODY", "PARAMETER_BODY"); NonTerminal PARAMETER_END = new NonTerminal("PARAMETER_END", "PARAMETER_END"); NonTerminal CALL = new NonTerminal("CALL", "CALL"); NonTerminal CALL_FUNCTION_PROCEDURE = new NonTerminal("CALL_FUNCTION_PROCEDURE", "CALL_FUNCTION_PROCEDURE"); NonTerminal CALL_PARAMETERS = new NonTerminal("CALL_PARAMETERS", "CALL_PARAMETERS"); NonTerminal FUNCION_HIJA = new NonTerminal("FUNCION_HIJA", "FUNCION_HIJA"); NonTerminal DECLARATION_LIST_HIJA = new NonTerminal("DECLARATION_LIST", "DECLARATION_LIST"); //NonTerminal ARGUMENTS = new NonTerminal("ARGUMENTS", "ARGUMENTS"); //NonTerminal REFERENCIA_VALOR = new NonTerminal("REFERENCIA_VALOR", "REFERENCIA_VALOR"); #endregion #endregion #region Gramatica init.Rule = start; start.Rule = RESERV_PROGRAM + IDENTIFIER + PUNTO_COMA + PROGRAM_BODY; PROGRAM_BODY.Rule = DECLARATION_LIST + FUNCTION_LIST + INSTRUCTIONS_BODY + PUNTO; INSTRUCTIONS_BODY.Rule = RESERV_BEGIN + INSTRUCTIONS + RESERV_END ; INSTRUCTIONS.Rule = MakePlusRule(INSTRUCTIONS, INSTRUCTION); INSTRUCTION.Rule = VAR_ASSIGNATE | IFTHEN | SENTENCE_CASE | WHILE | REPEAT_UNTIL | FOR | BREAK | CONTINUE | WRITE | CALL | EXIT ; INSTRUCTION.ErrorRule = SyntaxError + PUNTO_COMA | SyntaxError + RESERV_END ; #region DECLARACION & ASIGNACION DECLARATION_LIST.Rule = RESERV_VAR + IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION + DECLARATION_LIST | RESERV_CONST + IDENTIFIER + EQUALS + EXPRESION + PUNTO_COMA + CONST_DECLARATION + DECLARATION_LIST | Empty ; DECLARATION_LIST.ErrorRule = SyntaxError + PUNTO_COMA; VAR_DECLARATION.Rule = IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION | Empty ; CONST_DECLARATION.Rule = IDENTIFIER + EQUALS + EXPRESION + PUNTO_COMA + CONST_DECLARATION | Empty ; DECLARATION_BODY.Rule = DOS_PUNTOS + DATA_TYPE + ASSIGNATION + PUNTO_COMA | COMA + IDENTIFIER + MORE_ID + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA ; ASSIGNATION.Rule = EQUALS + EXPRESION | Empty; ; MORE_ID.Rule = COMA + IDENTIFIER + MORE_ID | Empty ; VAR_ASSIGNATE.Rule = IDENTIFIER + DOS_PUNTOS + EQUALS + EXPRESION + PUNTO_COMA; DATA_TYPE.Rule = RESERV_REAL | RESERV_STR | RESERV_TYPE | RESERV_INT | RESERV_BOL | IDENTIFIER ; #endregion #region TYPES Y ARRAY TYPE.Rule = RESERV_TYPE + IDENTIFIER + EQUALS + TYPE_P; TYPE_P.Rule = OBJECT | ARRAY ; OBJECT.Rule = RESERV_OBJ + DECLARATION + RESERV_END; ARRAY.Rule = RESERV_ARRAY + COR_IZQ + EXPRESION + COR_DER + PUNTO + PUNTO + EXPRESION + PAR_DER + RESERV_OF + DATA_TYPE; #endregion #region EXPRESSION EXPRESION.Rule = EXPRESION + PLUS + EXPRESION | EXPRESION + MIN + EXPRESION | EXPRESION + POR + EXPRESION | EXPRESION + DIVI + EXPRESION | EXPRESION + MODULE + EXPRESION | EXPRESION + LESS + EXPRESION | EXPRESION + HIGHER + EXPRESION | EXPRESION + LESS_EQUAL + EXPRESION | EXPRESION + HIGHER_EQUAL + EXPRESION | EXPRESION + EQUALS + EXPRESION | EXPRESION + DISCTINCT + EXPRESION | EXPRESION + AND + EXPRESION | EXPRESION + OR + EXPRESION //| MIN + EXPRESION | NOT + EXPRESION | CALL_FUNCTION_PROCEDURE | IDENTIFIER | NUMERO | CADENA | REAL | RESERV_TRUE | RESERV_FALSE | PAR_IZQ + EXPRESION + PAR_DER ; #endregion #endregion #region SENTENCIAS DE CONTROL #region IF-THEN IFTHEN.Rule = RESERV_IF + EXPRESION + RESERV_THEN + IF_SENTENCE + ELIF; IF_SENTENCE.Rule = INSTRUCTIONS_BODY | Empty ; ELIF.Rule = RESERV_ELSE + IF_SENTENCE + PUNTO_COMA | RESERV_ELSE + IFTHEN | Empty ; #endregion #region CASE SENTENCE_CASE.Rule = RESERV_CASE + EXPRESION + RESERV_OF + CASES + CASE_ELSE + RESERV_END + PUNTO_COMA; CASES.Rule = MakePlusRule(CASES, CASE) | CASE ; CASE.Rule = EXPRESION + DOS_PUNTOS + INSTRUCTIONS; CASE_ELSE.Rule = RESERV_ELSE + INSTRUCTIONS | Empty ; #endregion #region WHILE DO WHILE.Rule = RESERV_WHILE + EXPRESION + RESERV_DO + INSTRUCTIONS_BODY + PUNTO_COMA; #endregion #region REPEAT UNTIL REPEAT_UNTIL.Rule = RESERV_REPEAT + INSTRUCTIONS + RESERV_UNTIL + EXPRESION + PUNTO_COMA; #endregion #region FOR FOR.Rule = RESERV_FOR + IDENTIFIER + DOS_PUNTOS + EQUALS + EXPRESION + TODOWN + EXPRESION + RESERV_DO + INSTRUCTIONS_BODY + PUNTO_COMA ; TODOWN.Rule = RESERV_TO | RESERV_DOWN ; #endregion #endregion #region SENTENCIAS DE TRANSFERENCIA CONTINUE.Rule = RESERV_CONTINUE + PUNTO_COMA ; BREAK.Rule = RESERV_BREAK + PUNTO_COMA ; #endregion #region FUNCIONES Y PROCEDIMIENTOS FUNCTION_LIST.Rule = RESERV_FUNCTION + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA + DECLARATION_LIST_HIJA + FUNCION_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCTION_LIST | RESERV_PROCEDURE + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + PUNTO_COMA + DECLARATION_LIST_HIJA + FUNCION_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCTION_LIST | Empty ; FUNCTION_LIST.ErrorRule = SyntaxError + PUNTO_COMA; PARAMETER.Rule = RESERV_VAR + IDENTIFIER + PARAMETER_BODY + DOS_PUNTOS + DATA_TYPE + PARAMETER_END | IDENTIFIER + PARAMETER_BODY + DOS_PUNTOS + DATA_TYPE + PARAMETER_END | Empty; PARAMETER_BODY.Rule = COMA + IDENTIFIER + PARAMETER_BODY | Empty ; PARAMETER_END.Rule = PUNTO_COMA + PARAMETER | Empty ; CALL.Rule = IDENTIFIER + PAR_IZQ + CALL_PARAMETERS + PAR_DER + PUNTO_COMA; CALL_PARAMETERS.Rule = EXPRESION + CALL_PARAMETERS | COMA + EXPRESION + CALL_PARAMETERS | Empty ; CALL_FUNCTION_PROCEDURE.Rule = IDENTIFIER + PAR_IZQ + CALL_PARAMETERS + PAR_DER; FUNCTION.Rule = RESERV_FUNCTION + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA + INSTRUCTIONS_BODY + PUNTO_COMA ; PROCEDURE.Rule = RESERV_PROCEDURE + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + PUNTO_COMA + INSTRUCTIONS_BODY + PUNTO_COMA ; FUNCION_HIJA.Rule = RESERV_FUNCTION + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA + DECLARATION_LIST_HIJA + FUNCION_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCION_HIJA | RESERV_PROCEDURE + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + PUNTO_COMA + DECLARATION_LIST_HIJA + FUNCION_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCION_HIJA | Empty ; DECLARATION_LIST_HIJA.Rule = RESERV_VAR + IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION + DECLARATION_LIST_HIJA | RESERV_CONST + IDENTIFIER + EQUALS + EXPRESION + PUNTO_COMA + CONST_DECLARATION + DECLARATION_LIST_HIJA | Empty ; #endregion #region FUNCIONES NATIVAS WRITE.Rule = RESERV_WRITE + PAR_IZQ + WRHITE_PARAMETER + PAR_DER + PUNTO_COMA | RESERV_WRITEN + PAR_IZQ + WRHITE_PARAMETER + PAR_DER + PUNTO_COMA ; WRHITE_PARAMETER.Rule = EXPRESION + MORE_WRHITE_PARAMETER | Empty ; MORE_WRHITE_PARAMETER.Rule = COMA + EXPRESION + MORE_WRHITE_PARAMETER | Empty ; EXIT.Rule = RESERV_EXIT + PAR_IZQ + EXPRESION + PAR_DER + PUNTO_COMA; #endregion #region Preferencias this.Root = init; #endregion }
public ResedaGrammar() { var str = new StringLiteral("string", "\'"); var number = new NumberLiteral("number"); number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; var identifier = new IdentifierTerminal("identifier"); var comment = new CommentTerminal("comment", "#", "\n", "\r"); base.NonGrammarTerminals.Add(comment); var Process = new NonTerminal("Process"); var SubProcess = new NonTerminal("SubProcess"); var SubProcess_opt = new NonTerminal("SubProcess_opt"); var StructuredData = new NonTerminal("StructuredData"); var Relations = new NonTerminal("Relations"); var RelationsOpt = new NonTerminal("RelationsOpt"); var Relation = new NonTerminal("Relation"); var Include = new NonTerminal("Include"); var Exclude = new NonTerminal("Exclude"); var Response = new NonTerminal("Response"); var Condition = new NonTerminal("Condition"); var Milestone = new NonTerminal("Milestone"); var Spawn = new NonTerminal("Spawn"); var SpawnIterator = new NonTerminal("SpawnIterator"); var Event = new NonTerminal("Event"); var InputEvent = new NonTerminal("InputEvent"); var TypedInputEvent = new NonTerminal("TypedInputEvent"); var OutputEvent = new NonTerminal("OutputEvent"); var InputEventP = new NonTerminal("InputEventP"); var OutputEventP = new NonTerminal("OutputEventP"); var Expression = new NonTerminal("Expression"); var Path = new NonTerminal("Path"); var PathRoot = new NonTerminal("PathRoot"); var PathExpression = new NonTerminal("PathExpression"); var PathExpressionCont = new NonTerminal("PathExpressionCont"); var PathName = new NonTerminal("PathName"); var PathLocal = new NonTerminal("PathLocal"); var PathParent = new NonTerminal("PathParent"); var PathAll = new NonTerminal("PathAll"); var Filter = new NonTerminal("Filter"); Filter.Rule = (ToTerm("[") + Expression + ToTerm("]")) | Empty; PathName.Rule = identifier + Filter + PathExpressionCont; PathLocal.Rule = ToTerm(".") + Filter + PathExpressionCont; PathParent.Rule = ToTerm("..") + Filter + PathExpressionCont; PathAll.Rule = ToTerm("*") + Filter + PathExpressionCont; PathExpressionCont.Rule = (ToTerm("/") + PathExpression) | Empty; PathExpression.Rule = PathName | PathLocal | PathParent | PathAll; PathRoot.Rule = ToTerm("/") + PathExpression; Path.Rule = PathExpression | PathRoot; var Term = new NonTerminal("Term"); var ParExpr = new NonTerminal("ParExpr"); var NegOp = new NonTerminal("NegOp"); var BinExpr = new NonTerminal("BinExpr"); var BinExpr2 = new NonTerminal("BinExpr2"); var BinOp = new NonTerminal("BinOp"); //var Unit = new KeyTerm("", "Unit"); var Unit = new NonTerminal("Unit"); var Const = new NonTerminal("Const"); var PlusOp = new NonTerminal("PlusOp"); var MinOp = new NonTerminal("MinOp"); var TimesOp = new NonTerminal("TimesOp"); var DivOp = new NonTerminal("DivOp"); var DPath = new NonTerminal("DPath"); var DPathValue = new NonTerminal("DPathValue"); var DPathIncluded = new NonTerminal("DPathIncluded"); var DPathExecuted = new NonTerminal("DPathExecuted"); var DPathPending = new NonTerminal("DPathPending"); var DDPath = new NonTerminal("DDPath"); var RelExpr = new NonTerminal("RelExpr"); var BoolExpr = new NonTerminal("BoolExpr"); var AndOp = new NonTerminal("AndOp"); var OrOp = new NonTerminal("OrOp"); var EqOp = new NonTerminal("EqOp"); var GtOp = new NonTerminal("GtOp"); var InitialValue = new NonTerminal("InitialValue"); var InitialValueC = new NonTerminal("InitialValueC"); //var Trigger = new NonTerminal("Trigger"); var Marking = new NonTerminal("Marking"); var Executed = new NonTerminal("Executed"); var ExecutedPending = new NonTerminal("ExecutedPending"); var ExecutedExcluded = new NonTerminal("ExecutedExcluded"); var ExecutedPendingExcluded = new NonTerminal("ExecutedPendingExcluded"); var Pending = new NonTerminal("Pending"); var Excluded = new NonTerminal("Excluded"); var PendingExcluded = new NonTerminal("PendingExcluded"); var Function0Args = new NonTerminal("Function0Args"); var Function1Args = new NonTerminal("Function1Args"); DDPath.Rule = DPathValue | DPathIncluded | DPathExecuted | DPathPending | DPath; DPathValue.Rule = DPath + (ToTerm(Symbols.ValueShort) | ToTerm(Symbols.Value)); DPathIncluded.Rule = DPath + (ToTerm(Symbols.IncludedShort) | ToTerm(Symbols.Included)); DPathExecuted.Rule = DPath + (ToTerm(Symbols.ExecutedShort) | ToTerm(Symbols.Executed)); DPathPending.Rule = DPath + (ToTerm(Symbols.PendingShort) | ToTerm(Symbols.Pending)); DPath.Rule = ToTerm("@") + Path; Expression.Rule = Term | BoolExpr; BoolExpr.Rule = AndOp | OrOp | RelExpr; AndOp.Rule = RelExpr + ToTerm(Symbols.And) + RelExpr; OrOp.Rule = RelExpr + ToTerm(Symbols.Or) + RelExpr; RelExpr.Rule = EqOp | GtOp | BinExpr; EqOp.Rule = BinExpr + ToTerm(Symbols.Eq) + BinExpr; GtOp.Rule = BinExpr + ToTerm(Symbols.Gt) + BinExpr; Term.Rule = Const | ParExpr | NegOp | identifier | DDPath | Function0Args | Function1Args; Const.Rule = str | number | Unit; Unit.Rule = Empty; NegOp.Rule = ToTerm("!") + Expression; ParExpr.Rule = "(" + Expression + ")"; BinExpr.Rule = PlusOp | MinOp | BinExpr2; PlusOp.Rule = BinExpr2 + ToTerm("+") + BinExpr2; MinOp.Rule = BinExpr2 + ToTerm("-") + BinExpr2; Function0Args.Rule = identifier + ToTerm("()"); Function1Args.Rule = identifier + ToTerm("(") + Expression + ToTerm(")"); //Function0Args.Rule = ToTerm("abba") + identifier + ToTerm("()"); //Function0Args.Rule = ToTerm("abba") + identifier + ToTerm("(") + Expression + ToTerm(")"); BinExpr2.Rule = TimesOp | DivOp | Expression; TimesOp.Rule = Expression + ToTerm("*") + Expression; DivOp.Rule = Expression + ToTerm("/") + Expression; Include.Rule = Path + ToTerm("-->+") + Path; Exclude.Rule = Path + ToTerm("-->%") + Path; Spawn.Rule = Path + ToTerm("-->>") + ToTerm("{") + Process + ToTerm("}"); SpawnIterator.Rule = Path + ToTerm("-(") + identifier + ToTerm("in") + Path + ToTerm(")->>") + ToTerm("{") + Process + ToTerm("}"); Condition.Rule = Path + ToTerm("-->*") + Path; Milestone.Rule = Path + ToTerm("--><>") + Path; Response.Rule = Path + ToTerm("*-->") + Path; Relation.Rule = Include | Exclude | Response | Condition | Milestone | Spawn | SpawnIterator; Relations.Rule = MakeListRule(Relations, ToTerm(","), Relation) | Empty; InputEvent.Rule = Marking + identifier + InitialValue + ToTerm("[?]") + SubProcess; TypedInputEvent.Rule = Marking + identifier + InitialValue + ToTerm("[?:") + Expression + ToTerm("]") + SubProcess; OutputEvent.Rule = Marking + identifier + InitialValue + ToTerm("[") + Expression + ToTerm("]") + SubProcess; SubProcess.Rule = (ToTerm("{") + Process + ToTerm("}")) | Empty; Event.Rule = InputEvent | OutputEvent | TypedInputEvent; StructuredData.Rule = MakeListRule(StructuredData, ToTerm(","), Event) | Empty; Process.Rule = StructuredData + RelationsOpt; RelationsOpt.Rule = ((ToTerm(";") | ToTerm("~")) + Relations) | Empty; Marking.Rule = Pending | Excluded | PendingExcluded | Executed | ExecutedPending | ExecutedExcluded | ExecutedPendingExcluded | Empty; InitialValue.Rule = (ToTerm("(") + InitialValueC + ToTerm(")")) | Empty; InitialValueC.Rule = Expression; //InitialValueC.Rule = Const | Trigger; //Trigger.Rule = ToTerm("src") + Path + (ToTerm(Symbols.ValueShort) | ToTerm(Symbols.Value)) ; Pending.Rule = ToTerm("!"); Excluded.Rule = ToTerm("%"); PendingExcluded.Rule = ToTerm("!%") | ToTerm("%!"); Executed.Rule = ToTerm("✓"); ExecutedPending.Rule = ToTerm("!✓") | ToTerm("✓!"); ExecutedExcluded.Rule = ToTerm("✓%") | ToTerm("%✓"); ExecutedPendingExcluded.Rule = ToTerm("!✓%") | ToTerm("!%✓") | ToTerm("✓!%") | ToTerm("✓%!") | ToTerm("%!✓") | ToTerm("%✓!"); this.Root = Process; this.path = Path; MarkPunctuation("-->+", ",", ";", "-->%", "-->*", "--><>", "*-->", "-->>", "<", ">", "?", "!", "{", "}", "/", ".", "..", "*", "+", "-", "(", ")", "@", "[", "]", Symbols.And, Symbols.Eq, Symbols.Gt, Symbols.Neg, Symbols.Or, "[?]", "[?:", "-(", "in", ")->>"); MarkTransient(Relation, Event, SubProcess, PathExpressionCont, PathExpression, Path, BinExpr, Expression, Term, ParExpr, BinExpr2, DDPath, BoolExpr, RelExpr, Marking, RelationsOpt, InitialValueC); }
public AssemblyGrammar() { #region Declare Terminals Here CommentTerminal blockComment = new CommentTerminal("block-comment", "/*", "*/"); CommentTerminal lineComment = new CommentTerminal("line-comment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); //CommentTerminal sharpComment = new CommentTerminal("sharp-comment","#","\r","\n","\u2085","\u2028","\u2029"); NonGrammarTerminals.Add(blockComment); NonGrammarTerminals.Add(lineComment); //NonGrammarTerminals.Add(sharpComment); StringLiteral stringLiteral = new StringLiteral("string-literal", "\""); StringLiteral charLiteral = new StringLiteral("char-literal", "\'", StringOptions.IsChar); NumberLiteral number = new NumberLiteral("number", NumberOptions.AllowSign | NumberOptions.IntOnly); number.AddPrefix("0x", NumberOptions.Hex); number.AddPrefix("0b", NumberOptions.Binary); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); #endregion #region Declare NonTerminals Here; NonTerminal fileroot = new NonTerminal("fileroot"); NonTerminal rootdefs = new NonTerminal("root-defines"); NonTerminal rootdef = new NonTerminal("root-define"); NonTerminal usingDesc = new NonTerminal("using-description"); NonTerminal memorySizeDesc = new NonTerminal("memorysize-description"); NonTerminal targetISADesc = new NonTerminal("targetisa-description"); NonTerminal label = new NonTerminal("label"); NonTerminal operandReg = new NonTerminal("operand-register"); NonTerminal operandRef = new NonTerminal("operand-reference"); NonTerminal operandImm = new NonTerminal("operand-immediate"); NonTerminal valueInt = new NonTerminal("value-integer"); NonTerminal valueChar = new NonTerminal("value-character"); NonTerminal valueRefAddr = new NonTerminal("value-referaddress"); NonTerminal labeledStatement = new NonTerminal("labeled-statement"); NonTerminal statement = new NonTerminal("statement"); NonTerminal instr = new NonTerminal("instruction"); NonTerminal instrLabels = new NonTerminal("instruction-labels"); NonTerminal instrNemonic = new NonTerminal("instruction-nemonic"); NonTerminal instrOperands = new NonTerminal("instruction-operands"); NonTerminal instrOperand = new NonTerminal("instruction-operand"); NonTerminal labeledInstrOperand = new NonTerminal("labeled-instruction-operand"); NonTerminal instrJump = new NonTerminal("instruction-jump"); NonTerminal instrJumpNemonic = new NonTerminal("instruction-jump-nemonic"); NonTerminal instrJumpTarget = new NonTerminal("instruction-jump-target"); NonTerminal macrocall = new NonTerminal("macrocall"); NonTerminal macrocallLabels = new NonTerminal("macrocall-labels"); NonTerminal macrocallName = new NonTerminal("macrocall-name"); NonTerminal macrocallOperands = new NonTerminal("macrocall-operands"); NonTerminal macrocallOperand = new NonTerminal("macrocall-operand"); NonTerminal symboldef = new NonTerminal("symboldef"); NonTerminal symboldefName = new NonTerminal("symboldef-name"); NonTerminal symboldefContent = new NonTerminal("symboldef-content"); NonTerminal variabledef = new NonTerminal("variabledef"); NonTerminal variabledefName = new NonTerminal("variabledef-name"); NonTerminal variabledefContents = new NonTerminal("variabledef-contents"); NonTerminal variabledefContent = new NonTerminal("variabledef-content"); NonTerminal variabledefPositionHint = new NonTerminal("variabledef-poshint"); NonTerminal constantdef = new NonTerminal("constantdef"); NonTerminal constantdefName = new NonTerminal("constantdef-name"); NonTerminal constantdefContents = new NonTerminal("constantdef-content"); NonTerminal constantdefContent = new NonTerminal("constantdef-content"); NonTerminal macrodef = new NonTerminal("macrodef"); NonTerminal macrodefArguments = new NonTerminal("macrodef-arguments"); NonTerminal macrodefArgument = new NonTerminal("macrodef-arguments"); NonTerminal macrodefContents = new NonTerminal("macrodef-contents"); NonTerminal macrodefContent = new NonTerminal("macrodef-content"); NonTerminal sectiondef = new NonTerminal("sectiondef"); NonTerminal sectiondefAttributes = new NonTerminal("sectiondef-attributes"); NonTerminal sectiondefAttribute = new NonTerminal("sectiondef-attribute"); NonTerminal sectiondefContents = new NonTerminal("sectiondef-contents"); NonTerminal sectiondefContent = new NonTerminal("sectiondef-content"); NonTerminal blockdef = new NonTerminal("blockdef"); NonTerminal blockdefContents = new NonTerminal("blockdef-contents"); NonTerminal blockdefContent = new NonTerminal("blockdef-content"); NonTerminal debugprint = new NonTerminal("debugprint"); #endregion #region Place Rules Here this.Root = fileroot; fileroot.Rule = rootdefs; rootdefs.Rule = MakeStarRule(rootdefs, rootdef); rootdef.Rule = sectiondef | usingDesc | memorySizeDesc | targetISADesc; usingDesc.Rule = ToTerm("#include") + stringLiteral + ToTerm(";"); memorySizeDesc.Rule = ToTerm("#memorysize") + number + ToTerm(";"); targetISADesc.Rule = ToTerm("#targetisa") + stringLiteral + ToTerm(";"); //Commons operandImm.Rule = valueInt | valueChar | valueRefAddr; valueInt.Rule = number; valueChar.Rule = charLiteral; valueRefAddr.Rule = ToTerm("&") + identifier | ToTerm("&") + identifier + ToTerm("[") + number + ToTerm("]"); operandRef.Rule = identifier; operandReg.Rule = ToTerm("$") + number | ToTerm("$") + identifier; //Variable variabledef.Rule = ToTerm(".variable") + variabledefName + ToTerm(";") //With no initial value (these will be grouped into one variable by optimization.) | ToTerm(".variable") + variabledefName + ToTerm("=") + variabledefContent + ToTerm(";") //With initial value (these will be not grouped.) | ToTerm(".variable") + variabledefName + ToTerm("[") + number + ToTerm("]") + ToTerm("=") + ToTerm("{") + variabledefContents + ToTerm("}") + ToTerm(";") | ToTerm(".variable") + variabledefName + variabledefPositionHint + ToTerm(";") //With no initial value (these will be grouped into one variable by optimization.) | ToTerm(".variable") + variabledefName + variabledefPositionHint + ToTerm("=") + variabledefContent + ToTerm(";") //With initial value (these will be not grouped.) | ToTerm(".variable") + variabledefName + ToTerm("[") + number + ToTerm("]") + variabledefPositionHint + ToTerm("=") + ToTerm("{") + variabledefContents + ToTerm("}") + ToTerm(";");; variabledefPositionHint.Rule = ToTerm("(") + ToTerm("@") + number + ToTerm(")"); variabledefName.Rule = identifier; variabledefContents.Rule = MakeStarRule(variabledefContents, ToTerm(","), variabledefContent); variabledefContent.Rule = valueInt | valueChar | valueRefAddr; //Constant constantdef.Rule = ToTerm(".constant") + constantdefName + ToTerm("=") + constantdefContent + ToTerm(";") | ToTerm(".constant") + constantdefName + ToTerm("[") + number + ToTerm("]") + ToTerm("=") + ToTerm("{") + constantdefContents + ToTerm("}") + ToTerm(";"); constantdefName.Rule = identifier; constantdefContents.Rule = MakeStarRule(constantdefContents, ToTerm(","), constantdefContent); constantdefContent.Rule = valueInt | valueChar | valueRefAddr; //Statement instr | callmacro debugprint.Rule = ToTerm(">>>>") + stringLiteral; label.Rule = identifier + ToTerm(":"); labeledStatement.Rule = label + labeledStatement | statement; statement.Rule = instr | macrocall; //Instruction instr.Rule = instrNemonic + instrOperands + ToTerm(";") | instrNemonic + instrOperands + ToTerm(";") + debugprint | instrNemonic + instrOperands + instrJump + ToTerm(";") | instrNemonic + instrOperands + instrJump + ToTerm(";") + debugprint; instrNemonic.Rule = identifier; instrLabels.Rule = MakeStarRule(instrLabels, label); instrOperands.Rule = MakeStarRule(instrOperands, ToTerm(","), labeledInstrOperand); labeledInstrOperand.Rule = label + labeledInstrOperand | instrOperand; instrOperand.Rule = operandRef | operandImm | operandReg; //Instruction Jump instrJump.Rule = ToTerm("-<") + instrJumpNemonic + instrJumpTarget; instrJumpNemonic.Rule = identifier; instrJumpTarget.Rule = operandRef | operandImm | operandReg; //Macrocall macrocall.Rule = ToTerm("~") + macrocallName + ToTerm("(") + macrocallOperands + ToTerm(")") + ToTerm(";") | ToTerm("~") + macrocallName + ToTerm("(") + macrocallOperands + ToTerm(")") + ToTerm(";") + debugprint; macrocallName.Rule = identifier; macrocallOperands.Rule = MakeStarRule(macrocallOperands, ToTerm(","), macrocallOperand); macrocallOperand.Rule = operandRef | operandImm | operandReg; //Macrodefinition macrodef.Rule = ToTerm("macro") + identifier + ToTerm("(") + macrodefArguments + ToTerm(")") + ToTerm("{") + macrodefContents + ToTerm("}"); macrodefArguments.Rule = MakeStarRule(macrodefArguments, ToTerm(","), macrodefArgument); macrodefArgument.Rule = identifier; macrodefContents.Rule = MakeStarRule(macrodefContents, macrodefContent); macrodefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | macrodef; //Symboldefinition symboldef.Rule = ToTerm(".symbol") + symboldefName + ToTerm("=") + symboldefContent + ToTerm(";") | ToTerm(".symbol") + symboldefName + ToTerm(":=") + symboldefContent + ToTerm(";"); symboldefName.Rule = identifier; symboldefContent.Rule = operandReg | ToTerm("@") + number | valueInt | valueChar | valueRefAddr; //Section 属性を設定可能 sectiondef.Rule = ToTerm("section") + identifier + ToTerm("{") + sectiondefAttributes + sectiondefContents + ToTerm("}"); sectiondefAttributes.Rule = MakeStarRule(sectiondefAttributes, sectiondefAttribute); sectiondefAttribute.Rule = ToTerm(".startup"); sectiondefContents.Rule = MakeStarRule(sectiondefContents, sectiondefContent); sectiondefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | symboldef | macrodef; //Block ただのスコープ blockdef.Rule = ToTerm("{") + blockdefContents + ToTerm("}") | identifier + ToTerm("{") + blockdefContents + ToTerm("}"); blockdefContents.Rule = MakeStarRule(blockdefContents, blockdefContent); blockdefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | symboldef | macrodef; //セクションで定義された変数や定数・命令は最適化されて好き勝手な場所に配置される. //デバッグ情報からその変数がどこのセクションで定義され,どこに配置されているかが確認できる //セクションはその親のセクションを持っている //ラベルを参照する際にはそのラベルが使用されたセクションから順に上をたどって参照先を検索する //マクロが展開されるとその中身は新しいブロックの中に展開される //.startup //.variable NAME = //.constant NAME = 0x23a1s,65409 //'srl: rd,rs,rt //{ // //} // //@ROM //{ // //} #endregion #region Define Keywords this.MarkReservedWords("break", "continue", "else", "extern", "for", "if", "int", "return", "static", "void", "while"); #endregion }
public UIGrammar() : base(caseSensitive: false) { LanguageFlags = LanguageFlags.CreateAst; StringLiteral STRING = new StringLiteral("STRING", "\"", StringOptions.None); NumberLiteral NUMBER = new NumberLiteral("NUMBER", NumberOptions.None); //ints that are too long for int32 are converted to int64 NUMBER.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 }; STRING.AstConfig.NodeType = typeof(StringValueNode); NUMBER.AstConfig.NodeType = typeof(NumberValueNode); CommentTerminal LINE_COMMENT = new CommentTerminal("LINE_COMMENT", "#", "\n", "\r\n", "\u0009", "\u2028", "\u2028", "\r"); NonGrammarTerminals.Add(LINE_COMMENT); NonTerminal BEGIN = new NonTerminal("BEGIN", typeof(BeginNode)); NonTerminal START_STATEMENT = new NonTerminal("START_STATEMENT", typeof(StartStatementNode)); //< LINE_CONTENT > NonTerminal LINE_CONTENT = new NonTerminal("LINE_CONTENT", typeof(LineContentNode)); //Any of the below. NonTerminal BEGIN_STATEMENT = new NonTerminal("BEGIN_STATEMENT", typeof(BeginStatementNode)); //<Begin> NonTerminal ANYASSIGNMENT = new NonTerminal("ANYASSIGNMENT", typeof(AnyAssignmentNode)); NonTerminal ASSIGNMENT = new NonTerminal("ASSIGNMENT", typeof(UIParser.Nodes.AssignmentNode)); //Argument = STRING | NUMBER NonTerminal ASSIGNMENTBLOCK = new NonTerminal("ASSIGNMENTBLOCK", typeof(AssignmentBlockNode)); NonTerminal DEFINEIMAGE_STATEMENT = new NonTerminal("DEFINEIMAGE_STATEMENT", typeof(DefineImageNode)); //<DefineImage> NonTerminal DEFINESTRING_STATEMENT = new NonTerminal("DEFINESTRING_STATEMENT", typeof(DefineStringNode)); //<DefineString> NonTerminal SETSHAREDPROPS_STATEMENT = new NonTerminal("SETSHAREDPROPS_STATEMENT", typeof(SetSharedPropsNode)); //<SetSharedProperties> NonTerminal ADDBUTTON_STATEMENT = new NonTerminal("ADDBUTTON_STATEMENT", typeof(AddButtonNode)); //<AddButton> NonTerminal ADDTEXT_STATEMENT = new NonTerminal("ADDTEXT_STATEMENT", typeof(AddTextNode)); //<AddText> NonTerminal ADDTEXTEDIT_STATEMENT = new NonTerminal("ADDTEXTEDIT_STATEMENT", typeof(AddTextEditNode)); //<AddTextEdit> NonTerminal ADDSLIDER_STATEMENT = new NonTerminal("ADDSLIDER_STATEMENT", typeof(AddSliderNode)); //<AddSlider> NonTerminal ADDPROGRESSBAR_STATEMENT = new NonTerminal("ADDPROGRESSBAR_STATEMENT", typeof(AddProgressBarNode)); //<AddProgressBar> NonTerminal ADDLISTBOX_STATEMENT = new NonTerminal("ADDLISTBOX_STATEMENT", typeof(AddListboxNode)); //<AddListBox> NonTerminal ADDFORMATEDTEXT_STATEMENT = new NonTerminal("ADDFORMATEDTEXT", typeof(AddFormatedTextNode)); //<AddFormattedText> NonTerminal SETCONTROLPROPS_STATEMENT = new NonTerminal("SETCONTROLPROPS_STATEMENT", typeof(SetControlPropsNode)); //<SetControlProperties> NonTerminal ARRAY = new NonTerminal("ARRAY", typeof(ArrayNode)); NonTerminal ARRAYLIST = new NonTerminal("ARRAYLIST", typeof(ArrayListNode)); //(1,2,3,4) NonTerminal END_IDENTIFIER = new NonTerminal("END_IDENTIFIER", typeof(EndNode)); //<End> KeyTerm COMMA = new KeyTerm(",", "COMMA"); COMMA.AstConfig.NodeType = typeof(CommaNode); //Rules START_STATEMENT.Rule = Empty | ToTerm("<") + LINE_CONTENT + ToTerm(">"); LINE_CONTENT.Rule = Empty | BEGIN_STATEMENT | DEFINEIMAGE_STATEMENT | SETSHAREDPROPS_STATEMENT | SETCONTROLPROPS_STATEMENT | ADDBUTTON_STATEMENT | ADDTEXT_STATEMENT | ADDTEXTEDIT_STATEMENT | ADDSLIDER_STATEMENT | ADDPROGRESSBAR_STATEMENT | ADDLISTBOX_STATEMENT | ADDFORMATEDTEXT_STATEMENT | DEFINESTRING_STATEMENT | END_IDENTIFIER; BEGIN_STATEMENT.Rule = "Begin"; DEFINEIMAGE_STATEMENT.Rule = ToTerm("DefineImage") + STRING + ASSIGNMENTBLOCK; DEFINESTRING_STATEMENT.Rule = ToTerm("DefineString") + STRING + ASSIGNMENTBLOCK; ASSIGNMENT.Rule = ToTerm("stringDir") + ToTerm("=") + STRING | ToTerm("stringTable") + ToTerm("=") + NUMBER | ToTerm("leftArrowImage") + ToTerm("=") + STRING | ToTerm("rightArrowImage") + ToTerm("=") + STRING | ToTerm("tracking") + ToTerm("=") + NUMBER | ToTerm("trigger") + ToTerm("=") + NUMBER | ToTerm("image") + ToTerm("=") + STRING | ToTerm("position") + ToTerm("=") + ARRAY | ToTerm("size") + ToTerm("=") + ARRAY | ToTerm("tooltip") + ToTerm("=") + STRING | ToTerm("toolTip") + ToTerm("=") + STRING | ToTerm("id") + ToTerm("=") + NUMBER | ToTerm("orientation") + ToTerm("=") + NUMBER | ToTerm("opaque") + ToTerm("=") + NUMBER | ToTerm("assetID") + ToTerm("=") + STRING | ToTerm("stringIndex") + ToTerm("=") + NUMBER | ToTerm("text") + ToTerm("=") + STRING | ToTerm("font") + ToTerm("=") + NUMBER | ToTerm("textColor") + ToTerm("=") + ARRAY | ToTerm("textColorSelected") + ToTerm("=") + ARRAY | ToTerm("textColorHighlighted") + ToTerm("=") + ARRAY | ToTerm("textColorDisabled") + ToTerm("=") + ARRAY | ToTerm("textButton") + ToTerm("=") + NUMBER | ToTerm("color") + ToTerm("=") + ARRAY | ToTerm("alignment") + ToTerm("=") + NUMBER | ToTerm("backColor") + ToTerm("=") + ARRAY | ToTerm("frameOnFocus") + ToTerm("=") + NUMBER | ToTerm("cursorColor") + ToTerm("=") + ARRAY | ToTerm("transparent") + ToTerm("=") + NUMBER | ToTerm("frameColor") + ToTerm("=") + ARRAY | ToTerm("capacity") + ToTerm("=") + NUMBER | ToTerm("lines") + ToTerm("=") + NUMBER | ToTerm("flashOnEmpty") + ToTerm("=") + NUMBER | ToTerm("thumbSize") + ToTerm("=") + ARRAY | ToTerm("thumbMargins") + ToTerm("=") + ARRAY | ToTerm("thumbImageSize") + ToTerm("=") + ARRAY | ToTerm("thumbImageOffsets") + ToTerm("=") + ARRAY | ToTerm("thumbButtonImage") + ToTerm("=") + STRING | ToTerm("wrapped") + ToTerm("=") + NUMBER | ToTerm("textColor") + ToTerm("=") + ARRAY | ToTerm("mode") + ToTerm("=") + STRING | ToTerm("scrollBarImage") + ToTerm("=") + STRING | ToTerm("scrollBarGutter") + ToTerm("=") + NUMBER | ToTerm("scrollBarType") + ToTerm("=") + NUMBER | ToTerm("enableIME") + ToTerm("=") + NUMBER | ToTerm("highlighted") + ToTerm("=") + NUMBER | ToTerm("minValue") + ToTerm("=") + NUMBER | ToTerm("maxValue") + ToTerm("=") + NUMBER | ToTerm("pageSize") + ToTerm("=") + NUMBER | ToTerm("MouseTransparent") + ToTerm("=") + NUMBER | ToTerm("backgroundColor") + ToTerm("=") + ARRAY | ToTerm("alignments") + ToTerm("=") + NUMBER | ToTerm("visibleRows") + ToTerm("=") + NUMBER | ToTerm("columns") + ToTerm("=") + NUMBER | ToTerm("rowHeight") + ToTerm("=") + NUMBER | ToTerm("fillColor") + ToTerm("=") + ARRAY | ToTerm("selectionFillColor") + ToTerm("=") + ARRAY | ToTerm("cursor") + ToTerm("=") + NUMBER | ToTerm("lineHeight") + ToTerm("=") + NUMBER | ToTerm("edgeOffsetL") + ToTerm("=") + NUMBER | ToTerm("edgeOffsetR") + ToTerm("=") + NUMBER | ToTerm("edgeoffsetT") + ToTerm("=") + NUMBER | ToTerm("edgeOffsetB") + ToTerm("=") + NUMBER | ToTerm("foregroundImage") + ToTerm("=") + STRING | ToTerm("backgroundImage") + ToTerm("=") + STRING | ToTerm("value") + ToTerm("=") + NUMBER | ToTerm("useBackgroundImage") + ToTerm("=") + NUMBER | ToTerm("enabled") + ToTerm("=") + NUMBER | ToTerm("fittext") + ToTerm("=") + NUMBER; ANYASSIGNMENT.Rule = MakeStarRule(ANYASSIGNMENT, ASSIGNMENT); //This means "assignmentblock is assignment followed by n assignments". ASSIGNMENTBLOCK.Rule = MakePlusRule(ASSIGNMENTBLOCK, ANYASSIGNMENT); SETSHAREDPROPS_STATEMENT.Rule = ToTerm("SetSharedProperties") + ASSIGNMENTBLOCK; SETCONTROLPROPS_STATEMENT.Rule = ToTerm("SetControlProperties") + STRING + ASSIGNMENTBLOCK | ToTerm("SetControlProperties") + STRING; ADDBUTTON_STATEMENT.Rule = ToTerm("AddButton") + STRING + ASSIGNMENTBLOCK; ADDTEXT_STATEMENT.Rule = ToTerm("AddText") + STRING + ASSIGNMENTBLOCK; ADDTEXTEDIT_STATEMENT.Rule = ToTerm("AddTextEdit") + STRING + ASSIGNMENTBLOCK; ADDSLIDER_STATEMENT.Rule = ToTerm("AddSlider") + STRING + ASSIGNMENTBLOCK; ADDPROGRESSBAR_STATEMENT.Rule = ToTerm("AddProgressBar") + STRING + ASSIGNMENTBLOCK; ADDLISTBOX_STATEMENT.Rule = ToTerm("AddListBox") + STRING + ASSIGNMENTBLOCK; ADDFORMATEDTEXT_STATEMENT.Rule = ToTerm("AddFormatedText") + STRING + ASSIGNMENTBLOCK; ARRAY.Rule = ToTerm("(") + ARRAYLIST + ")"; ARRAYLIST.Rule = MakeStarRule(ARRAYLIST, COMMA, NUMBER); END_IDENTIFIER.Rule = "End"; BEGIN.Rule = MakePlusRule(BEGIN, START_STATEMENT); this.Root = BEGIN; }
public PieChartSeries GeneratePieChartSeries(string[] labels, double[] data) { PieChartSeries pieChartSeries1 = new PieChartSeries(); Index index1 = new Index() { Val = (UInt32Value)0U }; Order order1 = new Order() { Val = (UInt32Value)0U }; SeriesText seriesText1 = new SeriesText(); NumericValue numericValue1 = new NumericValue(); numericValue1.Text = "sreie 1"; seriesText1.Append(numericValue1); CategoryAxisData categoryAxisData1 = new CategoryAxisData(); StringLiteral stringLiteral1 = new StringLiteral(); PointCount pointCount1 = new PointCount() { Val = (uint)labels.Length }; //StringPoint stringPoint1 = new StringPoint() { Index = (UInt32Value)0U }; //NumericValue numericValue2 = new NumericValue(); //numericValue2.Text = "a"; //stringPoint1.Append(numericValue2); //StringPoint stringPoint2 = new StringPoint() { Index = (UInt32Value)1U }; //NumericValue numericValue3 = new NumericValue(); //numericValue3.Text = "n"; //stringPoint2.Append(numericValue3); //StringPoint stringPoint3 = new StringPoint() { Index = (UInt32Value)2U }; //NumericValue numericValue4 = new NumericValue(); //numericValue4.Text = "c"; //stringPoint3.Append(numericValue4); //StringPoint stringPoint4 = new StringPoint() { Index = (UInt32Value)3U }; //NumericValue numericValue5 = new NumericValue(); //numericValue5.Text = "d"; //stringPoint4.Append(numericValue5); //Ajout des etiquette de legendes for (int i = 0; i < labels.Length; i++) { StringPoint stringPoint = new StringPoint() { Index = (uint)i }; NumericValue numericValue = new NumericValue(); numericValue.Text = labels[i]; stringPoint.Append(numericValue); stringLiteral1.Append(stringPoint); } stringLiteral1.Append(pointCount1); //stringLiteral1.Append(stringPoint1); //stringLiteral1.Append(stringPoint2); //stringLiteral1.Append(stringPoint3); //stringLiteral1.Append(stringPoint4); categoryAxisData1.Append(stringLiteral1); DocumentFormat.OpenXml.Drawing.Charts.Values values1 = new DocumentFormat.OpenXml.Drawing.Charts.Values(); NumberLiteral numberLiteral1 = new NumberLiteral(); FormatCode formatCode1 = new FormatCode(); formatCode1.Text = "General"; PointCount pointCount2 = new PointCount() { Val = (uint)data.Length }; //NumericPoint numericPoint1 = new NumericPoint() { Index = (UInt32Value)0U }; //NumericValue numericValue6 = new NumericValue(); //numericValue6.Text = "1"; //numericPoint1.Append(numericValue6); //NumericPoint numericPoint2 = new NumericPoint() { Index = (UInt32Value)1U }; //NumericValue numericValue7 = new NumericValue(); //numericValue7.Text = "2"; //numericPoint2.Append(numericValue7); //NumericPoint numericPoint3 = new NumericPoint() { Index = (UInt32Value)2U }; //NumericValue numericValue8 = new NumericValue(); //numericValue8.Text = "3"; //numericPoint3.Append(numericValue8); //NumericPoint numericPoint4 = new NumericPoint() { Index = (UInt32Value)3U }; //NumericValue numericValue9 = new NumericValue(); //numericValue9.Text = "5"; //numericPoint4.Append(numericValue9); for (int i = 0; i < data.Length; i++) { NumericPoint numericPoint = new NumericPoint() { Index = (uint)i }; NumericValue numericValue = new NumericValue(); numericValue.Text = data[i].ToString(); numericPoint.Append(numericValue); numberLiteral1.Append(numericPoint); } numberLiteral1.Append(formatCode1); numberLiteral1.Append(pointCount2); //numberLiteral1.Append(numericPoint1); //numberLiteral1.Append(numericPoint2); //numberLiteral1.Append(numericPoint3); //numberLiteral1.Append(numericPoint4); values1.Append(numberLiteral1); pieChartSeries1.Append(index1); pieChartSeries1.Append(order1); pieChartSeries1.Append(seriesText1); pieChartSeries1.Append(categoryAxisData1); pieChartSeries1.Append(values1); return(pieChartSeries1); }
public Gramatica() : base(false) { // Expresiones regulares se escribe de la siguiente forma //existe multiples formas de crear expresiones regulares puedes revisar la documentacion. //RegexBasedTerminal Id = new RegexBasedTerminal("Id", "[0-9]*[a-zA-Z][0-9a-zA-Z]*"); Terminal id = new IdentifierTerminal("Id"), numDoble = new NumberLiteral("numDoble"), caracter = new StringLiteral("caracter", "'", StringOptions.IsChar), cadena = new StringLiteral("cadena", "\""), verdadero = ToTerm("true"), falso = ToTerm("false"), suma = ToTerm("+"), resta = ToTerm("-"), multi = ToTerm("*"), div = ToTerm("/"), power = ToTerm("pow"), abrirparentesis = ToTerm("("), cerrarparentesis = ToTerm(")"), //aumento = ToTerm("++"), //decremento = ToTerm("--"), numEntero = new NumberLiteral("numEntero", NumberOptions.IntOnly); //Comentarios. CommentTerminal comentarioMulti = new CommentTerminal("comentarioMulti", "{--", "--}"); CommentTerminal comentarioUni = new CommentTerminal("comentarioUni", "##"); base.NonGrammarTerminals.Add(comentarioMulti); base.NonGrammarTerminals.Add(comentarioUni); //Precedencia de operadores // RegisterOperators(1, suma, resta); //RegisterOperators(2, div, multi, power); //Declaracion de no terminales NonTerminal INICIO = new NonTerminal("INICIO"), VALOR = new NonTerminal("VALOR"), OPERADORA = new NonTerminal("OPERADORA"), OPARITMETICA = new NonTerminal("OPARITMETICA"); //S.Rule para escribir el cuerpo de un no terminal con todas sus producciones. INICIO.Rule = OPARITMETICA; VALOR.Rule = id | numDoble | numEntero | caracter | cadena | verdadero | falso; OPERADORA.Rule = suma | resta | multi | div | power; OPARITMETICA.Rule = OPARITMETICA + OPARITMETICA + OPERADORA + Eof | "(" + OPARITMETICA + OPARITMETICA + OPERADORA + ")" + Eof | "(" + VALOR + ")" + Eof | VALOR; //indicamos la produccion inicial con la siguiente linea this.Root = INICIO; }
public DemoGrammar() : base(false) // true means case sensitive { GrammarComments = @"A Demo Language. Case-insensitive."; //comment CommentTerminal eolComment = new CommentTerminal("eolComment", "//", "\n", "\r"); NonGrammarTerminals.Add(eolComment); //number NumberLiteral integer_terminal = new NumberLiteral("integer", NumberOptions.IntOnly | NumberOptions.AllowSign, typeof(IntegerAstNode)); integer_terminal.DefaultIntTypes = new TypeCode[] { TypeCode.Int32 }; integer_terminal.AddPrefix("0b", NumberOptions.Binary); integer_terminal.AddPrefix("0x", NumberOptions.Hex); //label IdentifierTerminal label_terminal = new IdentifierTerminal("label_terminal"); //string StringLiteral string_terminal = new StringLiteral("string", "\"", StringOptions.None, typeof(StringAstNode)); //keywords KeyTerm FILTERS = ToTerm("filters"); KeyTerm FILTER = ToTerm("filter"); KeyTerm OPEN = ToTerm("["); KeyTerm CLOSE = ToTerm("]"); //name NonTerminal name = new NonTerminal("name", typeof(NameAstNode)); name.Rule = label_terminal; //value NonTerminal value = new NonTerminal("value"); value.Rule = integer_terminal | string_terminal; //nvPair NonTerminal nvPair = new NonTerminal("nvPair", typeof(NvPairAstNode)); nvPair.Rule = name + "=" + value + ";"; //note: you don't have to excplitly declare KeyTerms //nvPairs NonTerminal nvPairs = new NonTerminal("nvPairs"); nvPairs.Rule = MakeStarRule(nvPairs, nvPair); //filter NonTerminal filter = new NonTerminal("filter", typeof(FilterAstNode)); filter.Rule = FILTER + OPEN + nvPairs + CLOSE; //filters NonTerminal filters = new NonTerminal("filters"); filters.Rule = MakeStarRule(filters, filter); //file NonTerminal file = new NonTerminal("file", typeof(FileAstNode)); file.Rule = FILTERS + OPEN + filters + CLOSE; Root = file; LanguageFlags |= LanguageFlags.CreateAst; }
public ExpressionGrammar() : 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 numberLiteral = new NumberLiteral("number", NumberOptions.AllowSign | NumberOptions.AllowStartEndDot) { DefaultIntTypes = new [] { TypeCode.Int32, TypeCode.Int64 } }; var stringLiteral = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote | StringOptions.AllowsLineBreak | StringOptions.AllowsAllEscapes); var idSimple = CreateSqlExtIdentifier("id_simple"); //covers normal identifiers (abc) and quoted id's ([abc d], "abc d") var commaTerm = ToTerm(","); var dotTerm = ToTerm("."); var notTerm = ToTerm("NOT"); //Non-terminals var id = new NonTerminal("Id"); var idlist = new NonTerminal("idlist"); var idlistPar = new NonTerminal("idlistPar"); var tuple = new NonTerminal("tuple"); var expression = new NonTerminal("expression"); var exprList = new NonTerminal("exprList"); var caseStmt = new NonTerminal("case"); var caseVariable = new NonTerminal("caseVariable"); var caseWhenList = new NonTerminal("caseWhenList"); var caseWhenThen = new NonTerminal("caseWhenThen"); var caseDefaultOpt = new NonTerminal("caseDefault"); 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 inExpr = new NonTerminal("inExpr"); var notOpt = new NonTerminal("notOpt"); var funCall = new NonTerminal("funCall"); var funArgs = new NonTerminal("funArgs"); //var inStmt = new NonTerminal("inStmt"); //BNF Rules Root = expression; //ID id.Rule = MakePlusRule(id, dotTerm, idSimple); idlistPar.Rule = "(" + idlist + ")"; idlist.Rule = MakePlusRule(idlist, commaTerm, id); caseWhenThen.Rule = "WHEN" + exprList + "THEN" + expression; caseWhenList.Rule = MakePlusRule(caseWhenList, caseWhenThen); caseDefaultOpt.Rule = Empty | "ELSE" + expression; caseVariable.Rule = Empty | expression; caseStmt.Rule = "CASE" + caseVariable + caseWhenList + caseDefaultOpt + "END"; //Expression exprList.Rule = MakePlusRule(exprList, commaTerm, expression); expression.Rule = term | unExpr | binExpr | caseStmt | betweenExpr; //-- BETWEEN brings a few parsing conflicts, use parentheses tuple.Rule = "(" + exprList + ")"; term.Rule = id | stringLiteral | numberLiteral | funCall | tuple; // | inStmt; unExpr.Rule = unOp + term | term + "IS" + "NULL" | term + "IS" + "NOT" + "NULL"; unOp.Rule = notTerm | "+" | "-" | "~"; binExpr.Rule = expression + binOp + expression; binOp.Rule = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic | "&" | "|" | "^" //bit | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>" | "AND" | "OR" | "XOR" | "LIKE" | notTerm + "LIKE" | "IN" | notTerm + "IN"; betweenExpr.Rule = expression + notOpt + "BETWEEN" + expression + "AND" + expression; notOpt.Rule = Empty | notTerm; //funCall covers some psedo-operators and special forms like ANY(...), SOME(...), ALL(...), EXISTS(...), IN(...) funCall.Rule = id + "(" + funArgs + ")"; funArgs.Rule = Empty | exprList; //inStmt.Rule = expression + "IN" + "(" + exprList + ")"; //Operators RegisterOperators(10, "*", "/", "%"); RegisterOperators(9, "+", "-"); RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>", "LIKE", "IN", "BETWEEN"); RegisterOperators(7, "^", "&", "|"); RegisterOperators(6, notTerm); RegisterOperators(5, "AND"); RegisterOperators(4, "OR", "XOR"); MarkPunctuation(",", "(", ")"); //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 MarkTransient(term, expression, unOp); binOp.SetFlag(TermFlags.InheritPrecedence); SnippetRoots.Add(expression); }
public void TestNumberLiteral() { NumberLiteral node = (NumberLiteral)GetExpression1(); CheckSerializationRoundTrip(node); }
public Gramatica_Import_DATA() : base(caseSensitive: false) { #region Expresiones_Regulares StringLiteral CADENA = new StringLiteral("Cadena", "\""); NumberLiteral NUMERO = new NumberLiteral("Numero"); var DECIMAL = new RegexBasedTerminal("Decimal", "[0-9]+'.'[0-9]+"); var RDATE = new RegexBasedTerminal("Date", "\'[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\'"); var RTIME = new RegexBasedTerminal("Time", "\'[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\'"); IdentifierTerminal IDENTIFICADOR = new IdentifierTerminal("Identificador"); CommentTerminal comentarioLinea = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n"); //si viene una nueva linea se termina de reconocer el comentario. CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/"); CommentTerminal CONT_DATA_IMPORT = new CommentTerminal("CONT_DATA_IMPORT", "$", "$"); #endregion #region Terminales KeyTerm MENQUE = ToTerm("<"), MAYQUE = ToTerm(">"), IGUAL = ToTerm("="), CORIZQ = ToTerm("["), CORDER = ToTerm("]"), COMA = ToTerm(","), RFALSE = ToTerm("FALSE"), RTRUE = ToTerm("TRUE"), RNULL = ToTerm("NULL"); #endregion #region No_Terminales NonTerminal S = new NonTerminal("S"), VALOR = new NonTerminal("VALOR"), DATA_DATA3 = new NonTerminal("DATA_DATA3"), DATA_DATA4 = new NonTerminal("DATA_DATA4"), DATA_DATA5 = new NonTerminal("DATA_DATA5"), DATA_DATA6 = new NonTerminal("DATA_DATA6"), LISTAS = new NonTerminal("LISTAS"), LISTAS2 = new NonTerminal("LISTAS2"), LISTAS3 = new NonTerminal("LISTAS3"), MAPA = new NonTerminal("MAPA"), MAPA2 = new NonTerminal("MAPA2"), MAPA3 = new NonTerminal("MAPA3"); #endregion #region GRAMATICA S.Rule = DATA_DATA3; DATA_DATA3.Rule = DATA_DATA3 + COMA + DATA_DATA4 | DATA_DATA4; DATA_DATA3.ErrorRule = SyntaxError + MENQUE; DATA_DATA4.Rule = MENQUE + DATA_DATA5 + MAYQUE; DATA_DATA5.Rule = DATA_DATA5 + COMA + DATA_DATA6 | DATA_DATA6; DATA_DATA6.Rule = VALOR + IGUAL + VALOR; VALOR.Rule = CADENA | DECIMAL | IDENTIFICADOR | MAPA | LISTAS | NUMERO | RTRUE | RFALSE | RTIME | RNULL | RDATE; #region LISTAS y MAPAS LISTAS.Rule = CORIZQ + LISTAS2 + CORDER; LISTAS2.Rule = LISTAS2 + COMA + LISTAS3 | LISTAS3 | Empty; LISTAS3.Rule = VALOR; MAPA.Rule = MENQUE + MAPA2 + MAYQUE; MAPA2.Rule = MAPA2 + COMA + MAPA3 | MAPA3 | Empty; MAPA3.Rule = VALOR + IGUAL + VALOR; #endregion #endregion #region Preferencias this.Root = S; #endregion }
public T3000Grammar() : base(caseSensitive: true) //Changed, Control Basic is Case Sensitive: SET-PRINTER vs Set-Printer { // 1. Terminals //Comentarios CommentTerminal Comment = new CommentTerminal("Comment", "REM ", "\n", "\r\n"); var Number = new NumberLiteral("Number", NumberOptions.AllowStartEndDot | NumberOptions.AllowSign); Number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64 }; Number.DefaultFloatType = TypeCode.Single; Number.AddExponentSymbols("E", TypeCode.Double); Number.AddExponentSymbols("E-", TypeCode.Double); Number.Priority = 20; //string MyNumberLiteral = "(\\-?\\d+)\\.?\\d+(E\\-|E\\+|E|\\d+)\\d+"; //var Number = new RegexBasedTerminal("MyNumber", MyNumberLiteral); //Number.Priority = 20; var IntegerNumber = new NumberLiteral("IntegerNumber", NumberOptions.IntOnly); IntegerNumber.Priority = 10; var LineNumber = new NumberLiteral("LineNumber", NumberOptions.IntOnly); LineNumber.Priority = 11; //var Space = new RegexBasedTerminal("Space", "\\s+"); //var AlarmMessage = new RegexBasedTerminal("AlarmMessage", "(\\w| |\\.|-|,|;|:|!|\\?|¡|¿|\\|\\/){1,69}"); var StringMessage = new FreeTextLiteral("Text", FreeTextOptions.AllowEmpty | FreeTextOptions.AllowEof, Environment.NewLine); StringMessage.Priority = 5; var EnclosedString = new StringLiteral("EnclosedString", "\"", StringOptions.NoEscapes); EnclosedString.Priority = 5; string IDTYPE1 = "[A-Z0-9]+?[\\.\\-_A-Z0-9]*(([A-Z]+[\\.]?[0-9]*)+?)"; var Identifier = new RegexBasedTerminal("Identifier", IDTYPE1); Identifier.Priority = 30; //123.25BAC_NET 1245.4A //12.3.FLOOR //FLOOR //FLOOR_A2 //12.A 15.0A // VAR1 VAR2 OUT12 IN1 THRU IN128 AY1 TRHU AY64 //12.5E23 <-- POSSIBLE CONFLICT BUT CORRECT NUMBER SciNotation SHOULD BE 12.5E+23 //19.253.REG136 //SCALTOT2 //A12 A23.3 <-- NOT SUPPORTED BY IDTYPE1 var LoopVariable = new RegexBasedTerminal("LoopVariable", "[A-K]"); var LocalVariable = new RegexBasedTerminal("LocalVariable", "[A-Z]{1}"); var LocalVariable1 = new RegexBasedTerminal("LocalVariable1", "[A-Z0-9]"); string PrintAscii = "(3[2-9])|([4-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|('[A-Za-z]')"; var PrintableAscii = new RegexBasedTerminal("PrintableAscii", PrintAscii); PrintableAscii.Priority = 25; //RegEx Tested Strings, for ending valid Control Points string UPTO128 = "12[0-8]|1[0-1][0-9]|[1-9][0-9]?"; string UPTO96 = "9[0-6]|[1-8][0-9]?"; string UPTO64 = "6[0-4]|[1-5][0-9]?"; string UPTO48 = "4[0-8]|[1-3][0-9]?"; string UPTO32 = "3[0-2]|[1-2][0-9]?"; string UPTO16 = "1[0-6]|[1-9]"; //string UPTO8 = "[1-8]"; string UPTO4 = "[1-4]"; string UPTO31 = "3[0-1]|[1-2][0-9]?"; string UPTO5 = "[1-5]"; //Control Points var VARS = new RegexBasedTerminal("VARS", "VAR(" + UPTO128 + ")"); VARS.Priority = 40; //adjusted for Rev6 //TODO: Adjust EBNF too!! var OUTS = new RegexBasedTerminal("OUTS", "OUT(" + UPTO64 + ")"); OUTS.Priority = 40; //adjusted for Rev6 //TODO: Adjust EBNF too!! var INS = new RegexBasedTerminal("INS", "IN(" + UPTO64 + ")"); INS.Priority = 40; //adjusted for Rev6 //TODO: Adjust EBNF too!! var PRG = new RegexBasedTerminal("PRG", "PRG(" + UPTO16 + ")"); PRG.Priority = 40; var DMON = new RegexBasedTerminal("DMON", "DMON(" + UPTO128 + ")"); DMON.Priority = 40; var AMON = new RegexBasedTerminal("AMON", "AMON(" + UPTO96 + ")"); AMON.Priority = 40; //ARRAYS ELEMENTS var ARR = new RegexBasedTerminal("ARR", "AY(" + UPTO48 + ")\\[\\d+\\]"); ARR.Priority = 40; //Controllers, now known as PIDS var PIDS = new RegexBasedTerminal("PIDS", "PID(" + UPTO64 + ")"); PIDS.Priority = 40; //Controllers, for backwards compatibility var CON = new RegexBasedTerminal("CON", "CON(" + UPTO64 + ")"); CON.Priority = 40; var CONNUMBER = new RegexBasedTerminal("CONNUMBER", "(" + UPTO64 + ")"); CON.Priority = 40; //Weekly Routines, now known as Schedules var WRS = new RegexBasedTerminal("WRS", "SCH(" + UPTO64 + ")"); WRS.Priority = 40; //Anual routines, now known as Holidays var ARS = new RegexBasedTerminal("ARS", "HOL(" + UPTO64 + ")"); ARS.Priority = 40; var GRP = new RegexBasedTerminal("GRP", "GRP(" + UPTO32 + ")"); GRP.Priority = 40; var PANEL = new RegexBasedTerminal("PANEL", "(" + UPTO5 + ")"); PANEL.Priority = 40; //Other sub-literals var DayNumber = new RegexBasedTerminal("DayNumber", "(" + UPTO31 + ")"); DayNumber.Priority = 9; var TimeLiteral = new RegexBasedTerminal("TimeLiteral", "(2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]"); TimeLiteral.Priority = 100; var Ordinal = new RegexBasedTerminal("Ordinal", UPTO64); String Phone = "(\\+\\d{1,2}[\\s\\.\\-])?(\\(?\\d{3}\\)?[\\s\\.\\-]?)?\\d{3,4}[\\s.-]?\\d{3,4}"; var PhoneNumber = new RegexBasedTerminal("PhoneNumber", Phone); PhoneNumber.Priority = 1; //v3 Manual states that only exists 5 customs tables. var TABLENUMBER = new RegexBasedTerminal("TABLENUMBER", "(" + UPTO5 + ")"); //Same, up to 16 program codes (control Basic) var SYSPRG = new RegexBasedTerminal("SYSPRG", "(" + UPTO16 + ")"); var TIMER = new RegexBasedTerminal("TIMER", "(" + UPTO4 + ")"); //KEYWORDS //Puctuation var PARIZQ = ToTerm("("); var PARDER = ToTerm(")"); var CommandSeparator = ToTerm(";"); var Comma = ToTerm(",", "COMMA"); var DDOT = ToTerm(":"); //Operators //Comparisson Operators var AssignOp = ToTerm("=", "ASSIGN"); var LT = ToTerm("<", "LT"); var GT = ToTerm(">", "GT"); var LTE = ToTerm("<=", "LE"); var GTE = ToTerm(">=", "GE"); var NEQ = ToTerm("<>", "NE"); var EQ = ToTerm("=", "EQ"); var NOT = ToTerm("NOT"); //Logical Operators var AND = ToTerm("AND"); var XOR = ToTerm("XOR"); var OR = ToTerm("OR"); //Arithmetic Operators var SUM = ToTerm("+", "PLUS"); var SUB = ToTerm("-", "MINUS"); var MUL = ToTerm("*", "MUL"); var DIV = ToTerm("/", "DIV"); var IDIV = ToTerm("\\", "IDIV"); // One \ operator for integer division var EXP = ToTerm("^", "POW"); var MOD = ToTerm("MOD"); //Months var JAN = ToTerm("JAN"); var FEB = ToTerm("FEB"); var MAR = ToTerm("MAR"); var APR = ToTerm("APR"); var MAY = ToTerm("MAY"); var JUN = ToTerm("JUN"); var JUL = ToTerm("JUL"); var AUG = ToTerm("AUG"); var SEP = ToTerm("SEP"); var OCT = ToTerm("OCT"); var NOV = ToTerm("NOV"); var DEC = ToTerm("DEC"); //Days var SUN = ToTerm("SUN"); var MON = ToTerm("MON"); var TUE = ToTerm("TUE"); var WED = ToTerm("WED"); var THU = ToTerm("THU"); var FRI = ToTerm("FRI"); var SAT = ToTerm("SAT"); //Functions var DOY = ToTerm("DOY"); var DOM = ToTerm("DOM"); var DOW = ToTerm("DOW"); var POWERLOSS = ToTerm("POWER-LOSS", "POWER_LOSS"); var DATE = ToTerm("DATE"); var TIME = ToTerm("TIME"); var UNACK = ToTerm("UNACK"); var USERA = ToTerm("USER-A", "USER_A"); var USERB = ToTerm("USER-B", "USER-B"); var BEEP = ToTerm("BEEP"); var SCANS = ToTerm("SCANS"); // 2. Non-terminals var CONTROL_BASIC = new NonTerminal("CONTROL_BASIC", typeof(StatementListNode)); var SentencesSequence = new NonTerminal("SentencesSequence"); var Sentence = new NonTerminal("Sentence"); var DECLAREStatement = new NonTerminal("DECLAREStatement"); var ENDStatement = new NonTerminal("ENDStatement"); var ProgramLine = new NonTerminal("ProgramLine"); var BasicLine = new NonTerminal("BasicLine"); var Subroutine = new NonTerminal("Subroutine"); var SubroutineSentences = new NonTerminal("SubRoutineSentences"); //var LineNumber = new NonTerminal("LineNumber"); var EmptyLine = new NonTerminal("EmptyLine"); var Statement = new NonTerminal("Statement"); var EndProgLine = new NonTerminal("CommentOpt"); var Commands = new NonTerminal("Commands"); var Command = new NonTerminal("Command"); var NextCommand = new NonTerminal("NextCommand"); //Commands var START = new NonTerminal("START"); var STOP = new NonTerminal("STOP"); var OPEN = new NonTerminal("OPEN"); var CLOSE = new NonTerminal("CLOSE"); var LET = new NonTerminal("LET"); var ALARM = new NonTerminal("ALARM"); var ALARMAT = new NonTerminal("ALARMAT"); var CALL = new NonTerminal("CALL"); var CALLARGS = new NonTerminal("CALLARGS"); var CALLARGSLIST = new NonTerminal("CALLARGLIST"); var ARG = new NonTerminal("ARG"); var CLEAR = new NonTerminal("CLEAR"); var DALARM = new NonTerminal("DALARM"); var DISABLE = new NonTerminal("DISABLE"); var ENABLE = new NonTerminal("ENABLE"); var HANGUP = new NonTerminal("HANGUP"); var PHONE = new NonTerminal("PHONE"); var PRINT = new NonTerminal("PRINT"); var PRINTAT = new NonTerminal("PRINTAT"); var PANELS = new NonTerminal("PANELS"); var PrintableKeywords = new NonTerminal("PrintableKeywords"); var REMOTEGET = new NonTerminal("REMOTEGET"); var REMOTESET = new NonTerminal("REMOTESET"); var RETURN = new NonTerminal("RETURN"); var RUNMACRO = new NonTerminal("RUNMACRO"); var SETPRINTER = new NonTerminal("SETPRINTER"); var PrintEverything = new NonTerminal("FULLPRINTING"); var PrintOnlyCommands = new NonTerminal("ONLYCOMMANDSPRINTING"); var WAIT = new NonTerminal("WAIT"); var Function = new NonTerminal("Function"); var ABS = new NonTerminal("ABS"); var AVG = new NonTerminal("AVG"); var CONPROP = new NonTerminal("CONPROP"); var CONRATE = new NonTerminal("CONRATE"); var CONRESET = new NonTerminal("CONRESET"); var INT = new NonTerminal("INT"); var INTERVAL = new NonTerminal("INVERVAL"); var LN = new NonTerminal("LN"); var LN1 = new NonTerminal("LN1"); var MAX = new NonTerminal("MAX"); var MIN = new NonTerminal("MIN"); //SQR | STATUS | TBL var SQR = new NonTerminal("SQR"); var STATUS = new NonTerminal("STATUS"); var TBL = new NonTerminal("TBL"); //TIMEOFF | TIMEON | WRON | WROFF var TIMEOFF = new NonTerminal("TIMEOFF"); var TIMEON = new NonTerminal("TIMEON"); var WRON = new NonTerminal("WRON"); var WROFF = new NonTerminal("WROFF"); var COM1 = new NonTerminal("COM1"); var BAUDRATE = new NonTerminal("BAUDRATE"); var PORT = new NonTerminal("PORT"); var CHARS = new NonTerminal("CHARS"); var ComParameters = new NonTerminal("ComParameters"); //Create Assignment statement var Assignment = new NonTerminal("Assignment"); var Branch = new NonTerminal("Branch"); //BRANCH //Branch ::= IF | IFTRUE | IFFALSE | GOSUB | GOTO | ON var IF = new NonTerminal("IF"); var IFTRUE = new NonTerminal("IFTRUE"); var IFFALSE = new NonTerminal("IFFALSE"); var GOSUB = new NonTerminal("GOSUB"); var GOTO = new NonTerminal("GOTO"); var ON = new NonTerminal("ON"); var IFCLAUSE = new NonTerminal("IFCLAUSE"); var ELSEOPT = new NonTerminal("ELSEOPT"); var GOSELECTOR = new NonTerminal("GOSELECTOR"); var ONALARM = new NonTerminal("ONALARM"); var ONERROR = new NonTerminal("ONERROR"); //var Loop = new NonTerminal("Loop"); var FOR = new NonTerminal("FOR"); var ENDFOR = new NonTerminal("ENDFOR"); var STEPFOR = new NonTerminal("STEPFOR"); //Operators var LogicOps = new NonTerminal("LogicOps"); var ArithmeticOps = new NonTerminal("ArithmeticOps"); var ComparisonOps = new NonTerminal("ComparisonOps"); var UnaryOps = new NonTerminal("UnaryOps"); var BinaryOps = new NonTerminal("BinaryOps"); var Designator = new NonTerminal("Designator"); var RemoteDesignator = new NonTerminal("RemoteDesignator"); var PointIdentifier = new NonTerminal("PointIdentifier"); var Literal = new NonTerminal("Literal"); var DatesLiteral = new NonTerminal("DatesLiteral"); var MonthLiteral = new NonTerminal("MonthLiteral"); var DayLiteral = new NonTerminal("DayLiteral"); //var TimeLiteral = new NonTerminal("TimeLiteral"); //Terms to Expressions var UnaryExpression = new NonTerminal("UnaryExpression"); var BinaryExpression = new NonTerminal("BinaryExpression"); var EnclosableExpression = new NonTerminal("EnclosableExpression"); var Expression = new NonTerminal("Expression"); // LISTAS var IdentifierList = new NonTerminal("IdentifierList"); var LoopVariableList = new NonTerminal("LoopVariableList"); var ExpressionListOpt = new NonTerminal("ExpressionListOpt"); var LineNumberListOpt = new NonTerminal("LineNumberListOpt"); var PrintableListOpt = new NonTerminal("PrintableListOpt"); // 3. BNF rules ///////////////////// //Set grammar root ///////////////////// Root = CONTROL_BASIC; //CONTROL_BASIC ::= SentencesSequence | SubRoutine CONTROL_BASIC.Rule = SentencesSequence | Subroutine; #region Encoded Subroutines //SubRoutine ::= (LineNumber DECLARE EndLine SentencesSequence LineNumber END) Subroutine.Rule = DECLAREStatement + SubroutineSentences; //DECLARE::= 'DECLARE' Identifier(',' Identifier) * DECLAREStatement.Rule = LineNumber + ToTerm("DECLARE") + IdentifierList + NewLine; SubroutineSentences.Rule = SentencesSequence; ENDStatement.Rule = LineNumber + ToTerm("END", "ENDPRG"); #endregion IdentifierList.Rule = MakePlusRule(IdentifierList, Identifier); //SentencesSequence ::= ProgramLine+ SentencesSequence.Rule = MakeStarRule(SentencesSequence, ProgramLine); //ProgramLine ::= EmptyLine | (LineNumber Sentence EndLine) //ProgramLine.Rule = EmptyLine | (LineNumber + Sentence + ReduceHere() + EndProgLine); ProgramLine.Rule = LineNumber + Sentence + EndProgLine; //EndProgLine.Rule = Comment.Q() + NewLine; EndProgLine.Rule = PreferShiftHere() + Comment.Q() + NewLine; //EmptyLine ::= LineNumber? EndLine //EmptyLine.Rule = LineNumber.Q() + NewLine; EmptyLine.Rule = Empty; //Sentence ::= (Comment | (Commands| Assignment | Branch | Loop) Comment?) //Sentence.Rule = Comment | ((ToTerm("END") + ReduceHere() | Commands | Assignment | Branch | FOR | ENDFOR) + Comment.Q() ); Sentence.Rule = ToTerm("END") | Commands | Assignment | Branch | FOR | ENDFOR | Comment; //Commands::= Command (';' Command) * Commands.Rule = Command + NextCommand; //Command ::= ALARM | ALARMAT | CALL | CLEAR | DALARM | DISABLE | ENABLE | //END | HANGUP | ONALARM | ONERROR | PHONE | PRINT | PRINTAT | REMOTEGET //| REMOTESET | RETURN | RUNMACRO | SETPRINTER | START | STOP | WAIT //| OPEN | CLOSE Command.Rule = ALARM | ALARMAT | CALL | CLEAR | DALARM | DISABLE | ENABLE | HANGUP | PHONE | PRINT | PRINTAT | REMOTEGET | REMOTESET | RETURN | RUNMACRO | SETPRINTER | START | STOP | WAIT | OPEN | CLOSE; NextCommand.Rule = MakeStarRule(NextCommand, CommandSeparator + Command); //TODO: ALARM, Waiting for information previously asked to TEMCO //ALARM ::= 'ALARM' Expression ComparisonOps Expression ',' Expression ',' StringLiteral* ALARM.Rule = "ALARM" + Expression + ComparisonOps + Expression + Comma + Expression + Comma + StringMessage; //DALARM ::= 'DALARM' Expression ',' NumberLiteral ',' StringLiteral+ DALARM.Rule = "DALARM" + Expression + Comma + Number + Comma + StringMessage; //DISABLE ::= 'DISABLE' Identifier PRINT.Rule = "PRINT" + PrintableKeywords + PrintableListOpt; PrintableKeywords.Rule = DATE | TIME | USERA | USERB | BEEP | PointIdentifier | EnclosedString; PrintableListOpt.Rule = MakeStarRule(PrintableListOpt, CommandSeparator + PrintableKeywords); //REMOTEGET ::= 'REMOTE-GET' Designator AssignOp RemoteDesignator //REMOTESET::= 'REMOTE-SET' RemoteDesignator AssignOp Designator REMOTEGET.Rule = "REMOTE-GET" + Designator + AssignOp + RemoteDesignator; REMOTESET.Rule = "REMOTE-SET" + RemoteDesignator + AssignOp + Designator; #region ENCODED COMMANDS PHONE.Rule = ToTerm("PHONE", "PHONE") + PhoneNumber; PRINTAT.Rule = ToTerm("PRINT-AT", "PRINT_AT") + (PANELS | ToTerm("ALL", "ALL")); PANELS.Rule = MakePlusRule(PANELS, PANEL); SETPRINTER.Rule = PrintEverything | PrintOnlyCommands; PrintEverything.Rule = ToTerm("SET-PRINTER", "SET_PRINTER") + (ToTerm("A", "PRT_A") | ToTerm("B", "PRT_B") | ToTerm("0", "PRT_0")); PrintOnlyCommands.Rule = "Set-Printer" + (ToTerm("a") | ToTerm("b") | ToTerm("0")); //ALARMAT ::= 'ALARM-AT' PANELS | 'ALL' ALARMAT.Rule = ToTerm("ALARM-AT", "ALARM_AT") + (PANELS | ToTerm("ALL", "ALL")); //RUNMACRO::= 'RUN-MACRO' SYSPRG RUNMACRO.Rule = ToTerm("RUN-MACRO", "RUN_MACRO") + SYSPRG; RUNMACRO.Precedence = 200; //CALL ::= 'CALL' PRG (AssignOp ARG (Space ',' Space ARG)* )? //TODO: CALL, Check if it works with expressions CALL.Rule = "CALL" + PRG + CALLARGS.Q(); CALLARGS.Rule = AssignOp + ARG + CALLARGSLIST; CALLARGSLIST.Rule = MakeStarRule(CALLARGSLIST, Comma + ARG); ARG.Rule = Designator | Expression; #region Decoded START.Rule = "START" + Designator; STOP.Rule = "STOP" + Designator; OPEN.Rule = "OPEN" + Designator; CLOSE.Rule = "CLOSE" + Designator; WAIT.Rule = "WAIT" + Expression; CLEAR.Rule = ToTerm("CLEAR", "CLEAR"); RETURN.Rule = ToTerm("RETURN", "RETURN"); HANGUP.Rule = ToTerm("HANGUP"); DISABLE.Rule = ToTerm("DISABLE", "DISABLEX") + Designator; ENABLE.Rule = ToTerm("ENABLE", "ENABLEX") + Designator; #endregion //Assignment ::= Designator AssignOp Expression LET.Rule = "LET"; Assignment.Rule = LET.Q() + Designator + AssignOp + Expression; //Branch ::= IF | IFTRUE | IFFALSE | GOSUB | GOTO | ON // IF::= 'IF' Expression 'THEN' IFCLAUSE('ELSE' IFCLAUSE) ? // IFTRUE::= 'IF+' Expression 'THEN' IFCLAUSE('ELSE' IFCLAUSE) ? // IFFALSE::= 'IF-' Expression 'THEN' IFCLAUSE('ELSE' IFCLAUSE) ? //IFCLAUSE::= (Sentence | LineNumber) Branch.Rule = IF | IFTRUE | IFFALSE | GOSUB | GOTO | ON | ONALARM | ONERROR; IF.Rule = "IF" + Expression + "THEN" + IFCLAUSE + ELSEOPT.Q(); IFTRUE.Rule = "IF+" + Expression + "THEN" + IFCLAUSE + ELSEOPT.Q(); IFFALSE.Rule = "IF-" + Expression + "THEN" + IFCLAUSE + ELSEOPT.Q(); //Added Function for testing purposes: Error found on a sample code PRG1 of BTUMETERrev22.prg IFCLAUSE.Rule = Commands | Function | Assignment | GOSELECTOR | LineNumber; //ELSEOPT.Rule = "ELSE" + IFCLAUSE; ELSEOPT.Rule = PreferShiftHere() + ToTerm("ELSE", "ELSE") + IFCLAUSE; #region JUMPS //ON ::= 'ON' IntegerTerm (GOTO | GOSUB) (',' LineNumber)* ON.Rule = ToTerm("ON") + Expression + GOSELECTOR + LineNumberListOpt; GOSELECTOR.Rule = GOTO | GOSUB; LineNumberListOpt.Rule = MakeStarRule(LineNumberListOpt, Comma + LineNumber); //GOSUB::= 'GOSUB' LineNumber GOSUB.Rule = "GOSUB" + LineNumber; //GOTO ::= 'GOTO' LineNumber GOTO.Rule = "GOTO" + LineNumber; ONALARM.Rule = ToTerm("ON-ALARM", "ON_ALARM") + LineNumber; ONERROR.Rule = ToTerm("ON-ERROR", "ON_ERROR") + LineNumber; #endregion #endregion //Loop::= FOR SentencesSequence ENDFOR //FOR::= 'FOR' LoopVariable AssignOp Integer 'TO' Integer('STEP' Integer) ? EndLine //ENDFOR::= 'NEXT'(LoopVariable(',' LoopVariable) *) ? //Loop.Rule = FOR + SentencesSequence | ENDFOR ; FOR.Rule = ToTerm("FOR") + LoopVariable + AssignOp + IntegerNumber + ToTerm("TO") + IntegerNumber + STEPFOR; STEPFOR.Rule = Empty | (ToTerm("STEP") + IntegerNumber); ENDFOR.Rule = ToTerm("NEXT") + LoopVariableList; LoopVariableList.Rule = MakePlusRule(LoopVariableList, Comma, LoopVariable); LogicOps.Rule = AND | OR | XOR; ArithmeticOps.Rule = SUM | SUB | MUL | DIV | IDIV | MOD | EXP; ComparisonOps.Rule = EQ | NEQ | GT | LT | LTE | GTE; UnaryOps.Rule = NOT; BinaryOps.Rule = ArithmeticOps | ComparisonOps | LogicOps; //LineNumber.Rule = IntegerNumber; //PointIdentifier ::= VARS | CONS | WRS | ARS | OUTS | INS | PRG | GRP | DMON | AMON | ARR PointIdentifier.Rule = VARS | PIDS | WRS | ARS | OUTS | INS | PRG | GRP | DMON | AMON | ARR | CON; //Designator ::= Identifier | PointIdentifier | LocalVariable Designator.Rule = PointIdentifier | Identifier | LocalVariable; RemoteDesignator.Rule = Designator; DayLiteral.Rule = SUN | MON | TUE | WED | THU | FRI | SAT; MonthLiteral.Rule = JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC; //DatesLiteral ::= MonthLiteral Space ([1-2] [1-9] | [3] [0-1]) DatesLiteral.Rule = MonthLiteral + DayNumber; //TimeLiteral ::= HH ':' MM ':' SS //TimeLiteral.Rule = HH + DDOT + MM + DDOT + SS; //Literal ::= NumbersLiteral | DatesLiteral | DaysLiteral | TimeLiteral Literal.Rule = IntegerNumber | Number | DatesLiteral | DayLiteral | TimeLiteral; #region 27 FUNCTIONS //27 Functions //Function::= ABS | AVG | CONPROP | CONRATE | CONRESET | DOM | DOW | DOY | //INT | INTERVAL | LN | LN1 | MAX | MIN | POWERLOSS | SCANS | SQR | STATUS | TBL | //TIME | TIMEOFF | TIMEON | WRON | WROFF | UNACK | USERA | USERB Function.Rule = ABS | AVG | CONPROP | CONRATE | CONRESET | COM1 | DOY | DOM | DOW | INT | INTERVAL | LN | LN1 | MAX | MIN | POWERLOSS | SCANS | SQR | STATUS | TBL | TIME | TIMEON | TIMEOFF | WRON | WROFF | UNACK | USERA | USERB; ABS.Rule = "ABS" + PARIZQ + Expression + PARDER; //INT ::= 'INT' PARIZQ Expression PARDER INT.Rule = ToTerm("INT", "_INT") + PARIZQ + Expression + PARDER; //INTERVAL::= 'INTERVAL' PARIZQ Expression PARDER INTERVAL.Rule = "INTERVAL" + PARIZQ + Expression + PARDER; //LN::= 'LN' PARIZQ Expression PARDER LN.Rule = "LN" + PARIZQ + Expression + PARDER; //LN1 ::= 'LN-1' PARIZQ Expression PARDER LN1.Rule = ToTerm("LN-1", "LN_1") + PARIZQ + Expression + PARDER; //SQR ::= 'SQR' PARIZQ Expression PARDER SQR.Rule = "SQR" + PARIZQ + Expression + PARDER; //STATUS ::= 'STATUS' PARIZQ Expression PARDER STATUS.Rule = ToTerm("STATUS", "_Status") + PARIZQ + Expression + PARDER; #region Functions with variable list of expressions, must add count of expressions as last token. //AVG ::= 'AVG' PARIZQ EXPRESSION ( Space ',' Space EXPRESSION )* PARDER AVG.Rule = "AVG" + PARIZQ + Expression + ExpressionListOpt + PARDER; //MAX ::= 'MAX' PARIZQ Expression (Space ',' Space Expression)*PARDER MAX.Rule = "MAX" + PARIZQ + Expression + ExpressionListOpt + PARDER; //MIN::= 'MIN' PARIZQ Expression (Space ',' Space Expression)*PARDER MIN.Rule = "MIN" + PARIZQ + Expression + ExpressionListOpt + PARDER; #endregion #region Functions not tested yet with enconding, PENDING FROM TEMCO //CONPROP ::= 'CONPROP' PARIZQ Ordinal ',' Expression PARDER CONPROP.Rule = "CONPROP" + PARIZQ + CONNUMBER + Comma + Expression + PARDER; //CONRATE ::= 'CONRATE' PARIZQ Ordinal ',' Expression PARDER RANGE CONRATE.Rule = "CONRATE" + PARIZQ + CONNUMBER + Comma + Expression + PARDER; //CONRESET ::= 'CONRESET' PARIZQ Ordinal ',' Expression PARDER RANGE CONRESET.Rule = "CONRESET" + PARIZQ + CONNUMBER + Comma + Expression + PARDER; //TBL ::= 'TBL' PARIZQ Expression ',' TABLENUMBER PARDER TBL.Rule = "TBL" + PARIZQ + Expression + Comma + TABLENUMBER + PARDER; //TIMEON ::= 'TIME-ON' PARIZQ Designator PARDER TIMEON.Rule = ToTerm("TIME-ON", "TIME_ON") + PARIZQ + Designator + PARDER; //TIMEOFF::= 'TIME-OFF' PARIZQ Designator PARDER TIMEOFF.Rule = ToTerm("TIME-OFF", "TIME_OFF") + PARIZQ + Designator + PARDER; //WRON ::= 'WR-ON' PARIZQ SYSPRG ',' TIMER PARDER WRON.Rule = ToTerm("WR-ON", "WR_ON") + PARIZQ + SYSPRG + Comma + TIMER + PARDER; //WROFF::= 'WR-OFF' PARIZQ SYSPRG ',' TIMER PARDER WROFF.Rule = ToTerm("WR-OFF", "WR_OFF") + PARIZQ + SYSPRG + Comma + TIMER + PARDER; //COM1 ::= 'COM1' PARIZQ BAUDRATE ',' PORT (CHARS+ | ',' EnclosedString) PARDER //BAUDRATE::= '9600' | '115200' //PORT::= '1' | 'Z' | 'Y' | 'X' //CHARS::= ','(PrintableAscii | ['] [A-Za-z] [']) //PrintableAscii::= '3'[2 - 9] | [4 - 9][0 - 9] | '1'[0 - 9][0 - 9] | '2'[0 - 4][0 - 9] | '25'[0 - 5] COM1.Rule = "COM1" + PARIZQ + BAUDRATE + Comma + PORT + ComParameters + PARDER; BAUDRATE.Rule = ToTerm("9600") | ToTerm("115200"); PORT.Rule = ToTerm("1") | ToTerm("Z") | ToTerm("Y") | ToTerm("X"); ComParameters.Rule = CHARS | EnclosedString; CHARS.Rule = MakePlusRule(CHARS, Comma + PrintableAscii); #endregion #endregion //EXPR.Rule = number | variable | FUN_CALL | stringLiteral | BINARY_EXPR // | "(" + EXPR + ")" | UNARY_EXPR; Expression.Rule = Function | Literal | Designator | UnaryExpression | BinaryExpression | EnclosableExpression; //UnaryExpression ::= UnaryOps Term UnaryExpression.Rule = UnaryOps + Expression; //BinaryExpression::= Expression BinaryOps Expression BinaryExpression.Rule = Expression + BinaryOps + Expression; //EnclosableExpression ::= ParIzq SimpleExpression ParDer EnclosableExpression.Rule = PARIZQ + Expression + PARDER; ExpressionListOpt.Rule = MakeStarRule(ExpressionListOpt, Comma + Expression); RegisterBracePair(PARIZQ.ToString(), PARDER.ToString()); RegisterBracePair("(", ")"); RegisterBracePair("[", "]"); RegisterBracePair("DECLARE", "END"); // 4. Operators precedence RegisterOperators(100, Associativity.Right, EXP); RegisterOperators(90, MUL, DIV, IDIV); RegisterOperators(80, MOD); RegisterOperators(70, SUM, SUB); RegisterOperators(60, LT, GT, LTE, GTE, EQ, NEQ); RegisterOperators(50, Associativity.Right, NOT); RegisterOperators(50, AND, OR, XOR); //// 5. Punctuation and transient terms MarkPunctuation(PARIZQ.ToString(), PARDER.ToString(), CommandSeparator.ToString()); PARIZQ.IsPairFor = PARDER; //MarkTransient(LineNumber); //MarkTransient(CodeLine, ProgramLine, // Term, Expression, // BinaryOperator, UnaryOperator, // AssignmentOperator,//FunctionOperator, // ParentExpression); LanguageFlags = //LanguageFlags.CreateAst | LanguageFlags.NewLineBeforeEOF; #region Define Keywords //GENERAL KEYWORDS MarkReservedWords("DECLARE", "END", "FOR", "NEXT", "TO", "STEP", "NOT"); //27 FUNCTIONS //9 Non parenthesis enclosed functions MarkReservedWords("DOY", "DOM", "DOW", "POWER-LOSS", "DATE", "TIME", "UNACK", "USER-A", "USER-B", "SCANS"); //18 Parenthesis enclosed functions MarkReservedWords("ABS", "AVG", "CONPROP", "CONRATE", "CONRESET", "INT", "INTERVAL"); MarkReservedWords("LN", "LN-1", "MAX", "MIN", "SQR", "STATUS", "TBL", "TIME-ON", "TIME-OFF"); MarkReservedWords("WR-ON", "WR-OFF", "COM1"); //Branches MarkReservedWords("IF", "IF+", "IF-", "ON-ALARM", "ON-ERROR", "ON", "GOTO", "GOSUB", "ELSE", "THEN"); //Commands MarkReservedWords("START", "STOP", "OPEN", "CLOSE", "LET", "ALARM", "ALARM-AT", "CALL", "ALL"); MarkReservedWords("CLEAR", "DALARM", "DISABLE", "ENABLE", "HANGUP", "PHONE", "PRINT", "PRINT-AT", "REMOTE-GET", "REMOTE-SET", "RETURN", "RUN-MACRO", "WAIT", "SET-PRINTER", "Set-Printer"); MarkReservedWords("AND", "OR", "XOR"); #endregion }
public Sql89Grammar() : 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 = new NumberLiteral("number"); var string_literal = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote); var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple"); //covers normal identifiers (abc) and quoted id's ([abc d], "abc d") var comma = ToTerm(","); var dot = ToTerm("."); var CREATE = ToTerm("CREATE"); var NULL = ToTerm("NULL"); var NOT = ToTerm("NOT"); var UNIQUE = ToTerm("UNIQUE"); var WITH = ToTerm("WITH"); var TABLE = ToTerm("TABLE"); 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 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"); //Non-terminals var Id = new NonTerminal("Id"); var stmt = new NonTerminal("stmt"); var createTableStmt = new NonTerminal("createTableStmt"); var createIndexStmt = new NonTerminal("createIndexStmt"); var alterStmt = new NonTerminal("alterStmt"); var dropTableStmt = new NonTerminal("dropTableStmt"); var dropIndexStmt = new NonTerminal("dropIndexStmt"); var selectStmt = new NonTerminal("selectStmt"); var insertStmt = new NonTerminal("insertStmt"); var updateStmt = new NonTerminal("updateStmt"); var deleteStmt = new NonTerminal("deleteStmt"); var fieldDef = new NonTerminal("fieldDef"); var fieldDefList = new NonTerminal("fieldDefList"); var nullSpecOpt = new NonTerminal("nullSpecOpt"); var typeName = new NonTerminal("typeName"); var typeSpec = new NonTerminal("typeSpec"); var typeParamsOpt = new NonTerminal("typeParams"); var constraintDef = new NonTerminal("constraintDef"); var constraintListOpt = new NonTerminal("constraintListOpt"); var constraintTypeOpt = new NonTerminal("constraintTypeOpt"); var idlist = new NonTerminal("idlist"); var idlistPar = new NonTerminal("idlistPar"); var uniqueOpt = new NonTerminal("uniqueOpt"); var orderList = new NonTerminal("orderList"); var orderMember = new NonTerminal("orderMember"); var orderDirOpt = new NonTerminal("orderDirOpt"); var withClauseOpt = new NonTerminal("withClauseOpt"); var alterCmd = new NonTerminal("alterCmd"); var insertData = new NonTerminal("insertData"); var intoOpt = new NonTerminal("intoOpt"); var assignList = new NonTerminal("assignList"); var whereClauseOpt = new NonTerminal("whereClauseOpt"); 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 inExpr = new NonTerminal("inExpr"); var parSelectStmt = new NonTerminal("parSelectStmt"); 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 funArgs = new NonTerminal("funArgs"); var inStmt = new NonTerminal("inStmt"); //BNF Rules this.Root = stmtList; stmtLine.Rule = stmt + semiOpt; semiOpt.Rule = Empty | ";"; stmtList.Rule = MakePlusRule(stmtList, stmtLine); //ID Id.Rule = MakePlusRule(Id, dot, Id_simple); stmt.Rule = createTableStmt | createIndexStmt | alterStmt | dropTableStmt | dropIndexStmt | selectStmt | insertStmt | updateStmt | deleteStmt | "GO"; //Create table createTableStmt.Rule = CREATE + TABLE + Id + "(" + fieldDefList + ")" + constraintListOpt; fieldDefList.Rule = MakePlusRule(fieldDefList, comma, fieldDef); fieldDef.Rule = Id + typeName + typeParamsOpt + nullSpecOpt; nullSpecOpt.Rule = NULL | NOT + NULL | Empty; typeName.Rule = ToTerm("BIT") | "DATE" | "TIME" | "TIMESTAMP" | "DECIMAL" | "REAL" | "FLOAT" | "SMALLINT" | "INTEGER" | "INTERVAL" | "CHARACTER" // MS SQL types: | "DATETIME" | "INT" | "DOUBLE" | "CHAR" | "NCHAR" | "VARCHAR" | "NVARCHAR" | "IMAGE" | "TEXT" | "NTEXT"; typeParamsOpt.Rule = "(" + number + ")" | "(" + number + comma + number + ")" | Empty; constraintDef.Rule = CONSTRAINT + Id + constraintTypeOpt; constraintListOpt.Rule = MakeStarRule(constraintListOpt, constraintDef); constraintTypeOpt.Rule = PRIMARY + KEY + idlistPar | UNIQUE + idlistPar | NOT + NULL + idlistPar | "Foreign" + KEY + idlistPar + "References" + Id + idlistPar; idlistPar.Rule = "(" + idlist + ")"; idlist.Rule = MakePlusRule(idlist, comma, Id); //Create Index createIndexStmt.Rule = CREATE + uniqueOpt + INDEX + Id + ON + Id + orderList + withClauseOpt; uniqueOpt.Rule = Empty | UNIQUE; orderList.Rule = MakePlusRule(orderList, comma, orderMember); orderMember.Rule = Id + orderDirOpt; orderDirOpt.Rule = Empty | "ASC" | "DESC"; withClauseOpt.Rule = Empty | WITH + PRIMARY | WITH + "Disallow" + NULL | WITH + "Ignore" + NULL; //Alter alterStmt.Rule = ALTER + TABLE + Id + alterCmd; alterCmd.Rule = ADD + COLUMN + fieldDefList + constraintListOpt | ADD + constraintDef | DROP + COLUMN + Id | DROP + CONSTRAINT + Id; //Drop stmts dropTableStmt.Rule = DROP + TABLE + Id; dropIndexStmt.Rule = DROP + INDEX + Id + ON + Id; //Insert stmt insertStmt.Rule = INSERT + intoOpt + Id + idlistPar + insertData; insertData.Rule = selectStmt | VALUES + "(" + exprList + ")"; intoOpt.Rule = Empty | INTO; //Into is optional in MSSQL //Update stmt updateStmt.Rule = UPDATE + Id + SET + assignList + whereClauseOpt; assignList.Rule = MakePlusRule(assignList, comma, assignment); assignment.Rule = Id + "=" + expression; //Delete stmt deleteStmt.Rule = DELETE + FROM + Id + whereClauseOpt; //Select stmt selectStmt.Rule = SELECT + selRestrOpt + selList + intoClauseOpt + fromClauseOpt + whereClauseOpt + groupClauseOpt + havingClauseOpt + orderClauseOpt; selRestrOpt.Rule = Empty | "ALL" | "DISTINCT"; selList.Rule = columnItemList | "*"; columnItemList.Rule = MakePlusRule(columnItemList, comma, columnItem); columnItem.Rule = columnSource + aliasOpt; aliasOpt.Rule = Empty | asOpt + Id; asOpt.Rule = Empty | AS; columnSource.Rule = aggregate | Id; 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 + idlist + joinChainOpt; joinChainOpt.Rule = Empty | joinKindOpt + JOIN + idlist + ON + Id + "=" + Id; joinKindOpt.Rule = Empty | "INNER" | "LEFT" | "RIGHT"; whereClauseOpt.Rule = Empty | "WHERE" + expression; groupClauseOpt.Rule = Empty | "GROUP" + BY + idlist; 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 | string_literal | number | funCall | tuple | parSelectStmt; // | inStmt; tuple.Rule = "(" + exprList + ")"; parSelectStmt.Rule = "(" + selectStmt + ")"; unExpr.Rule = unOp + term; unOp.Rule = NOT | "+" | "-" | "~"; binExpr.Rule = expression + binOp + expression; binOp.Rule = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic | "&" | "|" | "^" //bit | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>" | "AND" | "OR" | "LIKE" | NOT + "LIKE" | "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 + "(" + funArgs + ")"; funArgs.Rule = selectStmt | exprList; 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
TerminalSet _skipTokensInPreview = new TerminalSet(); //used in token preview for conflict resolution public AsmGrammar() { this.GrammarComments = "Asm grammar.\r\n"; #region Lexical structure NumberLiteral number = new NumberLiteral("NUMBER", NumberOptions.Default); IdentifierTerminal label = new IdentifierTerminal("LABEL", IdOptions.IsNotKeyword | IdOptions.AllowsEscapes | IdOptions.CanStartWithEscape); //RegexBasedTerminal label = new RegexBasedTerminal("LABEL", "[A-Za-z_][A-Za-z_0-9]+"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", ";", "#"); this.NonGrammarTerminals.Add(SingleLineComment); KeyTerm COMMA = this.ToTerm(",", "COMMA"); KeyTerm PLUS = this.ToTerm("+", "PLUS"); KeyTerm MINUS = this.ToTerm("-", "MINUS"); KeyTerm TIMES = this.ToTerm("*", "TIMES"); ///<remarks>Bracket Square Left</remarks> KeyTerm BSL = this.ToTerm("["); ///<remarks>Bracket Square Right</remarks> KeyTerm BSR = this.ToTerm("]"); ///<remarks>Bracket Left</remarks> KeyTerm BL = this.ToTerm("("); ///<remarks>Bracket Right</remarks> KeyTerm BR = this.ToTerm(")"); this.MarkPunctuation("(", ")", "[", "]"); #endregion Lexical structure #region NonTerminals var line = new NonTerminal("line"); var directive = new NonTerminal("directive"); var label_def = new NonTerminal("label_def"); var label_def_opt = new NonTerminal("label_def_opt"); var instruction = new NonTerminal("instruction"); var instruction_opt = new NonTerminal("instruction_opt"); #region Registers var r8 = new NonTerminal("Reg8"); var r16 = new NonTerminal("Reg16"); var r32 = new NonTerminal("Reg32"); var r64 = new NonTerminal("Reg64"); #endregion Registers var m8 = new NonTerminal("Mem8"); var m16 = new NonTerminal("Mem16"); var m32 = new NonTerminal("Mem32"); var m64 = new NonTerminal("Mem64"); var mem_op = new NonTerminal("MemOp"); //var mem_scale_index_32 = new NonTerminal("ScaleIdx32"); var mem_scale_index_64 = new NonTerminal("ScaleIdx64"); //var mem_scale_index_bracket_32 = new NonTerminal("ScaleIdxBrac32"); var mem_scale_index_bracket_64 = new NonTerminal("ScaleIdxBrac64"); // var mem_base_32 = new NonTerminal("Base32"); var mem_base_64 = new NonTerminal("Base64"); var mem_scale = new NonTerminal("Scale"); var mem_index_32 = new NonTerminal("Idx32"); var mem_index_64 = new NonTerminal("Idx64"); var mem_ptr = new NonTerminal("ptr"); var mem_disp = new NonTerminal("Disp"); var mnemomic_add = new NonTerminal("add"); var mnemomic_jmp = new NonTerminal("jmp"); #endregion NonTerminals #region operators, punctuation and delimiters this.RegisterOperators(1, "+", "-"); this.RegisterOperators(2, "*"); #endregion #region comments this.MarkPunctuation(";", ",", "(", ")", "[", "]", ":"); //this.MarkTransient(namespace_member_declaration, member_declaration); //this.AddTermsReportGroup("assignment", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="); //this.AddToNoReportGroup("var", "const", "new"); #endregion #region Rules this.Root = line; line.Rule = directive; line.Rule |= label_def_opt + instruction_opt; label_def_opt.Rule = this.Empty; label_def_opt.Rule |= label_def; label_def.Rule = label + ":"; label_def.Rule |= label + "::"; instruction_opt.Rule = this.Empty; instruction_opt.Rule |= instruction; #region Memory Operand m8.Rule = "byte" + mem_ptr + BSL + mem_op + BSR; m16.Rule = "word" + mem_ptr + BSL + mem_op + BSR; m32.Rule = "dword" + mem_ptr + BSL + mem_op + BSR; m64.Rule = "qword" + mem_ptr + BSL + mem_op + BSR; mem_ptr.Rule = this.Empty; mem_ptr.Rule |= "ptr"; mem_op.Rule = mem_base_64 + PLUS + mem_scale_index_bracket_64 + mem_disp; //ABC mem_op.Rule |= mem_base_64 + mem_disp + PLUS + mem_scale_index_bracket_64; //ACB //mem_op.Rule |= mem_disp + PLUS + mem_base_64 + PLUS + mem_scale_index_bracket_64; //CAB //mem_op.Rule |= mem_disp + PLUS + mem_scale_index_bracket_64 + PLUS + mem_base_64; //CBA //PreferShiftHere() + //mem_op.Rule |= mem_scale_index_bracket_64; //B //mem_op.Rule |= mem_base_64; not needed //mem_op.Rule |= mem_disp; //C //mem_op.Rule |= mem_base_64 + PLUS + mem_scale_index_bracket_64; //AB //mem_op.Rule |= mem_scale_index_bracket_64 + PLUS + mem_base_64; //BA //mem_op.Rule |= mem_base_64 + PLUS + mem_disp; //AC //mem_op.Rule |= mem_disp + PLUS + mem_base_64; //CA mem_scale_index_bracket_64.Rule = BL + mem_scale_index_64 + BR; mem_scale_index_bracket_64.Rule |= mem_scale_index_64; mem_scale_index_64.Rule = mem_scale + TIMES + mem_index_64; mem_scale_index_64.Rule |= mem_index_64 + TIMES + mem_scale; mem_scale_index_64.Rule |= mem_index_64; mem_base_64.Rule = r64; mem_scale.Rule = this.ToTerm("0"); mem_scale.Rule |= "1"; mem_scale.Rule |= "2"; mem_scale.Rule |= "4"; mem_scale.Rule |= "8"; mem_index_32.Rule = r32; mem_index_64.Rule = r64; mem_disp.Rule = PLUS + this.CustomActionHere(this.findTimesChar) + number; mem_disp.Rule |= MINUS + this.CustomActionHere(this.findTimesChar) + number; #endregion Memory Operand r8.Rule = this.ToTerm("al"); r8.Rule |= "ah"; r16.Rule = this.ToTerm("ax"); r32.Rule = this.ToTerm("eax"); r64.Rule = this.ToTerm("rax") | "rbx" | "rcx" | "rdx"; #region Mnemonics instruction.Rule = mnemomic_add; instruction.Rule |= mnemomic_jmp; mnemomic_add.Rule = "add" + r8 + COMMA + r8; mnemomic_add.Rule |= "add" + r16 + COMMA + r16; mnemomic_add.Rule |= "add" + m16 + COMMA + r16; mnemomic_add.Rule |= "add" + r16 + COMMA + m16; mnemomic_jmp.Rule = "jmp" + r8; mnemomic_jmp.Rule |= "jmp" + label; mnemomic_jmp.Rule |= "jmp" + m32; #endregion Mnemonics #region Directive directive.Rule = this.ToTerm("align"); directive.Rule |= "proc"; #endregion Directive #endregion Rules label.ValidateToken += this.label_ValidateToken; }
public PCodeGrammar() : base(false) { // ReSharper disable InconsistentNaming this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; var integerLiteral = new NumberLiteral("INTEGER"); integerLiteral.Options |= NumberOptions.IntOnly; integerLiteral.DefaultIntTypes = new[] { TypeCode.Int64 }; integerLiteral.AddPrefix("0x", NumberOptions.Hex); var floatLiteral = new NumberLiteral("FLOAT") { DefaultIntTypes = new[] { TypeCode.Double }, }; var stringLiteral = new StringLiteral("STRING", "\"", StringOptions.AllowsLineBreak | StringOptions.AllowsOctalEscapes | StringOptions.AllowsXEscapes); var name = new IdentifierTerminal("NAME", IdOptions.IsNotKeyword); var comment = new CommentTerminal("comment", "#", "\n"); var comma = ToTerm(",", "comma"); var colon = ToTerm(":", "colon"); var staticLiteral = new NonTerminal("STATIC") { Rule = this.ToTerm("Activation") | "AdjustLevel" | "Application" | "ClickableTracker" | "Contact" | "Context" | "CurNode" | "CurrentState" | "curStateTracker" | "dependencyVal" | "Encounter" | "Encounter2" | "EncounterDef" | "EncounterTemplate" | "Entity" | "Forever" | "GenData" | "GenInstanceColumn" | "GenInstanceColumnCount" | "GenInstanceCount" | "GenInstanceData" | "GenInstanceNumber" | "GenInstanceRow" | "GenInstanceRowCount" | "HP" | "HPMax" | "iLevelINTERNAL_LayerFSM" | "IsDisabled" | "IsSelectable" | "IsVisible" | "me" | "Mission" | "MissionClickable" | "MissionDef" | "Mod" | "ModDef" | "MouseX" | "MouseY" | "MouseZ" | "NewTreeLevel" | "NumTeamMembers" | "ParentValue" | "pathOldValue" | "Player" | "Power" | "PowerDef" | "PowerMax" | "PowerVolumeData" | "Prediction" | "RowData" | "Self" | "Source" | "SpawnLocation" | "TableValue" | "Target" | "TargetEnt" | "TeamHP" | "TeamHPMax" | "Volume", }; var PROGRAM = new NonTerminal("PROGRAM"); var LINE = new NonTerminal("LINE"); var STATEMENT = new NonTerminal("STATEMENT"); var VALUE = new NonTerminal("VALUE"); var LABEL = new NonTerminal("LABEL"); var LABEL_OPT = new NonTerminal("LABEL_OPT"); var STATEMENT_OPT = new NonTerminal("STATEMENT_OPT"); var COMMENT_OPT = new NonTerminal("COMMENT_OPT"); var BINARY = new NonTerminal("BINARY"); var OP_NON = new NonTerminal("OP_NON"); var OP_INT = new NonTerminal("OP_INT"); var OP_FLT = new NonTerminal("OP_FLT"); var OP_INS = new NonTerminal("OP_INS"); var OP_FLS = new NonTerminal("OP_FLS"); var OP_VEC = new NonTerminal("OP_VEC"); var OP_VC4 = new NonTerminal("OP_VC4"); var OP_MAT = new NonTerminal("OP_MAT"); var OP_QAT = new NonTerminal("OP_QAT"); var OP_STR = new NonTerminal("OP_STR"); var OP_FIL = new NonTerminal("OP_FIL"); var OP_ENT = new NonTerminal("OP_ENT"); var OP_PTR = new NonTerminal("OP_PTR"); var OP_ADD = new NonTerminal("OP_ADD"); var OP_SUB = new NonTerminal("OP_SUB"); var OP_NEG = new NonTerminal("OP_NEG"); var OP_MUL = new NonTerminal("OP_MUL"); var OP_DIV = new NonTerminal("OP_DIV"); var OP_EXP = new NonTerminal("OP_EXP"); var OP_BAN = new NonTerminal("OP_BAN"); var OP_BOR = new NonTerminal("OP_BOR"); var OP_BNT = new NonTerminal("OP_BNT"); var OP_BXR = new NonTerminal("OP_BXR"); var OP_O_P = new NonTerminal("OP_O_P"); var OP_C_P = new NonTerminal("OP_C_P"); var OP_O_B = new NonTerminal("OP_O_B"); var OP_C_B = new NonTerminal("OP_C_B"); var OP_EQU = new NonTerminal("OP_EQU"); var OP_LES = new NonTerminal("OP_LES"); var OP_NGR = new NonTerminal("OP_NGR"); var OP_GRE = new NonTerminal("OP_GRE"); var OP_NLE = new NonTerminal("OP_NLE"); var OP_FUN = new NonTerminal("OP_FUN"); var OP_IDS = new NonTerminal("OP_IDS"); var OP_S_V = new NonTerminal("OP_S_V"); var OP_COM = new NonTerminal("OP_COM"); var OP_AND = new NonTerminal("OP_AND"); var OP_ORR = new NonTerminal("OP_ORR"); var OP_NOT = new NonTerminal("OP_NOT"); var OP_IF_ = new NonTerminal("OP_IF_"); var OP_ELS = new NonTerminal("OP_ELS"); var OP_ELF = new NonTerminal("OP_ELF"); var OP_EIF = new NonTerminal("OP_EIF"); var OP_RET = new NonTerminal("OP_RET"); var OP_RZ_ = new NonTerminal("OP_RZ_"); var OP_J__ = new NonTerminal("OP_J__"); var OP_JZ_ = new NonTerminal("OP_JZ_"); var OP_CON = new NonTerminal("OP_CON"); var OP_STM = new NonTerminal("OP_STM"); var OP_RP_ = new NonTerminal("OP_RP_"); var OP_OBJ = new NonTerminal("OP_OBJ"); var OP_L_M = new NonTerminal("OP_L_M"); var OP_L_S = new NonTerminal("OP_L_S"); this.Root = PROGRAM; VALUE.Rule = integerLiteral | stringLiteral; PROGRAM.Rule = MakePlusRule(PROGRAM, LINE); LINE.Rule = LABEL_OPT + STATEMENT_OPT + COMMENT_OPT + NewLine; LABEL_OPT.Rule = LABEL | Empty; STATEMENT_OPT.Rule = STATEMENT | Empty; COMMENT_OPT.Rule = comment | Empty; STATEMENT.Rule = OP_NON | OP_INT | OP_FLT | OP_INS | OP_FLS | OP_VEC | OP_VC4 | /*OP_MAT | OP_QAT |*/ OP_STR | /*OP_FIL |*/ /*OP_ENT | OP_PTR |*/ OP_ADD | OP_SUB | OP_NEG | OP_MUL | OP_DIV | OP_EXP | OP_BAN | OP_BOR | OP_BNT | OP_BXR | OP_O_P | OP_C_P | OP_O_B | OP_C_B | OP_EQU | OP_LES | OP_NGR | OP_GRE | OP_NLE | OP_FUN | OP_IDS | OP_S_V | OP_COM | OP_AND | OP_ORR | OP_NOT | OP_IF_ | OP_ELS | OP_ELF | OP_EIF | OP_RET | OP_RZ_ | OP_J__ | OP_JZ_ | OP_CON | OP_STM | OP_RP_ | OP_OBJ | OP_L_M | OP_L_S; LABEL.Rule = name + ":"; BINARY.Rule = "binary"; OP_NON.Rule = "null"; OP_INT.Rule = "int" + integerLiteral; OP_FLT.Rule = "float" + floatLiteral; OP_INS.Rule = "ints" + stringLiteral; // todo: fixme OP_FLS.Rule = "floats" + stringLiteral; // todo: fixme OP_VEC.Rule = "vec3" + stringLiteral; // todo: fixme OP_VC4.Rule = "vec4" + stringLiteral; // todo: fixme OP_STR.Rule = "str" + stringLiteral; OP_ADD.Rule = "add"; OP_SUB.Rule = "sub"; OP_NEG.Rule = "neg"; OP_MUL.Rule = "mul"; OP_DIV.Rule = "div"; OP_EXP.Rule = "exp"; OP_BAN.Rule = BINARY + "and"; OP_BOR.Rule = BINARY + "or"; OP_BNT.Rule = BINARY + "not"; OP_BXR.Rule = BINARY + "xor"; OP_O_P.Rule = "("; OP_C_P.Rule = ")"; OP_O_B.Rule = "["; OP_C_B.Rule = "]"; OP_EQU.Rule = "equals"; OP_LES.Rule = "less"; OP_NGR.Rule = "notgreater"; OP_GRE.Rule = "greater"; OP_NLE.Rule = "notless"; OP_FUN.Rule = "call" + stringLiteral; OP_IDS.Rule = "ident" + stringLiteral; OP_S_V.Rule = "static" + staticLiteral; OP_COM.Rule = "comma"; OP_AND.Rule = "and"; OP_ORR.Rule = "or"; OP_NOT.Rule = "not"; OP_IF_.Rule = "if"; OP_ELS.Rule = "else"; OP_ELF.Rule = "elif"; OP_EIF.Rule = "endif"; OP_RET.Rule = "return"; OP_RZ_.Rule = "retifzero"; OP_J__.Rule = "j" + name; OP_JZ_.Rule = "jz" + name; OP_CON.Rule = "continue"; OP_STM.Rule = ";"; OP_RP_.Rule = "rootpath" + stringLiteral; OP_OBJ.Rule = "objpath" + stringLiteral; OP_L_M.Rule = "locm" + stringLiteral; // todo: fixme OP_L_S.Rule = "locs" + stringLiteral; // todo: fixme this.MarkPunctuation(",", ":"); this.MarkTransient( VALUE, LABEL_OPT, STATEMENT_OPT, COMMENT_OPT, staticLiteral); // ReSharper restore InconsistentNaming }
public ExcelFormulaGrammar() : base(false) { #region 1-Terminals #region Symbols and operators var comma = ToTerm(","); var colon = ToTerm(":"); var semicolon = ToTerm(";"); var OpenParen = ToTerm("("); var CloseParen = ToTerm(")"); var CloseSquareParen = ToTerm("]"); var OpenSquareParen = ToTerm("["); var exclamationMark = ToTerm("!"); var CloseCurlyParen = ToTerm("}"); var OpenCurlyParen = ToTerm("{"); var mulop = ToTerm("*"); var plusop = ToTerm("+"); var divop = ToTerm("/"); var minop = ToTerm("-"); var concatop = ToTerm("&"); var expop = ToTerm("^"); // Intersect op is a single space, which cannot be parsed normally so we need an ImpliedSymbolTerminal // Attention: ImpliedSymbolTerminal seems to break if you assign it a priority, and it's default priority is low var intersectop = new ImpliedSymbolTerminal(GrammarNames.TokenIntersect); var percentop = ToTerm("%"); var gtop = ToTerm(">"); var eqop = ToTerm("="); var ltop = ToTerm("<"); var neqop = ToTerm("<>"); var gteop = ToTerm(">="); var lteop = ToTerm("<="); #endregion #region Literals var BoolToken = new RegexBasedTerminal(GrammarNames.TokenBool, "TRUE|FALSE"); BoolToken.Priority = TerminalPriority.Bool; var NumberToken = new NumberLiteral(GrammarNames.TokenNumber, NumberOptions.None); NumberToken.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt }; var TextToken = new StringLiteral(GrammarNames.TokenText, "\"", StringOptions.AllowsDoubledQuote | StringOptions.AllowsLineBreak); var ErrorToken = new RegexBasedTerminal(GrammarNames.TokenError, "#NULL!|#DIV/0!|#VALUE!|#NAME\\?|#NUM!|#N/A"); var RefErrorToken = ToTerm("#REF!", GrammarNames.TokenRefError); #endregion #region Functions var UDFToken = new RegexBasedTerminal(GrammarNames.TokenUDF, @"(_xll\.)?[\w\\.]+\("); UDFToken.Priority = TerminalPriority.UDF; var ExcelRefFunctionToken = new RegexBasedTerminal(GrammarNames.TokenExcelRefFunction, "(INDEX|OFFSET|INDIRECT)\\("); ExcelRefFunctionToken.Priority = TerminalPriority.ExcelRefFunction; var ExcelConditionalRefFunctionToken = new RegexBasedTerminal(GrammarNames.TokenExcelConditionalRefFunction, "(IF|CHOOSE)\\("); ExcelConditionalRefFunctionToken.Priority = TerminalPriority.ExcelRefFunction; var ExcelFunction = new RegexBasedTerminal(GrammarNames.ExcelFunction, "(" + String.Join("|", excelFunctionList) + ")\\("); ExcelFunction.Priority = TerminalPriority.ExcelFunction; // Using this instead of Empty allows a more accurate trees var EmptyArgumentToken = new ImpliedSymbolTerminal(GrammarNames.TokenEmptyArgument); #endregion #region References and names var VRangeToken = new RegexBasedTerminal(GrammarNames.TokenVRange, "[$]?[A-Z]{1,4}:[$]?[A-Z]{1,4}"); var HRangeToken = new RegexBasedTerminal(GrammarNames.TokenHRange, "[$]?[1-9][0-9]*:[$]?[1-9][0-9]*"); const string CellTokenRegex = "[$]?[A-Z]{1,4}[$]?[1-9][0-9]*"; var CellToken = new RegexBasedTerminal(GrammarNames.TokenCell, CellTokenRegex); CellToken.Priority = TerminalPriority.CellToken; const string NamedRangeRegex = @"[A-Za-z\\_][\w\.]*"; var NamedRangeToken = new RegexBasedTerminal(GrammarNames.TokenNamedRange, NamedRangeRegex); NamedRangeToken.Priority = TerminalPriority.NamedRange; // To prevent e.g. "A1A1" being parsed as 2 celltokens var NamedRangeCombinationToken = new RegexBasedTerminal(GrammarNames.TokenNamedRangeCombination, "(TRUE|FALSE|" + CellTokenRegex + ")" + NamedRangeRegex); NamedRangeCombinationToken.Priority = TerminalPriority.NamedRangeCombination; const string mustBeQuotedInSheetName = @"\(\);{}#""=<>&+\-*/\^%, "; const string notSheetNameChars = @"'*\[\]\\:/?"; //const string singleQuotedContent = @"\w !@#$%^&*()\-\+={}|:;<>,\./\?" + "\\\""; //const string sheetRegEx = @"(([\w\.]+)|('([" + singleQuotedContent + @"]|'')+'))!"; const string normalSheetName = "[^" + notSheetNameChars + mustBeQuotedInSheetName + "]+"; const string quotedSheetName = "([^" + notSheetNameChars + "]|'')+"; const string sheetRegEx = "((" + normalSheetName + ")|('" + quotedSheetName + "'))!"; var SheetToken = new RegexBasedTerminal(GrammarNames.TokenSheet, sheetRegEx); SheetToken.Priority = TerminalPriority.SheetToken; var multiSheetRegex = String.Format("(({0}:{0})|('{1}:{1}'))!", normalSheetName, quotedSheetName); var MultipleSheetsToken = new RegexBasedTerminal(GrammarNames.TokenMultipleSheets, multiSheetRegex); MultipleSheetsToken.Priority = TerminalPriority.MultipleSheetsToken; var FileToken = new RegexBasedTerminal(GrammarNames.TokenFileNameNumeric, "[0-9]+"); FileToken.Priority = TerminalPriority.FileToken;; const string quotedFileSheetRegex = @"'\[\d+\]" + quotedSheetName + "'!"; var QuotedFileSheetToken = new RegexBasedTerminal(GrammarNames.TokenFileSheetQuoted, quotedFileSheetRegex); QuotedFileSheetToken.Priority = TerminalPriority.QuotedFileToken; var ReservedNameToken = new RegexBasedTerminal(GrammarNames.TokenReservedName, @"_xlnm\.[a-zA-Z_]+"); ReservedNameToken.Priority = TerminalPriority.ReservedName; var DDEToken = new RegexBasedTerminal(GrammarNames.TokenDDE, @"'([^']|'')+'"); #endregion #region Punctuation MarkPunctuation(exclamationMark); MarkPunctuation(OpenParen, CloseParen); MarkPunctuation(OpenSquareParen, CloseSquareParen); MarkPunctuation(OpenCurlyParen, CloseCurlyParen); #endregion #endregion #region 2-NonTerminals // Most nonterminals are first defined here, so they can be used anywhere in the rules // Otherwise you can only use nonterminals that have been defined previously var Argument = new NonTerminal(GrammarNames.Argument); var Arguments = new NonTerminal(GrammarNames.Arguments); var ArrayColumns = new NonTerminal(GrammarNames.ArrayColumns); var ArrayConstant = new NonTerminal(GrammarNames.ArrayConstant); var ArrayFormula = new NonTerminal(GrammarNames.ArrayFormula); var ArrayRows = new NonTerminal(GrammarNames.ArrayRows); var Bool = new NonTerminal(GrammarNames.Bool); var Cell = new NonTerminal(GrammarNames.Cell); var Constant = new NonTerminal(GrammarNames.Constant); var ConstantArray = new NonTerminal(GrammarNames.ConstantArray); var DynamicDataExchange = new NonTerminal(GrammarNames.DynamicDataExchange); var EmptyArgument = new NonTerminal(GrammarNames.EmptyArgument); var Error = new NonTerminal(GrammarNames.Error); var File = new NonTerminal(GrammarNames.File); var Formula = new NonTerminal(GrammarNames.Formula); var FormulaWithEq = new NonTerminal(GrammarNames.FormulaWithEq); var FunctionCall = new NonTerminal(GrammarNames.FunctionCall); var FunctionName = new NonTerminal(GrammarNames.FunctionName); var HRange = new NonTerminal(GrammarNames.HorizontalRange); var InfixOp = new NonTerminal(GrammarNames.TransientInfixOp); var MultipleSheets = new NonTerminal(GrammarNames.MultipleSheets); var NamedRange = new NonTerminal(GrammarNames.NamedRange); var Number = new NonTerminal(GrammarNames.Number); var PostfixOp = new NonTerminal(GrammarNames.TransientPostfixOp); var Prefix = new NonTerminal(GrammarNames.Prefix); var PrefixOp = new NonTerminal(GrammarNames.TransientPrefixOp); var QuotedFileSheet = new NonTerminal(GrammarNames.QuotedFileSheet); var Reference = new NonTerminal(GrammarNames.Reference); //var ReferenceFunction = new NonTerminal(GrammarNames.ReferenceFunction); var ReferenceItem = new NonTerminal(GrammarNames.TransientReferenceItem); var ReferenceFunctionCall = new NonTerminal(GrammarNames.ReferenceFunctionCall); var RefError = new NonTerminal(GrammarNames.RefError); var RefFunctionName = new NonTerminal(GrammarNames.RefFunctionName); var ReservedName = new NonTerminal(GrammarNames.ReservedName); var Sheet = new NonTerminal(GrammarNames.Sheet); var Start = new NonTerminal(GrammarNames.TransientStart); var Text = new NonTerminal(GrammarNames.Text); var UDFName = new NonTerminal(GrammarNames.UDFName); var UDFunctionCall = new NonTerminal(GrammarNames.UDFunctionCall); var Union = new NonTerminal(GrammarNames.Union); var VRange = new NonTerminal(GrammarNames.VerticalRange); #endregion #region 3-Rules #region Base rules Root = Start; Start.Rule = FormulaWithEq | Formula | ArrayFormula ; MarkTransient(Start); ArrayFormula.Rule = OpenCurlyParen + eqop + Formula + CloseCurlyParen; FormulaWithEq.Rule = eqop + Formula; Formula.Rule = Reference | Constant | FunctionCall | ConstantArray | OpenParen + Formula + CloseParen | ReservedName ; //MarkTransient(Formula); ReservedName.Rule = ReservedNameToken; Constant.Rule = Number | Text | Bool | Error ; Text.Rule = TextToken; Number.Rule = NumberToken; Bool.Rule = BoolToken; Error.Rule = ErrorToken; RefError.Rule = RefErrorToken; #endregion #region Functions FunctionCall.Rule = FunctionName + Arguments + CloseParen | PrefixOp + Formula | Formula + PostfixOp | Formula + InfixOp + Formula ; FunctionName.Rule = ExcelFunction; Arguments.Rule = MakeStarRule(Arguments, comma, Argument); //Arguments.Rule = Argument | Argument + comma + Arguments; EmptyArgument.Rule = EmptyArgumentToken; Argument.Rule = Formula | EmptyArgument; //MarkTransient(Argument); PrefixOp.Rule = ImplyPrecedenceHere(Precedence.UnaryPreFix) + plusop | ImplyPrecedenceHere(Precedence.UnaryPreFix) + minop; MarkTransient(PrefixOp); InfixOp.Rule = expop | mulop | divop | plusop | minop | concatop | gtop | eqop | ltop | neqop | gteop | lteop; MarkTransient(InfixOp); //PostfixOp.Rule = ImplyPrecedenceHere(Precedence.UnaryPostFix) + percentop; // ImplyPrecedenceHere doesn't seem to work for this rule, but postfix has such a high priority shift will nearly always be the correct action PostfixOp.Rule = PreferShiftHere() + percentop; MarkTransient(PostfixOp); #endregion #region References Reference.Rule = ReferenceItem | ReferenceFunctionCall | OpenParen + Reference + PreferShiftHere() + CloseParen | Prefix + ReferenceItem | DynamicDataExchange ; ReferenceFunctionCall.Rule = Reference + colon + Reference | Reference + intersectop + Reference | OpenParen + Union + CloseParen | RefFunctionName + Arguments + CloseParen //| ConditionalRefFunctionName + Arguments + CloseParen ; RefFunctionName.Rule = ExcelRefFunctionToken | ExcelConditionalRefFunctionToken; Union.Rule = MakePlusRule(Union, comma, Reference); ReferenceItem.Rule = Cell | NamedRange | VRange | HRange | RefError | UDFunctionCall ; MarkTransient(ReferenceItem); UDFunctionCall.Rule = UDFName + Arguments + CloseParen; UDFName.Rule = UDFToken; VRange.Rule = VRangeToken; HRange.Rule = HRangeToken; //ConditionalRefFunctionName.Rule = ExcelConditionalRefFunctionToken; QuotedFileSheet.Rule = QuotedFileSheetToken; Sheet.Rule = SheetToken; MultipleSheets.Rule = MultipleSheetsToken; Cell.Rule = CellToken; File.Rule = OpenSquareParen + FileToken + CloseSquareParen; DynamicDataExchange.Rule = File + exclamationMark + DDEToken; NamedRange.Rule = NamedRangeToken | NamedRangeCombinationToken; Prefix.Rule = Sheet | File + Sheet | File + exclamationMark | QuotedFileSheet | MultipleSheets | File + MultipleSheets; #endregion #region Arrays ConstantArray.Rule = OpenCurlyParen + ArrayColumns + CloseCurlyParen; ArrayColumns.Rule = MakePlusRule(ArrayColumns, semicolon, ArrayRows); ArrayRows.Rule = MakePlusRule(ArrayRows, comma, ArrayConstant); ArrayConstant.Rule = Constant | PrefixOp + Number | RefError; #endregion #endregion #region 5-Operator Precedence // Some of these operators are neutral associative instead of left associative, // but this ensures a consistent parse tree. As a lot of code is "hardcoded" onto the specific // structure of the parse tree, we like consistency. RegisterOperators(Precedence.Comparison, Associativity.Left, eqop, ltop, gtop, lteop, gteop, neqop); RegisterOperators(Precedence.Concatenation, Associativity.Left, concatop); RegisterOperators(Precedence.Addition, Associativity.Left, plusop, minop); RegisterOperators(Precedence.Multiplication, Associativity.Left, mulop, divop); RegisterOperators(Precedence.Exponentiation, Associativity.Left, expop); RegisterOperators(Precedence.UnaryPostFix, Associativity.Left, percentop); RegisterOperators(Precedence.Union, Associativity.Left, comma); RegisterOperators(Precedence.Intersection, Associativity.Left, intersectop); RegisterOperators(Precedence.Range, Associativity.Left, colon); //RegisterOperators(Precedence.ParameterSeparator, comma); #endregion }
public Gramatica_Import_DATABASE() : base(caseSensitive: false) { #region Expresiones_Regulares StringLiteral CADENA = new StringLiteral("Cadena", "\""); NumberLiteral NUMERO = new NumberLiteral("Numero"); var DECIMAL = new RegexBasedTerminal("Decimal", "[0-9]+'.'[0-9]+"); var RDATE = new RegexBasedTerminal("Date", "\'[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\'"); var RTIME = new RegexBasedTerminal("Time", "\'[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\'"); IdentifierTerminal IDENTIFICADOR = new IdentifierTerminal("Identificador"); CommentTerminal comentarioLinea = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n"); //si viene una nueva linea se termina de reconocer el comentario. CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/"); CommentTerminal ruta_import = new CommentTerminal("ruta_import", "${", "}$"); CommentTerminal CONT_DATA_IMPORT = new CommentTerminal("CONT_DATA_IMPORT", "$", "$"); #endregion #region Terminales KeyTerm DOLLAR = ToTerm("$"), MENQUE = ToTerm("<"), MAYQUE = ToTerm(">"), IGUAL = ToTerm("="), CORIZQ = ToTerm("["), CORDER = ToTerm("]"), COMA = ToTerm(","), PUNTO = ToTerm("."), LLAVIZQ = ToTerm("{"), LLAVDER = ToTerm("}"), RNAME = ToTerm("\"NAME\""), RDATA = ToTerm("\"DATA\""), RCQL_TYPE = ToTerm("\"CQL-TYPE\""), RCOLUMNS = ToTerm("\"COLUMNS\""), RTYPE = ToTerm("\"TYPE\""), RPK = ToTerm("\"PK\""), RATTRS = ToTerm("\"ATTRS\""), RINSTR = ToTerm("\"INSTR\""), RPARAMETERS = ToTerm("\"PARAMETERS\""), RAS = ToTerm("\"AS\""), RFALSE = ToTerm("FALSE"), RTRUE = ToTerm("TRUE"), RIN = ToTerm("IN"), ROUT = ToTerm("OUT"), RNULL = ToTerm("NULL"); #endregion #region No_Terminales NonTerminal S = new NonTerminal("S"), NAME = new NonTerminal("NAME"), VALOR = new NonTerminal("VALOR"), DATA2 = new NonTerminal("DATA2"), DATA3 = new NonTerminal("DATA3"), DATA4 = new NonTerminal("DATA4"), DATA5 = new NonTerminal("DATA5"), TABLA = new NonTerminal("TABLA"), OBJETO = new NonTerminal("OBJETO"), PROCEDURE = new NonTerminal("PROCEDURE"), CQL_TYPE = new NonTerminal("CQL_TYPE"), COLUMNS = new NonTerminal("COLUMNS"), DATA_DATA = new NonTerminal("DATA_DATA"), DATA_DATA2 = new NonTerminal("DATA_DATA2"), DATA_DATA3 = new NonTerminal("DATA_DATA3"), DATA_DATA4 = new NonTerminal("DATA_DATA4"), DATA_DATA5 = new NonTerminal("DATA_DATA5"), DATA_DATA6 = new NonTerminal("DATA_DATA6"), COLUMNS2 = new NonTerminal("COLUMNS2"), COLUMNS3 = new NonTerminal("COLUMNS3"), COLUMNS4 = new NonTerminal("COLUMNS4"), COLUMN = new NonTerminal("COLUMN"), TYPE = new NonTerminal("TYPE"), PK = new NonTerminal("PK"), MAPA = new NonTerminal("MAPA"), MAPA2 = new NonTerminal("MAPA2"), MAPA3 = new NonTerminal("MAPA3"), LISTAS = new NonTerminal("LISTAS"), LISTAS2 = new NonTerminal("LISTAS2"), LISTAS3 = new NonTerminal("LISTAS3"), ATTRIBUTES = new NonTerminal("ATTRIBUTES"), ATTRIBUTES2 = new NonTerminal("ATTRIBUTES2"), ATTRIBUTES3 = new NonTerminal("ATTRIBUTES3"), ATTRIBUTES4 = new NonTerminal("ATTRIBUTES4"), ATTRIBUTE = new NonTerminal("ATTRIBUTE"), PARAMETERS = new NonTerminal("PARAMETERS"), PARAMETERS2 = new NonTerminal("PARAMETERS2"), PARAMETERS3 = new NonTerminal("PARAMETERS3"), PARAMETERS4 = new NonTerminal("PARAMETERS4"), PARAMETER = new NonTerminal("PARAMETER"), INSTR = new NonTerminal("INSTR"), BOOL = new NonTerminal("BOOL"), AS = new NonTerminal("AS"), IN_OUT = new NonTerminal("IN_OUT"); ; #endregion #region GRAMATICA S.Rule = DATA5; NAME.Rule = RNAME + IGUAL + VALOR; DATA5.Rule = DATA5 + COMA + DATA2 | DATA2 | ruta_import | Empty; DATA5.ErrorRule = SyntaxError + COMA; DATA2.Rule = MENQUE + DATA3 + MAYQUE; DATA3.Rule = DATA3 + COMA + DATA4 | DATA4; DATA4.Rule = CQL_TYPE | NAME | TABLA | OBJETO | PROCEDURE; TABLA.Rule = COLUMNS | DATA_DATA; CQL_TYPE.Rule = RCQL_TYPE + IGUAL + VALOR; COLUMNS.Rule = RCOLUMNS + IGUAL + CORIZQ + COLUMNS4 + CORDER; COLUMNS4.Rule = COLUMNS4 + COMA + COLUMNS2 | COLUMNS2 | Empty; COLUMNS2.Rule = MENQUE + COLUMNS3 + MAYQUE; COLUMNS3.Rule = COLUMNS3 + COMA + COLUMN | COLUMN; COLUMN.Rule = NAME | TYPE | PK; TYPE.Rule = RTYPE + IGUAL + VALOR; PK.Rule = RPK + IGUAL + BOOL; DATA_DATA.Rule = RDATA + IGUAL + CORIZQ + DATA_DATA2 + CORDER; DATA_DATA2.Rule = ruta_import | DATA_DATA3 | Empty; DATA_DATA3.Rule = DATA_DATA3 + COMA + DATA_DATA4 | DATA_DATA4; DATA_DATA4.Rule = MENQUE + DATA_DATA5 + MAYQUE; DATA_DATA5.Rule = DATA_DATA5 + COMA + DATA_DATA6 | DATA_DATA6; DATA_DATA6.Rule = VALOR + IGUAL + VALOR; OBJETO.Rule = ATTRIBUTES; ATTRIBUTES.Rule = RATTRS + IGUAL + CORIZQ + ATTRIBUTES2 + CORDER; ATTRIBUTES2.Rule = ATTRIBUTES2 + COMA + ATTRIBUTES3 | ATTRIBUTES3 | Empty; ATTRIBUTES3.Rule = MENQUE + ATTRIBUTES4 + MAYQUE; ATTRIBUTES4.Rule = ATTRIBUTES4 + COMA + ATTRIBUTE | ATTRIBUTE; ATTRIBUTE.Rule = NAME | TYPE; PROCEDURE.Rule = PARAMETERS | INSTR; INSTR.Rule = RINSTR + IGUAL + CONT_DATA_IMPORT; PARAMETERS.Rule = RPARAMETERS + IGUAL + CORIZQ + PARAMETERS2 + CORDER; PARAMETERS2.Rule = PARAMETERS2 + COMA + PARAMETERS3 | PARAMETERS3 | Empty; PARAMETERS3.Rule = MENQUE + PARAMETERS4 + MAYQUE; PARAMETERS3.ErrorRule = SyntaxError + MAYQUE; PARAMETERS4.Rule = PARAMETERS4 + COMA + PARAMETER | PARAMETER; PARAMETER.Rule = NAME | TYPE | AS; AS.Rule = RAS + IGUAL + IN_OUT; IN_OUT.Rule = RIN | ROUT; BOOL.Rule = RTRUE | RFALSE; VALOR.Rule = CADENA | DECIMAL | IDENTIFICADOR | MAPA | LISTAS | NUMERO | RTRUE | RFALSE | RTIME | RNULL | RDATE; #region LISTAS y MAPAS LISTAS.Rule = CORIZQ + LISTAS2 + CORDER; LISTAS2.Rule = LISTAS2 + COMA + LISTAS3 | LISTAS3 | Empty; LISTAS3.Rule = VALOR; MAPA.Rule = MENQUE + MAPA2 + MAYQUE; MAPA2.Rule = MAPA2 + COMA + MAPA3 | MAPA3 | Empty; MAPA3.Rule = VALOR + IGUAL + VALOR; #endregion #region Preferencias this.Root = S; #endregion #endregion }
protected virtual void ConstructExpressions() { Number = new NumberLiteral("Number", NumberOptions.Default, (c, node) => node.AstNode = new PrimitiveValue(ConvertNumber(node.Token.Value))) { DefaultIntTypes = new[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt } }; SingleQuotedString = new StringLiteral( "SingleQuotedString", "'", StringOptions.NoEscapes, ToActualNodeCreator(n => new PrimitiveValue(n.Token.Value)) ); DoubleQuotedString = new StringLiteral( "DoubleQuotedString", "\"", StringOptions.NoEscapes, ToActualNodeCreator(n => new StringWithInterpolation((string)n.Token.Value)) ); Boolean = NonTerminal("Boolean", n => new PrimitiveValue(n.FindTokenAndGetText() == "true")); Literal = Transient <IAstExpression>("Literal"); Expression = Transient <IAstExpression>("Expression"); ExpressionSafeForAnyPosition = Transient <IAstExpression>("ExpressionSafeForAnyPosition"); ExpressionInBrackets = Transient <IAstExpression>("ExpressionInBrackets"); ThisExpression = NonTerminal("This", n => new AstThisExpression()); BinaryExpression = NonTerminal("BinaryExpression", node => new BinaryExpression( (IAstExpression)node.ChildNodes[0].AstNode, (IAstMethodReference)node.ChildNodes[1].AstNode, (IAstExpression)node.ChildNodes[2].AstNode )); BinaryOperator = NonTerminalWithSpecificType <IAstMethodReference>("BinaryOperator", node => new AstUnknownMethod(node.FindTokenAndGetText())); CommaSeparatedExpressionListStar = NonTerminal("CommaSeparatedExpressionListStar", node => node.ChildAsts <IAstExpression>()); ListInitializer = NonTerminal("ListInitializer", node => new AstListInitializer(AstElementsInStarChild(node, 0).Cast <IAstExpression>())); ObjectInitializer = NonTerminal("ObjectInitializer", node => new ObjectInitializer(AstElementsInStarChild(node, 0))); ObjectInitializerElementList = new NonTerminal("ObjectInitializerElementList"); ObjectInitializerElement = NonTerminal("ObjectInitializerElement", node => new ObjectInitializerEntry( node.ChildNodes[0].Token.Text, (IAstElement)node.ChildAst(1) )); MemberAccessOrCallExpression = NonTerminal("MemberAccessOrCall", node => { var path = (IEnumerable <IAstElement>)node.ChildAst(1); var result = (IAstExpression)node.ChildAst(0); foreach (var item in path) { var identifier = item as IdentifierExpression; if (identifier != null) { result = new MemberExpression(result, identifier.Name); continue; } var call = item as CallExpression; if (call != null) { result = new CallExpression(new MemberExpression(result, ((IdentifierExpression)call.Callee).Name), call.Arguments); continue; } var indexer = item as IndexerExpression; if (indexer != null) { result = new IndexerExpression(new MemberExpression(result, ((IdentifierExpression)indexer.Target).Name), indexer.Arguments); continue; } throw new NotImplementedException("LightGrammar: MemberAccessOrCall path element is " + item + "."); } return(result); }); MemberPathRoot = Transient <IAstElement>("MemberPathRoot"); MemberPathElement = Transient <IAstElement>("MemberPathElement"); MemberPathElementListPlus = NonTerminal("MemberPathElementListPlus", node => node.ChildAsts <IAstElement>()); SimpleCallExpression = NonTerminal("Call (Simple)", node => (IAstExpression) new CallExpression(new IdentifierExpression(node.Child(0).Token.Text), AstElementsInStarChild(node, 1).Cast <IAstExpression>())); SimpleIdentifierExpression = NonTerminal("Identifier", node => new IdentifierExpression(node.Child(0).Token.Text)); SimpleIndexerExpression = NonTerminal("Indexer (Simple)", node => new IndexerExpression(node.ChildAst(SimpleIdentifierExpression), AstElementsInStarChild(node, 1))); NewExpression = NonTerminal( "NewExpression", node => new AstNewExpression( node.ChildAst(TypeReference), node.Child(2).ChildAst(CommaSeparatedExpressionListStar) ?? Enumerable.Empty <IAstExpression>(), node.Child(3).ChildAst(ObjectInitializer) ) ); ArgumentList = Transient <IEnumerable <IAstExpression> >("ArgumentList"); LambdaExpression = NonTerminal("Lambda", node => { var parametersRaw = node.FirstChild.FirstChild.AstNode; var parameters = parametersRaw as IEnumerable <AstParameterDefinition> ?? new[] { (AstParameterDefinition)parametersRaw }; return((IAstExpression) new AstLambdaExpression(parameters, (IAstElement)node.ChildAst(1))); }); }
// Selz: End Customed terminal name public FluidGrammar() : base(caseSensitive: true) { // Terminals var OutputStart = ToTerm("{{"); var OutputEnd = ToTerm("}}"); var TagStart = ToTerm("{%"); var TagEnd = ToTerm("%}"); var Dot = ToTerm("."); var Comma = ToTerm(","); var Pipe = ToTerm("|"); var Colon = ToTerm(":"); var StringLiteralSingle = new StringLiteral("string1", "'", StringOptions.AllowsDoubledQuote | StringOptions.AllowsAllEscapes); var StringLiteralDouble = new StringLiteral("string2", "\"", StringOptions.AllowsDoubledQuote | StringOptions.AllowsAllEscapes); var Number = new NumberLiteral("number", NumberOptions.AllowSign); var True = ToTerm("true"); var False = ToTerm("false"); var FilterComma = ToTerm(","); // Non-terminals this.Root = Statement; // Statements Statement.Rule = Output | Tag; Output.Rule = OutputStart + Expression + OutputEnd; Tag.Rule = TagStart + KnownTags + TagEnd; // Members MemberAccess.Rule = Identifier + MemberAccessSegmentOpt; MemberAccessSegmentOpt.Rule = MakeStarRule(MemberAccessSegmentOpt, MemberAccessSegment); MemberAccessSegment.Rule = MemberAccessSegmentIdentifier | MemberAccessSegmentIndexer; MemberAccessSegmentIdentifier.Rule = Dot + Identifier; MemberAccessSegmentIndexer.Rule = "[" + Expression + "]"; // Expression Expression.Rule = Term + FilterList; Expression.Rule |= BinaryExpression; Term.Rule = MemberAccess | StringLiteralSingle | StringLiteralDouble | Number | Boolean; BinaryExpression.Rule = Expression + BinaryOperator + Expression; BinaryOperator.Rule = ToTerm("+") | ToTerm("-") | ToTerm("*") | ToTerm("/") | ToTerm("%") | ToTerm("==") | ToTerm(">") | ToTerm("<") | ToTerm(">=") | ToTerm("<=") | ToTerm("<>") | ToTerm("!=") | ToTerm("contains") | ToTerm("and") | ToTerm("or"); Boolean.Rule = True | False; // Operators RegisterOperators(10, "*", "/", "%"); RegisterOperators(9, "+", "-"); RegisterOperators(8, "==", ">", "<", ">=", "<=", "<>", "!=", "contains"); RegisterOperators(5, "and"); RegisterOperators(4, "or"); // Selz: Start intialize the rule of Cutom Terminal var By = ToTerm("by"); // Selz: Support <% include filename %> IdentifierList.Rule = MakeStarRule(IdentifierList, Identifier); // Selz: Support <% paginate Colltion by Setting.PageSize query: "queryname" PaginateArguments.Rule = Expression; PaginateArguments.Rule |= Expression + By + Expression; PaginateArguments.Rule |= Expression + FilterArgument; PaginateArguments.Rule |= Expression + By + Expression + FilterArgument; // Selz: Support {% shortcut "banner" "btn-settings-shortcut" "above-right" %} ExpressionList.Rule = MakeStarRule(ExpressionList, Expression); StringLiteralAll.Rule = StringLiteralSingle | StringLiteralDouble; PipeStringLiteral.Rule = Pipe + StringLiteralAll; // Selz: Support {% form 'search' | 'form-search' %} FormArguments.Rule = StringLiteralAll; FormArguments.Rule |= StringLiteralAll + Pipe + ExpressionList; // Selz: {% editable_region footer true %} EditableRegionArguments.Rule = Identifier; EditableRegionArguments.Rule |= Identifier + Expression; // Selz: End intialize the rule of Cutom Terminal // Filters FilterList.Rule = MakeStarRule(FilterList, Filter); Filter.Rule = Pipe + Identifier; Filter.Rule |= Pipe + Identifier + Colon + FilterArguments; Filter.Rule |= Pipe + Identifier + FilterComma + FilterArguments; FilterArguments.Rule = MakeListRule(FilterArguments, Comma, FilterArgument); FilterArgument.Rule = Identifier + Colon + Term; FilterArgument.Rule |= Term; // Known Tags var EndIf = ToTerm("endif"); // Selz: Else is a terminal now // var Else = ToTerm("else"); var EndUnless = ToTerm("endunless"); var EndCase = ToTerm("endcase"); var EndFor = ToTerm("endfor"); var EndCapture = ToTerm("endcapture"); var Continue = ToTerm("continue"); var Break = ToTerm("break"); var Comment = ToTerm("comment"); var EndComment = ToTerm("endcomment"); var Raw = ToTerm("raw"); var EndRaw = ToTerm("endraw"); KnownTags.Rule = If | EndIf | Elsif | ElseIf | Else | Unless | EndUnless | Case | EndCase | When | For | EndFor | Continue | Break | Comment | EndComment | Raw | EndRaw | Cycle | Assign | Capture | EndCapture | Increment | Decrement | Include; If.Rule = ToTerm("if") + Expression; Unless.Rule = ToTerm("unless") + Expression; Elsif.Rule = ToTerm("elsif") + Expression; Case.Rule = ToTerm("case") + Expression; When.Rule = ToTerm("when") + TermList; TermList.Rule = MakePlusRule(TermList, ToTerm("or"), Term); For.Rule = ToTerm("for") + Identifier + ToTerm("in") + ForSource + ForOptions; ForSource.Rule = MemberAccess | Range; Range.Rule = ToTerm("(") + RangeIndex + ToTerm("..") + RangeIndex + ToTerm(")"); RangeIndex.Rule = Number | MemberAccess; ForOptions.Rule = MakeStarRule(ForOptions, ForOption); ForOption.Rule = ForLimit | ForOffset | ToTerm("reversed"); // Selz: Support syntax of offset: settings.offset, limit: settings.pagesize ForOffset.Rule = ToTerm("offset") + Colon + Expression; ForLimit.Rule = ToTerm("limit") + Colon + Expression; // Selz: Support else if expression syntax Else.Rule = ToTerm("else"); Else.Rule |= ToTerm("else") + Identifier + Expression; // Selz: Support elseif expression syntax ElseIf.Rule = ToTerm("elseif") + Expression; // Selz: Support <% assign varible = filename %> syntax Assign.Rule = ToTerm("assign") + Identifier + ToTerm("=") + Expression; Assign.Rule |= ToTerm("assign") + Identifier + ToTerm("=") + Expression + ";"; // Selz: Support <% include filename syntax %> Include.Rule = ToTerm("include") + FileIdentifier; Cycle.Rule = ToTerm("cycle") + Term + Colon + CycleArguments; Cycle.Rule |= ToTerm("cycle") + CycleArguments; CycleArguments.Rule = MakePlusRule(CycleArguments, Comma, Term); Increment.Rule = ToTerm("increment") + Identifier; Decrement.Rule = ToTerm("decrement") + Identifier; Capture.Rule = ToTerm("capture") + Identifier; IncludeAssignments.Rule = (IncludeAssignments + Comma + IncludeAssignment) | IncludeAssignment; IncludeAssignment.Rule = Identifier + Colon + Term; // Selz: Make else into keyword list MarkPunctuation( "[", "]", ":", "|", "=", "if", "elsif", "elseif", "else", "unless", "assign", "capture", "increment", "decrement", "case", "for", "in", "(", ")", "..", "when", "cycle", "limit", "offset", "include", "with" ); MarkPunctuation(Dot, TagStart, TagEnd, OutputStart, OutputEnd, Colon, By, FilterComma); // Selz: Make String All and By to the node not show in the result MarkTransient(Statement, KnownTags, ForSource, RangeIndex, BinaryOperator, ForOption, Term, StringLiteralAll); }
public Sintactico() : base(caseSensitive: false) { #region Regex #endregion #region Terminales /*-------- COMENTARIOS EN LÍNEA --------*/ var LineComment = new CommentTerminal("LineComment", ">>", "\n", "\r\n"); /*-------- COMENTARIOS EN BLOQUE --------*/ var BlockComment = new CommentTerminal("BlockComment", "<-", "->"); /*-------- NUMERO --------*/ var Real = new NumberLiteral("tkREAL", NumberOptions.AllowSign); /*-------- CADENA --------*/ var Cadena = new StringLiteral("tkSTR", "\""); /*-------- CARACTER --------*/ var Caracter = new StringLiteral("tkCHAR", "'", StringOptions.IsChar); /*-------- PUNTUACION --------*/ var SEMICOLON = ToTerm(";", "SEMICOLON"); var COMMA = ToTerm(",", "COMMA"); var DOT = ToTerm(".", "DOT"); var COLON = ToTerm(":", "COLON"); /*-------- AGRUPACION --------*/ var PARIZQ = ToTerm("(", "PARIZQ"); var PARDER = ToTerm(")", "PARDER"); var LLVIZQ = ToTerm("{", "LLVIZQ"); var LLVDER = ToTerm("}", "LLVDER"); var CORIZQ = ToTerm("[", "CORIZQ"); var CORDER = ToTerm("]", "CORDER"); /*-------- BINARIOS --------*/ var MAS = ToTerm("+", "MAS"); var MENOS = ToTerm("-", "MENOS"); var POR = ToTerm("*", "POR"); var DIVISION = ToTerm("/", "DIVISION"); var POTENCIA = ToTerm("^", "POTENCIA"); var AND = ToTerm("&&", "AND"); var OR = ToTerm("||", "OR"); var IGUAL = ToTerm("==", "IGUAL"); var DIFERENTE = ToTerm("!=", "DIFERENTE"); var MAYOR_IGUAL = ToTerm(">=", "MAYOR_IGUAL"); var MENOR_IGUAL = ToTerm("<=", "MENOR_IGUAL"); var MAYOR = ToTerm(">", "MAYOR"); var MENOR = ToTerm("<", "MENOR"); var ASIGNACION = ToTerm("=", "ASIGNACION"); /*-------- UNARIOS --------*/ var INCREMENTO = ToTerm("++", "INCREMENTO"); var DECREMENTO = ToTerm("--", "DECREMENTO"); var NOT = ToTerm("!", "NOT"); /*-------- RESERVADAS --------*/ /*-------- DEFINICION DE TIPOS --------*/ var INT = ToTerm("int", "tkINT"); var CHAR = ToTerm("char", "tkCHAR"); var STRING = ToTerm("string", "tkSTR"); var DOUBLE = ToTerm("double", "tkDOUBLE"); var BOOL = ToTerm("bool", "tkBOOL"); var VOID = ToTerm("void", "tkVOID"); var ARRAY = ToTerm("array", "tkARR"); ConstantTerminal CSTBOOL = new ConstantTerminal("CSTBOOL"); CSTBOOL.Add("true", true); CSTBOOL.Add("verdadero", true); CSTBOOL.Add("falso", false); CSTBOOL.Add("false", false); /*-------- CLASES --------*/ var PUBLICO = ToTerm("publico", "tkVISIBLE"); var PRIVADO = ToTerm("privado", "tkVISIBLE"); var OVERRIDE = ToTerm("override", "tkOVERR"); var IMPORTAR = ToTerm("importar", "IMPORTAR"); var NEW = ToTerm("new", "NEW"); var MAIN = ToTerm("main", "MAIN"); var RETURN = ToTerm("return", "RETURN"); var CLASE = ToTerm("clase", "CLASE"); /*-------- NATIVA --------*/ var PRINT = ToTerm("print", "PRINT"); var SHOW = ToTerm("show", "SHOW"); var ADDFIGURE = ToTerm("addfigure", "ADDFIG"); var CIRCLE = ToTerm("circle", "CIRCLE"); var TRI = ToTerm("triangle", "TRIAN"); var SQA = ToTerm("square", "SQA"); var LINE = ToTerm("line", "LINE"); var FIGURE = ToTerm("figure", "FIGURE"); /*-------- CONDICIONALES Y LOOPS --------*/ var IF = ToTerm("if", "IF"); var ELSE = ToTerm("else", "ELSE"); var FOR = ToTerm("for", "FOR"); var REPEAT = ToTerm("repeat", "REPEAT"); var WHILE = ToTerm("while", "WHILE"); var COMPROBAR = ToTerm("comprobar", "COMPROBAR"); var CASO = ToTerm("caso", "CASO"); var DEFECTO = ToTerm("defecto", "DEFECTO"); var SALIR = ToTerm("salir", "SALIR"); var HACER = ToTerm("hacer", "HACER"); var MIENTRAS = ToTerm("mientras", "MIENTRAS"); var CONTINUAR = ToTerm("continuar", "CONTINUAR"); /*-------- IDENTIFICADORES --------*/ var Identificador = new IdentifierTerminal("tkID"); var Variable = new IdentifierTerminal("tkVAR"); #endregion #region No terminales /*PRODUCCIONES INICIALES*/ NonTerminal INICIO = new NonTerminal("INICIO"), CLASE_STA = new NonTerminal("CLASE_STA"), CLASE_STA_LIST = new NonTerminal("CLASE_LST"), CLASE_STA_BODY = new NonTerminal("CLASE_BODY"), IMPORTAR_STA = new NonTerminal("IMPORTAR_STA"), IMPORTAR_STA_LIST = new NonTerminal("IMP_LST"), FUNCION = new NonTerminal("FUNCION"), METODO = new NonTerminal("METODO"), INSTRUCCION = new NonTerminal("INSTRUCCION"), INSTRUCCION_LIST = new NonTerminal("INST_LST"), VISIBILIDAD = new NonTerminal("VISIBILIDAD"), MAIN_STA = new NonTerminal("MAIN_STA"), OVER_STA = new NonTerminal("OVER_STA"), /*Contiene los tipos de datos utilizados*/ DATATYPE = new NonTerminal("DATATYPE"), /*Contiene una lista de variables*/ VARLIST = new NonTerminal("VARLIST"), /*Declara las variables normales*/ DECLARACION = new NonTerminal("DECLARACION"), /*Asigna variables normales*/ ASSIGNMENT = new NonTerminal("ASSIGNMENT"), /*Establece la dimensión de los arreglos*/ DIMENSION = new NonTerminal("DIMENSION"), DIMENSION_LIST = new NonTerminal("DIMENSION_LIST"), /*Establece el contenido de los arreglos al declararse*/ ARRCONTENT = new NonTerminal("ARRCONTENT"), ARRCONTENT_LIST = new NonTerminal("ARRCONTENT_LIST"), /*Específica la forma de las operaciones*/ OPER = new NonTerminal("OPER"), /*Lista de operaciones :v*/ OPERLIST = new NonTerminal("OPERLIST"), /*Producciones para if*/ IF_STA = new NonTerminal("IF_STA"), ELSE_STA = new NonTerminal("ELSE_STA"), /*Producciones para un FOR*/ FOR_STA = new NonTerminal("FOR_STA"), FOR_CND = new NonTerminal("FOR_CND"), /*Producciones para un REPEAT*/ REPEAT_STA = new NonTerminal("REPEAT_STA"), WHILE_STA = new NonTerminal("WHILE_STA"), /*Producciones para un SWITCH*/ SWITCH = new NonTerminal("SWITCH"), CASE_LST = new NonTerminal("CASE_LST"), CASE = new NonTerminal("CASE"), /*Producciones para un DO-WHILE*/ DO = new NonTerminal("DO"), /*Lista de parametros al declarar funcion/metodo*/ PAR_LST = new NonTerminal("PAR_LST"), PAR = new NonTerminal("PAR"), CALL = new NonTerminal("CALL"), /*Produccion para un RETURN STATEMENT*/ RTN_STA = new NonTerminal("RTN_STA"), /*Produccion para las figuras*/ FIGURES = new NonTerminal("FIGURES"); #endregion #region Producciones INICIO.Rule = MakePlusRule(INICIO, CLASE_STA); #region CLASE //ESTRUCTURA BASICA DE UN CLASE CLASE_STA.Rule = CLASE + Identificador + IMPORTAR_STA + LLVIZQ + CLASE_STA_LIST + LLVDER; //IMPORTACIONES IMPORTAR_STA_LIST.Rule = MakeListRule(IMPORTAR_STA_LIST, COMMA, Identificador); IMPORTAR_STA.Rule = IMPORTAR + IMPORTAR_STA_LIST | Empty; //CUERPO DE UNA CLASE, VARIABLES GLOBALES, FUNCIONES Y METODOS CLASE_STA_LIST.Rule = MakeStarRule(CLASE_STA_LIST, CLASE_STA_BODY); CLASE_STA_BODY.Rule = MAIN_STA | FUNCION | METODO | DECLARACION + SEMICOLON; //VISIBILIDAD DE UNA FUNCION, METODO O VARIABLE GLOBAL VISIBILIDAD.Rule = PUBLICO | PRIVADO | Empty; //SOBRECARGA DE MÉTODOS OVER_STA.Rule = OVERRIDE | Empty; //LISTA DE INSTRUCCIONES VÁLIDAS DENTRO DE FUNCIONES Y MÉTODOS INSTRUCCION_LIST.Rule = MakeStarRule(INSTRUCCION_LIST, INSTRUCCION); NonTerminal NATIVA = new NonTerminal("NATIVA") { Rule = PRINT + PARIZQ + OPER + PARDER + SEMICOLON | SHOW + PARIZQ + OPERLIST + PARDER + SEMICOLON }; INSTRUCCION.Rule = DECLARACION + SEMICOLON | ASSIGNMENT + SEMICOLON | IF_STA | FOR_STA | REPEAT_STA | WHILE_STA | SWITCH | DO | CONTINUAR + SEMICOLON | SALIR + SEMICOLON | RTN_STA + SEMICOLON | NATIVA | FIGURES; #endregion #region PARAMETROS PAR_LST.Rule = MakeListRule(PAR_LST, COMMA, PAR, TermListOptions.AllowEmpty); PAR.Rule = DATATYPE + Variable | DATATYPE + ARRAY + Variable + DIMENSION_LIST; // CALL.Rule = Variable + PARIZQ + OPERLIST + PARDER | Variable + PARIZQ + PARDER; #endregion #region FUNCION FUNCION.Rule = VISIBILIDAD + Identificador + DATATYPE + OVER_STA + PARIZQ + PAR_LST + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER | VISIBILIDAD + Identificador + ARRAY + DATATYPE + DIMENSION_LIST + OVER_STA + PARIZQ + PAR_LST + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; #endregion #region METODO METODO.Rule = VISIBILIDAD + Identificador + VOID + OVER_STA + PARIZQ + PAR_LST + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; #endregion #region RETURN STATEMENT RTN_STA.Rule = RETURN + ASSIGNMENT; #endregion #region MAIN MAIN_STA.Rule = MAIN + PARIZQ + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; #endregion #region DECLARACION, ASIGNACION Y GET DE VARIABLES Y ARREGLOS DATATYPE.Rule = INT | CHAR | STRING | DOUBLE | BOOL | Identificador; //var, var , var VARLIST.Rule = MakeListRule(VARLIST, COMMA, Variable, TermListOptions.PlusList); //[oper][oper][oper] DIMENSION_LIST.Rule = MakePlusRule(DIMENSION_LIST, DIMENSION); DIMENSION.Rule = CORIZQ + OPER + CORDER; //{3,3} {{3,3},{3,3}} {{{3,3},{3,3}},{{3,3},{3,3}}} ARRCONTENT_LIST.Rule = MakeListRule(ARRCONTENT_LIST, COMMA, ARRCONTENT, TermListOptions.PlusList); ARRCONTENT.Rule = LLVIZQ + ARRCONTENT_LIST + LLVDER | LLVIZQ + OPERLIST + LLVDER; //int var, var, var; //int var, var = oper; //int array var, var, var[oper][oper]; //int array var, var, var[oper][oper] = {{3,3},{3,3}}; DECLARACION.Rule = VISIBILIDAD + DATATYPE + VARLIST | VISIBILIDAD + DATATYPE + VARLIST + ASIGNACION + OPER | VISIBILIDAD + DATATYPE + ARRAY + VARLIST + DIMENSION_LIST | VISIBILIDAD + DATATYPE + ARRAY + VARLIST + DIMENSION_LIST + ASIGNACION + ARRCONTENT; //var = oper; //var[oper] = oper; ASSIGNMENT.Rule = Variable + ASIGNACION + OPER | Variable + DIMENSION_LIST + ASIGNACION + OPER | OPER; #endregion #region OPERACIONES OPER.Rule = /*TRES NODOS*/ OPER + MAS + OPER | OPER + MENOS + OPER | OPER + POR + OPER | OPER + DIVISION + OPER | OPER + POTENCIA + OPER | OPER + IGUAL + OPER | OPER + DIFERENTE + OPER | OPER + MAYOR + OPER | OPER + MENOR + OPER | OPER + MAYOR_IGUAL + OPER | OPER + MENOR_IGUAL + OPER | OPER + DOT + OPER | OPER + OR + OPER | OPER + AND + OPER /*DOS NODOS*/ | NOT + OPER | OPER + INCREMENTO | OPER + DECREMENTO | NEW + Identificador + PARIZQ + PARDER | Variable + DIMENSION_LIST /*UN NODO*/ | PARIZQ + OPER + PARDER | Real | Caracter | Cadena | CSTBOOL | Variable | CALL; OPERLIST.Rule = MakeListRule(OPERLIST, COMMA, OPER); #endregion #region IF IF_STA.Rule = IF + PARIZQ + OPER + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER + ELSE_STA; ELSE_STA.Rule = ELSE + LLVIZQ + INSTRUCCION_LIST + LLVDER | ELSE + IF_STA | Empty; #endregion #region FOR NonTerminal FOR_DEC = new NonTerminal("FOR_DEC") { Rule = INT + Variable + ASIGNACION + OPER | Variable + ASIGNACION + OPER }; NonTerminal FOR_ASS = new NonTerminal("FOR_ASS") { Rule = Variable + ASIGNACION + OPER | OPER }; FOR_STA.Rule = FOR + PARIZQ + FOR_CND + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; FOR_CND.Rule = FOR_DEC + SEMICOLON + OPER + SEMICOLON + FOR_ASS; #endregion #region REPEAT REPEAT_STA.Rule = REPEAT + PARIZQ + OPER + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; #endregion #region WHILE WHILE_STA.Rule = WHILE + PARIZQ + OPER + PARDER + LLVIZQ + INSTRUCCION_LIST + LLVDER; #endregion #region COMPROBAR SWITCH.Rule = COMPROBAR + PARIZQ + OPER + PARDER + LLVIZQ + CASE_LST + LLVDER; CASE_LST.Rule = MakePlusRule(CASE_LST, CASE); CASE.Rule = CASO + OPER + COLON + INSTRUCCION_LIST | DEFECTO + COLON + INSTRUCCION_LIST; #endregion #region DO-WHILE DO.Rule = HACER + LLVIZQ + INSTRUCCION_LIST + LLVDER + MIENTRAS + PARIZQ + OPER + PARDER + SEMICOLON; #endregion #region FIGURAS FIGURES.Rule = ADDFIGURE + PARIZQ + CIRCLE + PARIZQ + OPERLIST + PARDER + PARDER + SEMICOLON | ADDFIGURE + PARIZQ + TRI + PARIZQ + OPERLIST + PARDER + PARDER + SEMICOLON | ADDFIGURE + PARIZQ + SQA + PARIZQ + OPERLIST + PARDER + PARDER + SEMICOLON | ADDFIGURE + PARIZQ + LINE + PARIZQ + OPERLIST + PARDER + PARDER + SEMICOLON | FIGURE + PARIZQ + OPER + PARDER + SEMICOLON; #endregion #endregion #region Preferencias /*-------- INICIO --------*/ this.Root = INICIO; /*-------- COMENTARIOS IGNORADOS --------*/ NonGrammarTerminals.Add(LineComment); NonGrammarTerminals.Add(BlockComment); /*-------- PUNTUACIÓN Y AGRUPACIÓN --------*/ MarkPunctuation(SEMICOLON, COLON, /*DOT ,*/ COMMA, PARIZQ, PARDER, LLVIZQ, LLVDER, CORIZQ, CORDER); MarkPunctuation(IMPORTAR, CLASE, MAIN, IF, ELSE, FOR, COMPROBAR, CASO, DEFECTO, WHILE, REPEAT, ASIGNACION); MarkPunctuation(HACER, MIENTRAS, ARRAY); MarkPunctuation(ADDFIGURE); /*-------- ASOCIATIVIDAD --------*/ RegisterOperators(9, Associativity.Left, DOT); RegisterOperators(1, Associativity.Left, OR); RegisterOperators(2, Associativity.Left, AND); RegisterOperators(3, Associativity.Left, IGUAL, DIFERENTE, MAYOR, MAYOR_IGUAL, MENOR, MENOR_IGUAL); RegisterOperators(4, Associativity.Right, NOT); RegisterOperators(5, Associativity.Left, MAS, MENOS, DECREMENTO, INCREMENTO); RegisterOperators(6, Associativity.Left, POR, DIVISION); RegisterOperators(7, Associativity.Left, POTENCIA); RegisterOperators(8, Associativity.Left, PARIZQ, PARDER); /*-------- PALABRAS RESERVADAS --------*/ MarkReservedWords(INT.Text, CHAR.Text, STRING.Text, DOUBLE.Text, BOOL.Text, VOID.Text, ARRAY.Text, PUBLICO.Text, PRIVADO.Text, OVERRIDE.Text, IMPORTAR.Text, NEW.Text, MAIN.Text, RETURN.Text, PRINT.Text, SHOW.Text, IF.Text, ELSE.Text, FOR.Text, REPEAT.Text, WHILE.Text, COMPROBAR.Text, CASO.Text, DEFECTO.Text, SALIR.Text, HACER.Text, MIENTRAS.Text, CONTINUAR.Text, CLASE.Text, "false", "true", "verdadero", "falso", ADDFIGURE.Text, CIRCLE.Text, LINE.Text, SQA.Text, TRI.Text, FIGURE.Text); /*-------- NOTERMINAL TRANSIENT --------*/ MarkTransient(DATATYPE, ARRCONTENT, DIMENSION, INSTRUCCION, IMPORTAR_STA, OVER_STA, CLASE_STA_BODY, VISIBILIDAD); MarkTransient(ELSE_STA); #endregion }
public FdoExpressionGrammar() : base(false) { //1. Terminals IdentifierTerminal Identifier = new IdentifierTerminal(FdoTerminalNames.Identifier); StringLiteral QuotedIdentifier = new StringLiteral(FdoTerminalNames.Identifier, "\""); StringLiteral String = new StringLiteral(FdoTerminalNames.String, "\'"); NumberLiteral Integer = new NumberLiteral(FdoTerminalNames.Integer, NumberOptions.IntOnly | NumberOptions.AllowSign); NumberLiteral Double = new NumberLiteral(FdoTerminalNames.Double); //2. Non-Terminals NonTerminal Expression = new NonTerminal(FdoTerminalNames.Expression); NonTerminal UnaryExpression = new NonTerminal(FdoTerminalNames.UnaryExpression); NonTerminal BinaryExpression = new NonTerminal(FdoTerminalNames.BinaryExpression); NonTerminal ValueExpression = new NonTerminal(FdoTerminalNames.ValueExpression); NonTerminal Function = new NonTerminal(FdoTerminalNames.Function); NonTerminal DataValue = new NonTerminal(FdoTerminalNames.DataValue); NonTerminal LiteralValue = new NonTerminal(FdoTerminalNames.LiteralValue); NonTerminal Parameter = new NonTerminal(FdoTerminalNames.Parameter); NonTerminal ExpressionCollection = new NonTerminal(FdoTerminalNames.ExpressionCollection); NonTerminal GeometryValue = new NonTerminal(FdoTerminalNames.GeometryValue); NonTerminal Boolean = new NonTerminal(FdoTerminalNames.Boolean); NonTerminal DateTime = new NonTerminal(FdoTerminalNames.DateTime); //3. BNF Rules Expression.Rule = "(" + Expression + ")" | UnaryExpression | BinaryExpression | Function | Identifier | QuotedIdentifier | ValueExpression; BinaryExpression.Rule = Expression + "+" + Expression | Expression + "-" + Expression | Expression + "*" + Expression | Expression + "/" + Expression; DataValue.Rule = DateTime | Double | Integer | String | //Blob | //Clob | Boolean | "NULL"; Boolean.Rule = ToTerm("TRUE") | ToTerm("FALSE"); DateTime.Rule = "DATE" + String | "TIME" + String | "TIMESTAMP" + String; Function.Rule = Identifier + "(" + ExpressionCollection + ")" | Identifier + "()"; ExpressionCollection.Rule = Expression | ExpressionCollection + "," + Expression; GeometryValue.Rule = ToTerm("GEOMFROMTEXT") + "(" + String + ")"; ValueExpression.Rule = LiteralValue | Parameter; LiteralValue.Rule = GeometryValue | DataValue; Parameter.Rule = Parameter | ":" + Identifier; UnaryExpression.Rule = "-" + Expression; this.Root = Expression; // 4. Set operators precedence RegisterOperators(1, "+", "-"); RegisterOperators(2, "*", "/"); this.MarkPunctuation("(", ")", ",", ":", "-"); /* * <Expression> ::= '(' Expression ')' | <UnaryExpression> | <BinaryExpression> | <Function> | <Identifier> | <ValueExpression> | <BinaryExpression> ::= | <Expression> '+' <Expression> | <Expression> '-' <Expression> | <Expression> '*' <Expression> | <Expression> '/' <Expression> | <DataValue> ::= | TRUE | FALSE | DATETIME | DOUBLE | INTEGER | STRING | BLOB | CLOB | NULL | <Function> ::= <Identifier> '(' <ExpressionCollection> ')' | <ExpressionCollection> ::= | <Expression> | <ExpressionCollection> ',' <Expression> | <GeometryValue> ::= GEOMFROMTEXT '(' STRING ')' | <Identifier> ::= IDENTIFIER | <ValueExpression> ::= <LiteralValue> | <Parameter>; | <LiteralValue> ::= <GeometryValue> | <DataValue> | <Parameter> ::= PARAMETER | ':'STRING | <UnaryExpression> ::= '-' <Expression> | */ }
public SqlGrammar() : base(false) { var comment = new CommentTerminal("comment", "/*", "*/"); var lineComment = new CommentTerminal("line_comment", "--", "\n", "\r\n"); NonGrammarTerminals.Add(comment); NonGrammarTerminals.Add(lineComment); var number = new NumberLiteral("number"); var string_literal = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote); var Id_simple = TerminalFactory.CreateSqlExtIdentifier(this, "id_simple"); //covers normal identifiers (abc) and quoted id's ([abc d], "abc d") var comma = ToTerm(","); var dot = ToTerm("."); var CREATE = ToTerm("CREATE"); var NULL = ToTerm("NULL"); var NOT = ToTerm("NOT"); var ON = ToTerm("ON"); 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 TRUE = ToTerm("TRUE"); var FALSE = ToTerm("FALSE"); //Non-terminals var Id = new NonTerminal("Id"); var statement = new NonTerminal("stmt"); var selectStatement = new NonTerminal("selectStatement"); var idlist = new NonTerminal("idlist"); var aliaslist = new NonTerminal("aliaslist"); var aliasItem = new NonTerminal("aliasItem"); var orderList = new NonTerminal("orderList"); var orderMember = new NonTerminal("orderMember"); var orderDirOptional = new NonTerminal("orderDirOpt"); var whereClauseOptional = new NonTerminal("whereClauseOpt"); var expression = new NonTerminal("expression"); var expressionList = new NonTerminal("exprList"); var optionalSelectRestriction = new NonTerminal("optionalSelectRestriction"); var selectorList = new NonTerminal("selList"); var fromClauseOpt = new NonTerminal("fromClauseOpt"); var groupClauseOpt = new NonTerminal("groupClauseOpt"); var havingClauseOpt = new NonTerminal("havingClauseOpt"); var orderClauseOpt = new NonTerminal("orderClauseOpt"); var limitClauseOpt = new NonTerminal("limitClauseOpt"); var offsetClauseOpt = new NonTerminal("offsetClauseOpt"); 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 tuple = new NonTerminal("tuple"); var joinChainOpt = new NonTerminal("joinChainOpt"); var joinStatement = new NonTerminal("joinStatement"); 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 inExpr = new NonTerminal("inExpr"); var parSelectStatement = new NonTerminal("parSelectStmt"); var notOpt = new NonTerminal("notOpt"); var funCall = new NonTerminal("funCall"); var parameter = new NonTerminal("parameter"); var statementLine = new NonTerminal("stmtLine"); var optionalSemicolon = new NonTerminal("semiOpt"); var statementList = new NonTerminal("stmtList"); var functionArguments = new NonTerminal("funArgs"); var inStatement = new NonTerminal("inStmt"); var boolean = new NonTerminal("boolean"); //BNF Rules this.Root = statementList; statementLine.Rule = statement + optionalSemicolon; optionalSemicolon.Rule = Empty | ";"; statementList.Rule = MakePlusRule(statementList, statementLine); statement.Rule = selectStatement; Id.Rule = MakePlusRule(Id, dot, Id_simple); aliasOpt.Rule = Empty | asOpt + Id; asOpt.Rule = Empty | AS; idlist.Rule = MakePlusRule(idlist, comma, columnSource); aliaslist.Rule = MakePlusRule(aliaslist, comma, aliasItem); aliasItem.Rule = Id + aliasOpt; //Create Index orderList.Rule = MakePlusRule(orderList, comma, orderMember); orderMember.Rule = Id + orderDirOptional; orderDirOptional.Rule = Empty | "ASC" | "DESC"; //Select stmt selectStatement.Rule = SELECT + optionalSelectRestriction + selectorList + fromClauseOpt + whereClauseOptional + groupClauseOpt + havingClauseOpt + orderClauseOpt + limitClauseOpt + offsetClauseOpt; optionalSelectRestriction.Rule = Empty | "ALL" | "DISTINCT"; selectorList.Rule = columnItemList | "*"; columnItemList.Rule = MakePlusRule(columnItemList, comma, columnItem); columnItem.Rule = columnSource + aliasOpt; columnSource.Rule = funCall | Id; fromClauseOpt.Rule = Empty | FROM + aliaslist + joinChainOpt; joinChainOpt.Rule = MakeStarRule(joinChainOpt, joinStatement); joinStatement.Rule = joinKindOpt + JOIN + aliaslist + ON + Id + "=" + Id; joinKindOpt.Rule = Empty | "INNER" | "LEFT" | "RIGHT"; whereClauseOptional.Rule = Empty | "WHERE" + expression; groupClauseOpt.Rule = Empty | "GROUP" + BY + idlist; havingClauseOpt.Rule = Empty | "HAVING" + expression; orderClauseOpt.Rule = Empty | "ORDER" + BY + orderList; limitClauseOpt.Rule = Empty | "LIMIT" + expression; offsetClauseOpt.Rule = Empty | "OFFSET" + expression; //Expression expressionList.Rule = MakePlusRule(expressionList, comma, expression); expression.Rule = term | unExpr | binExpr | betweenExpr | parameter; term.Rule = Id | boolean | string_literal | number | funCall | tuple | parSelectStatement | inStatement; boolean.Rule = TRUE | FALSE; tuple.Rule = "(" + expressionList + ")"; parSelectStatement.Rule = "(" + selectStatement + ")"; unExpr.Rule = unOp + term; unOp.Rule = NOT | "+" | "-" | "~"; binExpr.Rule = expression + binOp + expression; binOp.Rule = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic | "&" | "|" | "^" //bit | "=" | ">" | "<" | ">=" | "<=" | "<>" | "!=" | "!<" | "!>" | "AND" | "OR" | "LIKE" | NOT + "LIKE" | "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 + "(" + functionArguments + ")"; functionArguments.Rule = selectStatement | expressionList | "*"; inStatement.Rule = expression + "IN" + "(" + expressionList + ")"; parameter.Rule = "@" + Id | "@" + Id + ":" + term; //Operators RegisterOperators(10, "*", "/", "%"); RegisterOperators(9, "+", "-"); RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>", "LIKE", "IN"); RegisterOperators(7, "^", "&", "|"); RegisterOperators(6, NOT); RegisterOperators(5, "AND"); RegisterOperators(4, "OR"); MarkPunctuation(",", "(", ")"); MarkPunctuation(asOpt, optionalSemicolon); //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(statement, term, asOpt, aliasOpt, statementLine, expression, unOp, tuple); binOp.SetFlag(TermFlags.InheritPrecedence); }
public GramaticaCQL() : base(caseSensitive: false) { #region TERMINAL //palabras reservadas var create = ToTerm("Create"); var type = ToTerm("type"); var not = ToTerm("not"); var exist = ToTerm("exists"); var news = ToTerm("new"); var entero = ToTerm("int"); var dec = ToTerm("double"); var strings = ToTerm("string"); var boolean = ToTerm("boolean"); var date = ToTerm("date"); var time = ToTerm("time"); var usertype = ToTerm("User_type"); var alter = ToTerm("alter"); var add = ToTerm("add"); var delete = ToTerm("delete"); //Definicion de Datos (DDL) var db = ToTerm("database"); var use = ToTerm("Use"); var drop = ToTerm("drop"); var counter = ToTerm("counter"); var primary = ToTerm("primary "); var key = ToTerm("key"); var map = ToTerm("map"); var set = ToTerm("set"); var list = ToTerm("list"); var truncate = ToTerm("truncate"); //Control de Transacciones (TCL) var commit = ToTerm("commit"); var rollback = ToTerm("rollback"); //Control de Datos (DCL)" var user = ToTerm("User"); var with = ToTerm("with"); var pass = ToTerm("password"); var grant = ToTerm("grant"); var on = ToTerm("on"); var revoke = ToTerm("revoke"); //Lenguaje Manipulacion de Datos (DML) var insert = ToTerm("insert"); var into = ToTerm("into"); var values = ToTerm("values"); var update = ToTerm("update"); var where = ToTerm("where"); var froms = ToTerm("from"); var table = ToTerm("table"); var select = ToTerm("select"); var indato = ToTerm("in"); var order = ToTerm("order"); var verdadero = ToTerm("true"); var falso = ToTerm("falso"); var by = ToTerm("by"); var asc = ToTerm("asc"); var desc = ToTerm("desc"); var begin = ToTerm("begin"); var batch = ToTerm("batch"); var apply = ToTerm("apply"); var count = ToTerm("count"); var min = ToTerm("min"); var max = ToTerm("max"); var sum = ToTerm("sum"); var avg = ToTerm("avg"); var limit = ToTerm("limit"); //Lenguaje de Control de flujo (FCL) var elses = ToTerm("else"); var ifs = ToTerm("if"); var switchs = ToTerm("switch"); var cases = ToTerm("case"); var defaults = ToTerm("default"); var whiles = ToTerm("while"); var does = ToTerm("do"); var fors = ToTerm("for"); var get = ToTerm("get"); var remove = ToTerm("remove"); var size = ToTerm("size"); var clear = ToTerm("clear"); var contain = ToTerm("contains"); var returns = ToTerm("return"); var breaks = ToTerm("break"); var procedure = ToTerm("procedure"); var call = ToTerm("call"); var length = ToTerm("length "); var upper = ToTerm("touppercase"); var lower = ToTerm("tolowercase"); var starts = ToTerm("startswith"); var ends = ToTerm("endswith"); var substr = ToTerm("substring"); var year = ToTerm("getyear"); var month = ToTerm("getmonth"); var day = ToTerm("getday"); var hour = ToTerm("gethour"); var minute = ToTerm("getminuts "); var second = ToTerm("getseconds"); var today = ToTerm("today"); var now = ToTerm("now"); var continues = ToTerm("continue"); var cursor = ToTerm("cursor"); var iss = ToTerm("is"); var each = ToTerm("each"); var open = ToTerm("open"); var close = ToTerm("close"); var log = ToTerm("log"); var throws = ToTerm("throw"); var trys = ToTerm("try"); var catchs = ToTerm("catch"); var ins = ToTerm("in"); var TypeAlreadyExists = ToTerm("TypeAlreadyExists"); var TypeDontExists = ToTerm("TypeDontExists"); var BDAlreadyExists = ToTerm("BDAlreadyExists"); var BDDontExists = ToTerm("BDDontExists"); var UseBDException = ToTerm("UseBDException"); var TableAlreadyExists = ToTerm("TableAlreadyExists"); var TableDontExists = ToTerm("TableDontExists"); var CounterTypeException = ToTerm("CounterTypeException"); var UserAlreadyExists = ToTerm("UserAlreadyExists"); var UserDontExists = ToTerm("UserDontExists"); var ValuesException = ToTerm("ValuesException"); var ColumnException = ToTerm("ColumnException"); var BatchException = ToTerm("BatchException"); var IndexOutException = ToTerm("IndexOutException"); var ArithmeticException = ToTerm("ArithmeticException"); var NullPointerException = ToTerm("NullPointerException"); var NumberReturnsException = ToTerm("NumberReturnsException"); var FunctionAlreadyExists = ToTerm("FunctionAlreadyExists"); var ProcedureAlreadyExists = ToTerm("ProcedureAlreadyExists"); var ObjectAlreadyExists = ToTerm("ObjectAlreadyExists"); //simbolos var or = ToTerm("||"); var and = ToTerm("&&"); var xor = ToTerm("^"); var dif = ToTerm("!="); var igual = ToTerm("=="); var menor = ToTerm("<"); var mayor = ToTerm(">"); var mayorigual = ToTerm(">="); var menorigual = ToTerm("<="); var mas = ToTerm("+"); var menos = ToTerm("-"); var por = ToTerm("*"); var div = ToTerm("/"); var mod = ToTerm("%"); var pot = ToTerm("**"); var notsymbol = ToTerm("!"); var aumenta = ToTerm("++"); var disminuye = ToTerm("--"); #endregion #region ER IdentifierTerminal id = new IdentifierTerminal("ID"); //RegexBasedTerminal ids = new RegexBasedTerminal("id2", "@[" + id.ToString() + "]"); RegexBasedTerminal fecha = new RegexBasedTerminal("fecha", "'[0-3][0-9]/[0-1][0-9]/[0-9][0-9]'"); RegexBasedTerminal hora = new RegexBasedTerminal("hora", "[0-2][0-9]:[0-5][0-9]:[0-5][0-9]"); //RegexBasedTerminal decimales = new RegexBasedTerminal("decimal", "[0-9]+.[0-9]+"); NumberLiteral number = new NumberLiteral("number"); StringLiteral cadena = new StringLiteral("cadena", "\""); /* se indica que la cadena va a empezar con " (comillas dobles) y con * esto acepta cualquier cosa que venga despues de las comillas dobles */ #endregion #region NO TERMINAL NonTerminal S = new NonTerminal("S"); NonTerminal CQL = new NonTerminal("CQL"); NonTerminal TYPEEXCEPTION = new NonTerminal("TYPEEXCEPTION"); NonTerminal RETURNVAL = new NonTerminal("RETURNVAL"); NonTerminal CQLBREAK = new NonTerminal("CQLBREAK"); NonTerminal CQLCYCLE = new NonTerminal("CQLCYCLE"); NonTerminal DECLARACION = new NonTerminal("DECLARACION"); NonTerminal LVARIABLES = new NonTerminal("LVARIABLES"); NonTerminal IDENT = new NonTerminal("IDENT"); NonTerminal PARMVALS = new NonTerminal("PARMVALS"); NonTerminal PARAMETERS = new NonTerminal("PARAMETERS"); NonTerminal LPARMS = new NonTerminal("LPARMS"); NonTerminal SENTENCIA = new NonTerminal("SENTENCIA"); NonTerminal FORES = new NonTerminal("FORES"); NonTerminal LCASES = new NonTerminal("LCASES"); NonTerminal DEFAULTS = new NonTerminal("DEFAULTS"); NonTerminal IFS = new NonTerminal("IFS"); NonTerminal ELSEIFS = new NonTerminal("ELSEIFS"); NonTerminal ELSE = new NonTerminal("ELSE"); NonTerminal FUNAGREG = new NonTerminal("FUNAGREG"); NonTerminal LSENTDML = new NonTerminal("LSENTDML"); NonTerminal SENTDML = new NonTerminal("SENTDML"); NonTerminal SELECTWHERE = new NonTerminal("SELECTWHERE"); NonTerminal SELECTWHEREVAL = new NonTerminal("SELECTWHEREVAL"); NonTerminal ORDERLIMIT = new NonTerminal("ORDERLIMIT"); NonTerminal ORDERLIMITVAL = new NonTerminal("ORDERLIMITVAL"); NonTerminal LORDER = new NonTerminal("LORDER"); NonTerminal ASCDESC = new NonTerminal("ASCDESC"); NonTerminal LIMITDATA = new NonTerminal("LIMITDATA"); NonTerminal DATASELECT = new NonTerminal("DATASELECT"); NonTerminal LASIGNACION = new NonTerminal("LASIGNACION"); NonTerminal DELETEDATA = new NonTerminal("DELETEDATA"); NonTerminal WHEREEXP = new NonTerminal("WHEREEXP"); NonTerminal INSERTDATA = new NonTerminal("INSERTDATA"); NonTerminal LVALUSER = new NonTerminal("LVALUSER"); NonTerminal TRUNCATEDATA = new NonTerminal("TRUNCATEDATA"); NonTerminal ASIGNA = new NonTerminal("ASIGNA"); NonTerminal SIGNO = new NonTerminal("SIGNO"); NonTerminal CAMBIA = new NonTerminal("CAMBIA"); NonTerminal INSTR = new NonTerminal("INSTR"); NonTerminal LCOLUMS = new NonTerminal("LCOLUMS"); NonTerminal COL = new NonTerminal("COL"); NonTerminal INFODB = new NonTerminal("INFODB"); NonTerminal EXIST = new NonTerminal("EXIST"); NonTerminal ALTERDATA = new NonTerminal("ALTERDATA"); NonTerminal ALTERTABLE = new NonTerminal("ALTERTABLE"); NonTerminal DROPDATA = new NonTerminal("DROPDATA"); NonTerminal EXPSELECT = new NonTerminal("EXPSELECT"); NonTerminal EXPSELECTVAL = new NonTerminal("EXPSELECTVAL"); NonTerminal TIPO = new NonTerminal("TIPO"); NonTerminal PRIMITIVO = new NonTerminal("PRIMITIVO"); NonTerminal EXP = new NonTerminal("EXP"); NonTerminal PUNTOID = new NonTerminal("PUNTOID"); NonTerminal VAL = new NonTerminal("VAL"); NonTerminal LVALORES = new NonTerminal("LVALORES"); NonTerminal VALUES = new NonTerminal("VALUES"); NonTerminal LCQL = new NonTerminal("LCQL"); NonTerminal LISTLAN = new NonTerminal("LISTLAN"); NonTerminal LANGUAGE = new NonTerminal("LANGUAGE"); NonTerminal LVAL = new NonTerminal("LVAL"); NonTerminal LCYCLE = new NonTerminal("LCYCLE"); NonTerminal LBREAKCQL = new NonTerminal("LBREAKCQL"); NonTerminal LIDS = new NonTerminal("LIDS"); NonTerminal IDENTIFICADOR = new NonTerminal("IDENTIFICADOR"); NonTerminal CASO = new NonTerminal("CASO"); NonTerminal ELSEIFSES = new NonTerminal("ELSEIFSES"); NonTerminal ORDENA = new NonTerminal("ORDENA"); NonTerminal TIPOASIG = new NonTerminal("TIPOASIG"); NonTerminal TIPOUSER = new NonTerminal("TIPOUSER"); NonTerminal IDES = new NonTerminal("IDES"); #endregion #region COMMENT CommentTerminal comentarioLinea = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n"); //si viene una nueva linea se termina de reconocer el comentario. CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/"); NonGrammarTerminals.Add(comentarioLinea); NonGrammarTerminals.Add(comentarioBloque); #endregion #region GRAMATICA S.Rule = LISTLAN; LISTLAN.Rule = MakePlusRule(LISTLAN, LANGUAGE); LANGUAGE.Rule = procedure + id + "(" + PARAMETERS + "," + "(" + PARAMETERS + "{" + LCQL + "}" | TIPO + id + "(" + PARAMETERS + "{" + LCQL + "}" | CQL; CQL.Rule = create + INSTR | TIPO + LVARIABLES + ASIGNA | alter + ALTERDATA | use + id + ";" | drop + DROPDATA | truncate + table + id + ";" | commit + ";" //falta | rollback + ";" //falta | grant + id + on + id + ";" | revoke + id + on + id + ";" | SENTDML | select + DATASELECT + froms + id + SELECTWHERE //falta | begin + batch + LSENTDML + apply + batch + ";" //falta | FUNAGREG + "(" + "<" + select + DATASELECT + froms + id + SELECTWHEREVAL + ">" + ")" + ";" //falta | FUNAGREG + "(" + "<" + select + DATASELECT + froms + id + ">" + ")" + ";" //falta | IFS | switchs + "(" + EXP + ")" + "{" + LCASES + DEFAULTS | whiles + "(" + EXP + ")" + "{" + LCYCLE + "}" | does + "{" + LCYCLE + "}" + whiles + "(" + EXP + ")" + ";" | fors + FORES | PUNTOID + "(" + PARMVALS + ";" | call + PUNTOID + "(" + PARMVALS + ";" | returns + RETURNVAL | cursor + "@" + id + iss + select + DATASELECT + froms + id + SELECTWHERE //falta | open + "@" + id + ";" //falta | close + "@" + id + ";" //falta | log + "(" + EXP + ")" + ";" | throws + news + TYPEEXCEPTION + ";" //falta | trys + "{" + LCQL + "}" + catchs + "(" + TYPEEXCEPTION + id + ")" + "{" + LCQL + "}" //falta | PUNTOID + "." + insert + "(" + VAL + "," + EXP + ")" | PUNTOID + "." + insert + "(" + EXP + ")" | PUNTOID + "." + set + "(" + VAL + "," + EXP + ")" | PUNTOID + "." + remove + "(" + VAL + ")" | PUNTOID + "." + clear + "(" + ")" | PUNTOID + aumenta + ";" | PUNTOID + disminuye + ";" | PUNTOID + SIGNO + EXP + ";" | PUNTOID + "[" + EXP + "]" + SIGNO + EXP + ";" ; CQL.ErrorRule = SyntaxError + ";"; CQL.ErrorRule = SyntaxError + "}"; LCQL.Rule = MakePlusRule(LCQL, CQL); TYPEEXCEPTION.Rule = TypeAlreadyExists | TypeDontExists | BDAlreadyExists | BDDontExists | UseBDException | TableAlreadyExists | TableDontExists | CounterTypeException | UserAlreadyExists | UserDontExists | ValuesException | ColumnException | BatchException | IndexOutException | ArithmeticException | NullPointerException | NumberReturnsException | FunctionAlreadyExists | ProcedureAlreadyExists | ObjectAlreadyExists; RETURNVAL.Rule = LVAL + ";" | ";"; CQLBREAK.Rule = CQL | breaks + ";"; CQLCYCLE.Rule = CQLBREAK | continues + ";"; LVAL.Rule = MakePlusRule(LVAL, EXP); LVARIABLES.Rule = MakePlusRule(LVARIABLES, ToTerm(","), IDENT); IDENT.Rule = "@" + id | id; PARMVALS.Rule = LVAL + ")" | ")"; PARMVALS.ErrorRule = SyntaxError + ")"; PARAMETERS.Rule = LPARMS + ")" | ")"; PARAMETERS.ErrorRule = SyntaxError + ")"; LPARMS.Rule = MakePlusRule(LPARMS, ToTerm(","), IDENTIFICADOR); IDENTIFICADOR.Rule = TIPO + "@" + id; /*SENTENCIA.Rule = * SENTENCIA.Rule = SyntaxError + ")";*/ LCYCLE.Rule = MakePlusRule(LCYCLE, CQLCYCLE); LBREAKCQL.Rule = MakePlusRule(LBREAKCQL, CQLBREAK); FORES.Rule = "(" + TIPO + IDENT + SIGNO + EXP + ";" + EXP + ";" + EXP + ")" + "{" + LCYCLE + "}" | each + "(" + LPARMS + ins + "@" + id + "{" + LCYCLE + "}"; LCASES.Rule = MakePlusRule(LCASES, CASO); CASO.Rule = cases + EXP + ":" + LBREAKCQL; DEFAULTS.Rule = defaults + ":" + LBREAKCQL + "}" | "}"; IFS.Rule = ifs + "(" + EXP + ")" + "{" + LCQL + "}" + ELSEIFS + ELSE | ifs + "(" + EXP + ")" + "{" + LCQL + "}" + ELSEIFS | ifs + "(" + EXP + ")" + "{" + LCQL + "}" + ELSE | ifs + "(" + EXP + ")" + "{" + LCQL + "}"; ELSEIFS.Rule = MakePlusRule(ELSEIFS, ELSEIFSES); ELSEIFSES.Rule = elses + ifs + "(" + EXP + ")" + "{" + LCQL + "}"; ELSE.Rule = elses + "{" + LCQL + "}"; FUNAGREG.Rule = count | min | max | sum | avg; LSENTDML.Rule = MakePlusRule(LSENTDML, SENTDML); SENTDML.Rule = insert + into + id + INSERTDATA | update + id + set + LASIGNACION + WHEREEXP | delete + DELETEDATA; SELECTWHERE.Rule = where + EXP + EXPSELECT; SELECTWHEREVAL.Rule = where + EXP + EXPSELECTVAL; ORDERLIMIT.Rule = order + by + LORDER + LIMITDATA | LIMITDATA; ORDERLIMITVAL.Rule = order + by + LORDER + limit + EXP | order + by + LORDER | limit + EXP; LORDER.Rule = MakePlusRule(LORDER, ToTerm(","), ORDENA); ORDENA.Rule = id + ASCDESC; ASCDESC.Rule = asc | desc; LIMITDATA.Rule = limit + EXP + ";" | ";"; DATASELECT.Rule = LVAL | ToTerm("*"); LASIGNACION.Rule = MakePlusRule(LASIGNACION, ToTerm(","), TIPOASIG); TIPOASIG.Rule = id + "=" + VAL; DELETEDATA.Rule = type + id + ";" | froms + id + WHEREEXP; WHEREEXP.Rule = where + EXP + ";" | ";"; INSERTDATA.Rule = values + "(" + LVAL + ")" | "(" + LVAL + ")" + values + "(" + LVAL + ")"; LVALUSER.Rule = MakePlusRule(LVALUSER, TIPOUSER); TIPOUSER.Rule = id + TIPO; ASIGNA.Rule = ";" | SIGNO + EXP + ";"; SIGNO.Rule = ToTerm("=") | ToTerm("+=") | ToTerm("-=") | ToTerm("*=") | ToTerm("/="); CAMBIA.Rule = add + "(" + LVALUSER + ")" + ";" | delete + "(" + LIDS + ")" + ";"; LIDS.Rule = MakePlusRule(LIDS, ToTerm(","), id); INSTR.Rule = type + id + "(" + LVALUSER + ")" + ";" | db + INFODB + ";" | table + INFODB + "(" + LCOLUMS + ")" + ";" | user + VAL + with + pass + VAL + ";"; LCOLUMS.Rule = MakePlusRule(LCOLUMS, COL); COL.Rule = id + TIPO + primary + key | id + TIPO | primary + key + "(" + LIDS + ")"; INFODB.Rule = ifs + EXIST + id | id; EXIST.Rule = not + exist | exist; ALTERDATA.Rule = type + id + CAMBIA | table + id + ALTERTABLE; ALTERTABLE.Rule = add + LVALUSER + ";" | drop + LIDS + ";"; DROPDATA.Rule = table + INFODB + ";" | db + INFODB + ";"; EXPSELECT.Rule = EXP + ORDERLIMIT | indato + EXP + ORDERLIMIT | ORDERLIMIT; EXPSELECTVAL.Rule = EXP + order + by + LORDER + limit + EXP | EXP + order + by + LORDER | EXP + limit + EXP | EXP | indato + EXP + order + by + LORDER + limit + EXP | indato + EXP + order + by + LORDER | indato + EXP + limit + EXP | indato + EXP | order + by + LORDER + limit + EXP | order + by + LORDER | limit + EXP; TIPO.Rule = PRIMITIVO | map + "<" + PRIMITIVO + "," + PRIMITIVO + ">" | list + "<" + PRIMITIVO + ">" | set + "<" + PRIMITIVO + ">"; PRIMITIVO.Rule = entero | dec | strings | boolean | date | time | id; EXP.Rule = EXP + or + EXP | EXP + and + EXP | EXP + xor + EXP | EXP + dif + EXP | EXP + igual + EXP | EXP + menor + EXP | EXP + mayor + EXP | EXP + mayorigual + EXP | EXP + menorigual + EXP | EXP + mas + EXP | EXP + menos + EXP | EXP + por + EXP | EXP + div + EXP | EXP + mod + EXP | EXP + pot + EXP | notsymbol + EXP | menos + EXP | EXP + aumenta | EXP + disminuye | ToTerm("(") + EXP + ToTerm(")") | VAL; PUNTOID.Rule = MakePlusRule(PUNTOID, ToTerm("."), IDES); IDES.Rule = id | "@" + id; VAL.Rule = number | cadena //| decimales | verdadero | falso | fecha | hora | news + TIPO | "{" + LVALORES + "}" | PUNTOID | "(" + TIPO + ")" + VAL | ToTerm("null") | select + DATASELECT + froms + id + SELECTWHEREVAL | FUNAGREG + "(" + "<" + select + DATASELECT + froms + id + SELECTWHEREVAL + ">" + ")" | PUNTOID + ToTerm(".") + "[" + EXP + "]" | PUNTOID + "[" + EXP + "]" // | "[" + LVALORES + "]" | "(" + EXP + ")" + "?" + EXP + ":" + EXP | PUNTOID + "." + size + "(" + ")" | PUNTOID + "." + contain + "(" + EXP + ")" | PUNTOID + "(" + PARMVALS | call + PUNTOID + "(" + PARMVALS | PUNTOID + "." + length + "(" + ")" | PUNTOID + "." + upper + "(" + ")" | PUNTOID + "." + lower + "(" + ")" | PUNTOID + "." + starts + "(" + VAL + ")" | PUNTOID + "." + ends + "(" + VAL + ")" | PUNTOID + "." + substr + "(" + VAL + "," + VAL + ")" | PUNTOID + "." + year + "(" + ")" | PUNTOID + "." + month + "(" + ")" | PUNTOID + "." + day + "(" + ")" | PUNTOID + "." + hora + "(" + ")" | PUNTOID + "." + min + "(" + ")" | PUNTOID + "." + second + "(" + ")" | PUNTOID + "." + get + "(" + VAL + ")" | today + "(" + ")" | now + "(" + ")"; LVALORES.Rule = MakePlusRule(LVALORES, ToTerm(","), VALUES); VALUES.Rule = EXP | VAL + ":" + EXP; #endregion #region PREFERENCIA this.Root = S; this.RegisterOperators(11, Associativity.Neutral, aumenta, disminuye); this.RegisterOperators(10, Associativity.Right, menos, notsymbol); this.RegisterOperators(9, Associativity.Left, pot); this.RegisterOperators(8, Associativity.Left, por, div, mod); this.RegisterOperators(7, Associativity.Left, mas, menos); this.RegisterOperators(6, Associativity.Neutral, menor, mayor, menorigual, mayorigual); this.RegisterOperators(5, Associativity.Left, igual, dif); this.RegisterOperators(4, Associativity.Left, xor); this.RegisterOperators(3, Associativity.Left, and); this.RegisterOperators(2, Associativity.Left, or); this.MarkPunctuation("(", ")", ",", "{", "}", "@", ":", ";", "?"); #endregion }
public SBLScriptGrammar() { var IntegerLiteral = new NumberLiteral(INT_LITERAL, NumberOptions.IntOnly); var StringLiteral = new StringLiteral(STRING_LITERAL, "'", StringOptions.AllowsAllEscapes | StringOptions.AllowsLineBreak); var BoolLiteral = new RegexBasedTerminal(BOOL_LITERAL, "true|false"); var DecimalLiteral = new RegexBasedTerminal(DECIMAL_LITERAL, "[+-]?([0-9]+M|[0-9]+\\.[0-9]+M)"); var FloatLiteral = new RegexBasedTerminal(FLOAT_LITERAL, "[+-]?([0-9]+F|[0-9]+\\.[0-9]+F)"); // var BaseIdentifier = new IdentifierTerminal(BASE_IDENTIFIER, IdOptions.NameIncludesPrefix); var Identifier = new NonTerminal(FULL_IDENTIFIER); // var Expression = new NonTerminal(EXPRESSION); var BinaryOp = new NonTerminal(BINARY_OP); var BinaryOperation = new NonTerminal(BINARY_OPERATION); // var FunctionCallArgumentList = new NonTerminal(FUNCTION_CALL_ARGUMENT_LIST); var FunctionCall = new NonTerminal(FUNCTION_CALL); var FunctionDefinition = new NonTerminal(FUNCTION_DEFINITION); var FunctionDefinitionArgument = new NonTerminal(FUNCTION_DEFINITION_ARGUMENT); // var TypeName = new NonTerminal(TYPE_NAME); // var Statement = new NonTerminal(STATEMENT); var StatementGroup = new NonTerminal(STATEMENT_GROUP); var MetaStatement = new NonTerminal(META_INSTRUCTION); var VarDeclaration = new NonTerminal(VAR_DECLARATION); var AssignmentStatement = new NonTerminal(ASSIGNMENT_STATEMENT); var ForStatement = new NonTerminal(FOR_STATEMENT); var ForEachStatement = new NonTerminal(FOREACH_STATEMENT); var WhileStatement = new NonTerminal(WHILE_STATEMENT); var Program = new NonTerminal(PROGRAM); /******************/ Identifier.Rule = BaseIdentifier | BaseIdentifier + "." + Identifier; Expression.Rule = IntegerLiteral | StringLiteral | BoolLiteral | DecimalLiteral | FloatLiteral | Identifier | BinaryOperation | "(" + Expression + ")"; BinaryOp.Rule = ToTerm("+") | "-" | "*" | "/" | ">" | "<" | ">=" | "<=" | "%" | "==" | "<>" | "&" | "|" | "and" | "or"; BinaryOperation.Rule = Expression + BinaryOp + Expression; FunctionCallArgumentList.Rule = Expression | Expression + "," + FunctionCallArgumentList; FunctionCall.Rule = Identifier + "(" + ")" | Identifier + "(" + FunctionCallArgumentList + ")"; // // FunctionDefinitionArgument.Rule = TypeName + BaseIdentifier | TypeName + BaseIdentifier + "," + FunctionDefinitionArgument; // TypeName.Rule = ToTerm("bool") | "int" | "float" | "decimal" | "string" | "struct" + Identifier | "class" + Identifier; Statement.Rule = MetaStatement | VarDeclaration | ForStatement | AssignmentStatement | ForEachStatement | WhileStatement | FunctionDefinition; StatementGroup.Rule = Statement | StatementGroup + Statement; // MetaStatement.Rule = "@" + BaseIdentifier + BaseIdentifier | "@" + BaseIdentifier + "(" + StringLiteral + ")" | "@" + BaseIdentifier + "(" + StringLiteral + ")" + "as" + Identifier; VarDeclaration.Rule = "var" + Identifier + "=" + Expression + ";" | "var" + Identifier + "=" + "new" + FunctionCall + ";"; FunctionDefinition.Rule = "fn" + Identifier + "(" + ")" + "{" + "}" | "fn" + Identifier + "(" + ")" + "{" + StatementGroup + "}" | "fn" + Identifier + "(" + FunctionDefinitionArgument + ")" + "{" + "}" | "fn" + Identifier + "(" + FunctionDefinitionArgument + ")" + "{" + StatementGroup + "}"; AssignmentStatement.Rule = Identifier + "=" + Expression + ";"; ForStatement.Rule = ToTerm("for") + "(" + VarDeclaration + Expression + ";" + Identifier + "=" + Expression + ")" + "{" + "}" | ToTerm("for") + "(" + VarDeclaration + Expression + ";" + Identifier + "=" + Expression + ")" + "{" + StatementGroup + "}"; ForEachStatement.Rule = ToTerm("foreach") + "(" + "var" + BaseIdentifier + "in" + Identifier + ")" + "{" + "}" | ToTerm("foreach") + "(" + "var" + BaseIdentifier + "in" + Identifier + ")" + "{" + StatementGroup + "}"; WhileStatement.Rule = ToTerm("while") + "(" + Expression + ")" + "{" + "}" | ToTerm("while") + "(" + Expression + ")" + "{" + StatementGroup + "}"; // // Program.Rule = StatementGroup; // Root = Program; }
public CustomDslGrammar() : base(false) { #region Non-terminals var Number = new NumberLiteral("number", NumberOptions.AllowSign, typeof(NumberNode)) { DefaultFloatType = TypeCode.Decimal }; var StringLiteral = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote, typeof(StringNode)); var Comma = new NonTerminal("comma") { Rule = ToTerm(","), Flags = TermFlags.NoAstNode }; var Not = new NonTerminal("not") { Rule = ToTerm("NOT"), Flags = TermFlags.NoAstNode }; var LParen = new NonTerminal("lparen") { Rule = ToTerm("("), Flags = TermFlags.NoAstNode }; var RParen = new NonTerminal("rparen") { Rule = ToTerm(")"), Flags = TermFlags.NoAstNode }; var UnaryOperator = new NonTerminal("unaryOperator") { Rule = ToTerm("+") | "-" | Not, Flags = TermFlags.NoAstNode }; var BinaryOperator = new NonTerminal("binaryOperator") { Rule = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic | "&" | "|" | "^" //bit | "=" | ">" | "<" | ">=" | "<=" | "<>" | "AND" | "OR", Flags = TermFlags.NoAstNode }; var date = new NonTerminal("date", typeof(DateNode)); var boolean = new NonTerminal("boolean", typeof(BooleanNode)); var nil = new NonTerminal("null", typeof(NilNode)); var expression = new NonTerminal("expression"); var unaryExpression = new NonTerminal("unaryExpression", typeof(UnaryExpressionNode)); var binaryExpression = new NonTerminal("binaryExpression", typeof(BinaryExpressionNode)); var functionCall = new NonTerminal("functionCall", typeof(FunctionNode)); var terminal = new NonTerminal("term") { Flags = TermFlags.NoAstNode }; var tuple = new NonTerminal("tuple", typeof(TupleNode)); var logicFunction = new NonTerminal("logicFunction", typeof(FunctionNode)); var mathFunction = new NonTerminal("mathFunction", typeof(FunctionNode)); var stringFunction = new NonTerminal("stringFunction", typeof(FunctionNode)); var iifFunction = new NonTerminal("iif", typeof(IifFunctionNode)); var icaseFunction = new NonTerminal("icase", typeof(IcaseFunctionNode)); var caseCondition = new NonTerminal("case", typeof(CaseConditionNode)); var caseConditionList = new NonTerminal("caselist", typeof(CaseConditionListNode)); var powerFunction = new NonTerminal("power", typeof(FunctionNode)); var minFunction = new NonTerminal("min", typeof(MinFunctionNode)); var maxFunction = new NonTerminal("max", typeof(MaxFunctionNode)); var substringFunction = new NonTerminal("substring", typeof(FunctionNode)); var concatFunction = new NonTerminal("concat", typeof(ConcatFunctionNode)); var leftFunction = new NonTerminal("left", typeof(FunctionNode)); var rightFunction = new NonTerminal("right", typeof(FunctionNode)); var fieldName = new NonTerminal("fieldName") { Flags = TermFlags.NoAstNode }; var expressionList = new NonTerminal("expressionList", typeof(ExpressionListNode)); var today = new NonTerminal("today", typeof(TodayNode)); var objectProperty = new NonTerminal("objectProperty", typeof(ObjectPropertyNode)); #endregion #region Expression expression.Rule = terminal | unaryExpression | binaryExpression; expressionList.Rule = MakePlusRule(expressionList, Comma, expression); #endregion #region Literals date.Rule = ToTerm("Date") + LParen + StringLiteral + RParen; boolean.Rule = ToTerm("true") | ToTerm("false") ; nil.Rule = ToTerm("null"); #endregion #region Terminals and Expressions terminal.Rule = StringLiteral | Number | date | boolean | nil | functionCall | tuple | today | objectProperty ; tuple.Rule = LParen + expression + RParen; unaryExpression.Rule = UnaryOperator + expression; binaryExpression.Rule = expression + BinaryOperator + expression; #endregion #region Functions functionCall.Rule = logicFunction | mathFunction | stringFunction ; logicFunction.Rule = iifFunction | icaseFunction ; mathFunction.Rule = powerFunction | minFunction | maxFunction ; stringFunction.Rule = substringFunction | concatFunction | leftFunction | rightFunction ; #endregion #region Logic Functions iifFunction.Rule = ToTerm("IIF") + LParen + expression + Comma + expression + Comma + expression + RParen; icaseFunction.Rule = ToTerm("ICASE") + LParen + caseConditionList + (Comma + expression).Q() + RParen; caseCondition.Rule = expression + Comma + expression; caseConditionList.Rule = MakePlusRule(caseConditionList, Comma, caseCondition); #endregion #region Math Functions powerFunction.Rule = ToTerm("POWER") + LParen + expression + Comma + expression + RParen; minFunction.Rule = ToTerm("MIN") + LParen + expression + Comma + expression + RParen; maxFunction.Rule = ToTerm("MAX") + LParen + expression + Comma + expression + RParen; #endregion #region String Functions substringFunction.Rule = ToTerm("SUBSTRING") + LParen + expression + Comma + expression + Comma + expression + RParen; concatFunction.Rule = ToTerm("CONCAT") + LParen + expression + Comma + expression + RParen; leftFunction.Rule = ToTerm("LEFT") + LParen + expression + Comma + expression + RParen; rightFunction.Rule = ToTerm("RIGHT") + LParen + expression + Comma + expression + RParen; #endregion #region Special Functions today.Rule = ToTerm("#{TODAY}"); fieldName.Rule = TerminalFactory.CreateCSharpIdentifier("id"); objectProperty.Rule = ToTerm("$") + fieldName; #endregion #region Grammar Metadata LanguageFlags = LanguageFlags.CreateAst; RegisterOperators(10, "*", "/", "%"); RegisterOperators(9, "+", "-"); RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>"); RegisterOperators(7, "^", "&", "|"); RegisterOperators(6, "NOT"); RegisterOperators(5, "AND"); RegisterOperators(4, "OR", "LIKE", "IN"); MarkPunctuation(",", "(", ")", "}", "{", "${", ".", "?", "#{"); MarkTransient(terminal, expression, functionCall, logicFunction, mathFunction, stringFunction); #endregion Root = expression; }