public ASLGrammar() : base(true) { var string_lit = TerminalFactory.CreateCSharpString("string"); var number = TerminalFactory.CreateCSharpNumber("number"); var identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); var code = new CustomTerminal("code", MatchCodeTerminal); var single_line_comment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var delimited_comment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(single_line_comment); NonGrammarTerminals.Add(delimited_comment); var state = new KeyTerm("state", "state"); var init = new KeyTerm("init", "init"); var exit = new KeyTerm("exit", "exit"); var update = new KeyTerm("update", "update"); var start = new KeyTerm("start", "start"); var split = new KeyTerm("split", "split"); var reset = new KeyTerm("reset", "reset"); var startup = new KeyTerm("startup", "startup"); var shutdown = new KeyTerm("shutdown", "shutdown"); var isLoading = new KeyTerm("isLoading", "isLoading"); var gameTime = new KeyTerm("gameTime", "gameTime"); var comma = ToTerm(",", "comma"); var semi = ToTerm(";", "semi"); var root = new NonTerminal("root"); var state_def = new NonTerminal("stateDef"); var version = new NonTerminal("version"); var state_list = new NonTerminal("stateList"); var method_list = new NonTerminal("methodList"); var var_list = new NonTerminal("varList"); var var = new NonTerminal("var"); var module = new NonTerminal("module"); var method = new NonTerminal("method"); var offset_list = new NonTerminal("offsetList"); var offset = new NonTerminal("offset"); var method_type = new NonTerminal("methodType"); root.Rule = state_list + method_list; version.Rule = (comma + string_lit) | Empty; state_def.Rule = state + "(" + string_lit + version + ")" + "{" + var_list + "}"; state_list.Rule = MakeStarRule(state_list, state_def); method_list.Rule = MakeStarRule(method_list, method); var_list.Rule = MakeStarRule(var_list, semi, var); module.Rule = (string_lit + comma) | Empty; var.Rule = (identifier + identifier + ":" + module + offset_list) | Empty; method.Rule = (method_type + "{" + code + "}") | Empty; offset_list.Rule = MakePlusRule(offset_list, comma, offset); offset.Rule = number; method_type.Rule = init | exit | update | start | split | isLoading | gameTime | reset | startup | shutdown; Root = root; MarkTransient(var_list, method_list, offset, method_type); LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public VASLGrammar() : base(true) { var code = new CustomTerminal("code", MatchCodeTerminal); var stringLit = TerminalFactory.CreateCSharpString("string"); var identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); var number = TerminalFactory.CreateCSharpNumber("number"); number.Options |= NumberOptions.AllowSign; var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var delimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(delimitedComment); // Todo: Aliases var init = new KeyTerm("init", "init"); var exit = new KeyTerm("exit", "exit"); var update = new KeyTerm("update", "update"); var start = new KeyTerm("start", "start"); var split = new KeyTerm("split", "split"); var reset = new KeyTerm("reset", "reset"); var startup = new KeyTerm("startup", "startup"); var shutdown = new KeyTerm("shutdown", "shutdown"); var undoSplit = new KeyTerm("undoSplit", "undoSplit"); var isLoading = new KeyTerm("isLoading", "isLoading"); var gameTime = new KeyTerm("gameTime", "gameTime"); var comma = ToTerm(",", "comma"); var semi = ToTerm(";", "semi"); var root = new NonTerminal("root"); var version = new NonTerminal("version"); var methodList = new NonTerminal("methodList"); var varList = new NonTerminal("varList"); var var = new NonTerminal("var"); var method = new NonTerminal("method"); var methodType = new NonTerminal("methodType"); root.Rule = methodList; version.Rule = (comma + stringLit) | Empty; methodList.Rule = MakeStarRule(methodList, method); varList.Rule = MakeStarRule(varList, semi, var); method.Rule = (methodType + "{" + code + "}") | Empty; methodType.Rule = init | exit | update | start | split | isLoading | gameTime | reset | startup | shutdown | undoSplit; Root = root; MarkTransient(varList, methodList, methodType); LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public ASLGrammar() : base(true) { var stringLit = TerminalFactory.CreateCSharpString("string"); var number = TerminalFactory.CreateCSharpNumber("number"); var identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); var code = new CustomTerminal("code", MatchCodeTerminal); var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var delimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(delimitedComment); var state = new KeyTerm("state", "state"); var start = new KeyTerm("start", "start"); var split = new KeyTerm("split", "split"); var reset = new KeyTerm("reset", "reset"); var isLoading = new KeyTerm("isLoading", "isLoading"); var gameTime = new KeyTerm("gameTime", "gameTime"); var comma = ToTerm(",", "comma"); var semi = ToTerm(";", "semi"); var root = new NonTerminal("root"); var stateDef = new NonTerminal("stateDef"); var methodList = new NonTerminal("methodList"); var varList = new NonTerminal("varList"); var var = new NonTerminal("var"); var method = new NonTerminal("method"); var offsetList = new NonTerminal("offsetList"); var offset = new NonTerminal("offset"); var methodType = new NonTerminal("methodType"); root.Rule = stateDef + methodList; stateDef.Rule = state + "(" + stringLit + ")" + "{" + varList + "}"; methodList.Rule = MakeStarRule(methodList, method); varList.Rule = MakeStarRule(varList, semi, var); var.Rule = (identifier + identifier + ":" + stringLit + comma + offsetList) | Empty; method.Rule = (methodType + "{" + code + "}") | Empty; offsetList.Rule = MakePlusRule(offsetList, comma, offset); offset.Rule = number; methodType.Rule = start | split | isLoading | gameTime | reset; this.Root = root; MarkTransient(varList, methodList, offset, methodType); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public void TestString_CSharp() { Parser parser; Token token; parser = TestHelper.CreateParser(TerminalFactory.CreateCSharpString("String")); token = parser.ParseInput('"' + @"abcd\\" + '"' + " "); Assert.IsTrue((string)token.Value == @"abcd\", "Failed to process double escape char at the end of the string."); token = parser.ParseInput('"' + @"abcd\\\" + '"' + "efg" + '"' + " "); Assert.IsTrue((string)token.Value == @"abcd\" + '"' + "efg", @"Failed to process '\\\ + double-quote' inside the string."); //with Escapes token = parser.ParseInput(ReplaceQuotes(@"'00\a\b\t\n\v\f\r\'\\00' ")); Assert.IsTrue((string)token.Value == "00\a\b\t\n\v\f\r\"\\00", "Failed to process escaped characters."); token = parser.ParseInput(ReplaceQuotes("'abcd\nefg' ")); Assert.IsTrue(token.IsError(), "Failed to detect erroneous multi-line string."); //With invalid escape token = parser.ParseInput(ReplaceQuotes("\"\\d\"")); Assert.IsTrue(token.IsError(), "Failed to detect invalid escape sequence."); //with disabled escapes token = parser.ParseInput(ReplaceQuotes(@"@'00\a\b\t\n\v\f\r00' ")); Assert.IsTrue((string)token.Value == @"00\a\b\t\n\v\f\r00", "Failed to process @-string with disabled escapes."); token = parser.ParseInput(ReplaceQuotes("@'abc\ndef' ")); Assert.IsTrue((string)token.Value == "abc\ndef", "Failed to process @-string with linebreak."); //Unicode and hex token = parser.ParseInput(ReplaceQuotes(@"'abc\u0040def' ")); Assert.IsTrue((string)token.Value == "abc@def", "Failed to process unicode escape \\u."); token = parser.ParseInput(ReplaceQuotes(@"'abc\U00000040def' ")); Assert.IsTrue((string)token.Value == "abc@def", "Failed to process unicode escape \\u."); token = parser.ParseInput(ReplaceQuotes("\"\\u1\"")); Assert.IsTrue((string)token.Text == "\"\\u1\"", "Failed to process unicode escape \"\\u1\"."); token = parser.ParseInput(ReplaceQuotes(@"'abc\x0040xyz' ")); Assert.IsTrue((string)token.Value == "abc@xyz", "Failed to process hex escape (4 digits)."); token = parser.ParseInput(ReplaceQuotes(@"'abc\x040xyz' ")); Assert.IsTrue((string)token.Value == "abc@xyz", "Failed to process hex escape (3 digits)."); token = parser.ParseInput(ReplaceQuotes(@"'abc\x40xyz' ")); Assert.IsTrue((string)token.Value == "abc@xyz", "Failed to process hex escape (2 digits)."); //octals token = parser.ParseInput(ReplaceQuotes(@"'abc\0601xyz' ")); //the last digit "1" should not be included in octal number Assert.IsTrue((string)token.Value == "abc01xyz", "Failed to process octal escape (3 + 1 digits)."); token = parser.ParseInput(ReplaceQuotes(@"'abc\060xyz' ")); Assert.IsTrue((string)token.Value == "abc0xyz", "Failed to process octal escape (3 digits)."); token = parser.ParseInput(ReplaceQuotes(@"'abc\60xyz' ")); Assert.IsTrue((string)token.Value == "abc0xyz", "Failed to process octal escape (2 digits)."); token = parser.ParseInput(ReplaceQuotes(@"'abc\0xyz' ")); Assert.IsTrue((string)token.Value == "abc\0xyz", "Failed to process octal escape (1 digit)."); }
public void TestCSharpString() { SetTerminal(TerminalFactory.CreateCSharpString("String")); TryMatch('"' + @"abcd\\" + '"' + " "); Assert.IsTrue((string)_token.Value == @"abcd\", "Failed to process double escape char at the end of the string."); TryMatch('"' + @"abcd\\\" + '"' + "efg" + '"' + " "); Assert.IsTrue((string)_token.Value == @"abcd\" + '"' + "efg", @"Failed to process '\\\ + double-quote' inside the string."); //with Escapes TryMatchDoubles(@"'00\a\b\t\n\v\f\r\'\\00' "); Assert.IsTrue((string)_token.Value == "00\a\b\t\n\v\f\r\"\\00", "Failed to process escaped characters."); TryMatchDoubles("'abcd\nefg' "); Assert.IsTrue(_token.IsError(), "Failed to detect erroneous multi-line string."); //with disabled escapes TryMatchDoubles(@"@'00\a\b\t\n\v\f\r00' "); Assert.IsTrue((string)_token.Value == @"00\a\b\t\n\v\f\r00", "Failed to process @-string with disabled escapes."); TryMatchDoubles("@'abc\ndef' "); Assert.IsTrue((string)_token.Value == "abc\ndef", "Failed to process @-string with linebreak."); //Unicode and hex TryMatchDoubles(@"'abc\u0040def' "); Assert.IsTrue((string)_token.Value == "abc@def", "Failed to process unicode escape \\u."); TryMatchDoubles(@"'abc\U00000040def' "); Assert.IsTrue((string)_token.Value == "abc@def", "Failed to process unicode escape \\u."); TryMatchDoubles(@"'abc\x0040xyz' "); Assert.IsTrue((string)_token.Value == "abc@xyz", "Failed to process hex escape (4 digits)."); TryMatchDoubles(@"'abc\x040xyz' "); Assert.IsTrue((string)_token.Value == "abc@xyz", "Failed to process hex escape (3 digits)."); TryMatchDoubles(@"'abc\x40xyz' "); Assert.IsTrue((string)_token.Value == "abc@xyz", "Failed to process hex escape (2 digits)."); //octals TryMatchDoubles(@"'abc\0601xyz' "); //the last digit "1" should not be included in octal number Assert.IsTrue((string)_token.Value == "abc01xyz", "Failed to process octal escape (3 + 1 digits)."); TryMatchDoubles(@"'abc\060xyz' "); Assert.IsTrue((string)_token.Value == "abc0xyz", "Failed to process octal escape (3 digits)."); TryMatchDoubles(@"'abc\60xyz' "); Assert.IsTrue((string)_token.Value == "abc0xyz", "Failed to process octal escape (2 digits)."); TryMatchDoubles(@"'abc\0xyz' "); Assert.IsTrue((string)_token.Value == "abc\0xyz", "Failed to process octal escape (1 digit)."); }
public SpecParser() { //Expr -> n | v | Expr BinOp Expr | UnOP Expr | ( Expr ) //BinOp -> + | - | * | / | ** //UnOp -> - //ExprLine -> Expr EOF //1. Terminals //Terminal num = new NumberLiteral("number"); Terminal id = new IdentifierTerminal("id"); //Terminal stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //2. Non-Terminals //Programs and declarations var program = new NonTerminal("program"); var declarationOrStatementsInMainProgram = new NonTerminal("declarationOrStatementsInMainProgram"); var declaration = new NonTerminal("declaration"); var constantDeclaration = new NonTerminal("constantDeclaration"); var initializingValue = new NonTerminal("initializingValue"); var variableDeclaration = new NonTerminal("variableDeclaration"); //Types var typeDeclaration = new NonTerminal("typeDeclaration"); var typeSpec = new NonTerminal("typeSpec"); var standardType = new NonTerminal("standardType"); var subrangeType = new NonTerminal("subrangeType"); var arrayType = new NonTerminal("arrayType"); var indexType = new NonTerminal("indexType"); var recordType = new NonTerminal("recordType"); var namedType = new NonTerminal("namedType"); //subprograms var subprogramDeclaration = new NonTerminal("subprogramDeclaration"); var subprogramHeader = new NonTerminal("subprogramHeader"); var parameterDeclaration = new NonTerminal("parameterDeclaration"); var parameterType = new NonTerminal("parameterType"); var subprogramBody = new NonTerminal("subprogramBody"); //statements and input/output var declarationsAndStatements = new NonTerminal("declarationsAndStatements"); var declarationOrStatement = new NonTerminal("declarationOrStatement"); var statement = new NonTerminal("statement"); var procedureCall = new NonTerminal("procedureCall"); var ifStatement = new NonTerminal("ifStatement"); var loopStatement = new NonTerminal("loopStatement"); var caseStatement = new NonTerminal("caseStatement"); var forStatement = new NonTerminal("forStatement"); var putStatement = new NonTerminal("putStatement"); var putItem = new NonTerminal("putItem"); var getStatement = new NonTerminal("getStatement"); var getItem = new NonTerminal("getItem"); var openStatement = new NonTerminal("openStatement"); var capability = new NonTerminal("capability"); var closeStatement = new NonTerminal("closeStatement"); var streamNumber = new NonTerminal("streamNumber"); var widthExpn = new NonTerminal("widthExpn"); var fractionWidth = new NonTerminal("fractionWidth"); var exponentWidth = new NonTerminal("exponentWidth"); var fileNumber = new NonTerminal("fileNumber"); var fileNumberVariable = new NonTerminal("fileNumberVariable"); //this was not defined in the spec. The behaviour should conform to how the language works, but it's not guaranteed var fileName = new NonTerminal("fileName"); //above is a variable declared of int type, and this is either string constant or variable //References and Expressions var variableReference = new NonTerminal("variableReference"); var reference = new NonTerminal("reference"); var componentSelector = new NonTerminal("componentSelector"); var booleanExpr = new NonTerminal("booleanExpr"); var compileTimeExpn = new NonTerminal("compileTimeExpn"); var expn = new NonTerminal("expn"); var explicitConstant = new NonTerminal("explicitConstant"); var infixOperator = new NonTerminal("infixOperator"); var prefixOperator = new NonTerminal("prefixOperator"); var substring = new NonTerminal("substring"); var substringPosition = new NonTerminal("substringPosition"); //Explicit Constants Terminal explicitStringConstant = TerminalFactory.CreateCSharpString("explicitStringConstant"); //new StringLiteral("explicitStringConstant");//new NonTerminal("explicitStringConstant"); Terminal explicitUnsignedRealConstant = new NumberLiteral("explicitUnsignedRealConstant", NumberOptions.Default); //new NonTerminal("explicitUnsignedRealConstant"); Terminal explicitUnsignedIntegerConstant = new NumberLiteral("explicitUnsignedIntegerConstant", NumberOptions.IntOnly | NumberOptions.NoDotAfterInt); //new NonTerminal("explicitUnsignedIntegerConstant"); //3. BNF Rules //Programs and declarations program.Rule = MakeStarRule(program, declarationOrStatementsInMainProgram); declarationOrStatementsInMainProgram.Rule = declaration | statement | subprogramDeclaration; declaration.Rule = constantDeclaration | variableDeclaration | typeDeclaration; constantDeclaration.Rule = ToTerm("const") + id + ":=" + expn | "const" + id + ":" + typeSpec + ":=" + initializingValue; initializingValue.Rule = expn | "init" + "(" + MakePlusRule(initializingValue, ToTerm(","), initializingValue) + ")"; variableDeclaration.Rule = ToTerm("var") + MakePlusRule(variableDeclaration, ToTerm(","), id) + ":=" + expn | "var" + MakePlusRule(variableDeclaration, ToTerm(","), id) + ":" + typeSpec + (":=" + initializingValue | Empty); //Types typeDeclaration.Rule = ToTerm("type") + id + ":" + typeSpec; typeSpec.Rule = standardType | subrangeType | arrayType | recordType | namedType; standardType.Rule = ToTerm("int") | "real" | "boolean" | "string" + ("(" + compileTimeExpn + ")" | Empty); subrangeType.Rule = compileTimeExpn + ".." + expn; arrayType.Rule = ToTerm("array") + MakePlusRule(arrayType, ToTerm(","), indexType) + "of" + typeSpec; indexType.Rule = subrangeType | namedType; recordType.Rule = ToTerm("record") + MakePlusRule(recordType, MakePlusRule(recordType, ToTerm(","), id) + ":" + typeSpec) + "end" + "record"; namedType.Rule = id; //Subprograms subprogramDeclaration.Rule = subprogramHeader + subprogramBody; subprogramHeader.Rule = ToTerm("procedure") + id + ("(" + MakePlusRule(subprogramHeader, ToTerm(","), parameterDeclaration) + ")" | Empty) | "function" + id + ("(" + MakePlusRule(subprogramHeader, ToTerm(","), parameterDeclaration) + ")" | Empty) + ":" + typeSpec; parameterDeclaration.Rule = (ToTerm("var") | Empty) + MakePlusRule(parameterDeclaration, ToTerm(","), id) + ":" + parameterType; parameterType.Rule = typeSpec | "string" + "(" + "*" + ")" | "array" + MakePlusRule(parameterType, ToTerm(","), compileTimeExpn + ".." + "*") + "of" + typeSpec | "array" + MakePlusRule(parameterType, ToTerm(","), compileTimeExpn + ".." + "*") + "of" + "string" + "(" + "*" + ")"; subprogramBody.Rule = declarationsAndStatements + "end" + id; //Statements and Input/Output declarationsAndStatements.Rule = MakePlusRule(declarationsAndStatements, declarationOrStatement); declarationOrStatement.Rule = declaration | statement; statement.Rule = variableReference + ":=" + expn | procedureCall | "assert" + booleanExpr | "result" + expn | ifStatement | loopStatement | "exit" + ("when" + booleanExpr | Empty) | caseStatement | forStatement | putStatement | getStatement | openStatement | closeStatement; procedureCall.Rule = reference; ifStatement.Rule = ToTerm("if") + booleanExpr + "then" + declarationsAndStatements + MakeStarRule(ifStatement, ToTerm("elsif") + booleanExpr + "then" + declarationsAndStatements) + ("else" + declarationsAndStatements | Empty) + "end" + "if"; loopStatement.Rule = ToTerm("loop") + declarationsAndStatements + "end" + "loop"; caseStatement.Rule = ToTerm("case") + expn + "of" + MakePlusRule(caseStatement, ToTerm("label") + MakePlusRule(caseStatement, ToTerm(","), compileTimeExpn) + ":" + declarationsAndStatements) + ("label" + ":" + declarationsAndStatements | Empty) + "end" + "case"; forStatement.Rule = ToTerm("for") + (id | Empty) + ":" + expn + ".." + expn + ("by" + expn | Empty) + declarationsAndStatements + "end" + "for" | "for" + "decreasing" + (id | Empty) + ":" + expn + ".." + expn + ("by" + expn | Empty) + declarationsAndStatements + "end" + "for"; putStatement.Rule = ToTerm("put") + (":" + streamNumber + "," | Empty) + MakePlusRule(putStatement, ToTerm(","), putItem) + (".." | Empty); putItem.Rule = expn + (":" + widthExpn + (":" + fractionWidth + (":" + exponentWidth | Empty) | Empty) | Empty) | "skip"; getStatement.Rule = ToTerm("get") + (":" + streamNumber + "," | Empty) + MakePlusRule(getStatement, ToTerm(","), getItem); getItem.Rule = variableReference | "skip" | variableReference + ":" + "*" | variableReference + ":" + widthExpn; openStatement.Rule = ToTerm("open") + ":" + fileNumberVariable + "," + fileName + "," + MakePlusRule(openStatement, ToTerm(","), capability); capability.Rule = ToTerm("put") | "get"; closeStatement.Rule = ToTerm("close") + ":" + fileNumber; streamNumber.Rule = widthExpn.Rule = fractionWidth.Rule = exponentWidth.Rule = fileNumber.Rule = expn; //Following are guesses as to the rules, since the spec does not state the rules for them fileNumberVariable.Rule = variableReference; fileName.Rule = explicitStringConstant | variableReference; //References and Expressions variableReference.Rule = reference; reference.Rule = id | reference + componentSelector; componentSelector.Rule = "(" + MakePlusRule(componentSelector, ToTerm(","), expn) + ")" | "." + id; booleanExpr.Rule = compileTimeExpn.Rule = expn; expn.Rule = reference | explicitConstant | substring | expn + infixOperator + expn | prefixOperator + expn | "(" + expn + ")"; expn.SetFlag(TermFlags.InheritPrecedence); explicitConstant.Rule = explicitUnsignedIntegerConstant | explicitUnsignedRealConstant | explicitStringConstant | "true" | "false"; infixOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "div" | "mod" | "**" | "<" | ">" | "=" | "<=" | ">=" | "not=" | "and" | "or"; //prefixOperator.Precedence = 70; prefixOperator.Rule = ToTerm("+") | "-" | "not"; substring.Rule = reference + "(" + substringPosition + (".." + substringPosition | Empty) + ")"; substringPosition.Rule = expn | "*" + ("-" + expn | Empty); this.Root = program; //4. Set operator precendence and associativity RegisterOperators(80, Associativity.Left, "**");//this is VERY odd, but Turing simplifies associativity by saying it's all left associative RegisterOperators(60, "*", "/", "div", "mod"); RegisterOperators(50, "+", "-"); RegisterOperators(40, "<", ">", "=", "<=", ">=", "not="); RegisterOperators(30, "not"); RegisterOperators(20, "and"); RegisterOperators(10, "or"); //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree MarkPunctuation("(", ")", ","); RegisterBracePair("(", ")"); //MarkTransient(Expr, BinOp, ParExpr); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public TplGrammar() : base(false) { var lineComment = new CommentTerminal("LineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var blockComment = new CommentTerminal("BlockComment", "/*", "*/"); NonGrammarTerminals.Add(lineComment); NonGrammarTerminals.Add(blockComment); var comma = ToTerm(","); var pipe = ToTerm("|", "pipe"); var boolean = new RegexBasedTerminal("boolean", @"\b(?:true|false)\b") { EditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None) }; var integer = new RegexBasedTerminal("integer", @"-?\d+") { EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None) }; var _decimal = new RegexBasedTerminal("decimal", @"-?\d+\.\d+") { EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None) }; var typeConvert = new CustomRegexBasedTerminal("type_convert_op", @"\[(?<type>number|string|bool)\]") { EditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None), ValueSelector = m => { switch (m.Groups["type"].Value) { case "number": return(TypeCode.Double); case "string": return(TypeCode.String); case "bool": return(TypeCode.Boolean); default: return(null); } } }; var variable = new CustomRegexBasedTerminal("variable", @"\$[0-9A-Za-z_]+") { EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None), ValueSelector = s => s.Value.Substring(1) }; var argument = new CustomRegexBasedTerminal("ArgumentName", "-[A-Za-z]+") { EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None), ValueSelector = s => s.Value.Substring(1) }; var word = new RegexBasedTerminal("word", @"\w+"); argument.EditorInfo = new TokenEditorInfo(TokenType.Text, TokenColor.Text, TokenTriggers.None); var dblQuoteString = TerminalFactory.CreateCSharpString("DoubleQuoteString"); // Allows Literal strings (@"\string") var singleQuoteString = new StringLiteral("SingleQuoteString", "'"); //Punctuation MarkPunctuation(comma); //Nonterminals var PIPELINE = new NonTerminal("PIPELINE"); var FUNCTION = new NonTerminal("FUNCTION"); var STRING = new NonTerminal("STRING"); var OPTIONAL_INT = new NonTerminal("OPTIONAL_INT"); var OPTIONAL_VAR = new NonTerminal("OPTIONAL_VAR"); var SORT_VAR = new NonTerminal("SORT_VAR"); var VALUE = new NonTerminal("VALUE"); var LIST_OF_VARIABLES = new NonTerminal("VAR_LIST"); var LIST_OF_SORT_VARIABLES = new NonTerminal("SORT_VAR_LIST"); var LIST_OF_VALUES = new NonTerminal("VALUE_LIST"); var NAMED_ARGUMENT = new NonTerminal("ARGUMENT"); var SWITCH_ARGUMENT = new NonTerminal("SWITCH_ARGUMENT"); var LIST_OF_ARGUMENTS = new NonTerminal("ARGUMENT_LIST"); var OPTIONAL_BY_FIELDS = new NonTerminal("BY_FIELDS_LIST"); var EXPRESSION_LVL0 = new NonTerminal("EXPRESSION LVL 0"); var EXPRESSION_LVL1 = new NonTerminal("EXPRESSION LVL 1"); var EXPRESSION_LVL2 = new NonTerminal("EXPRESSION LVL 2"); var EXPRESSION_LVL3 = new NonTerminal("EXPRESSION LVL 3"); var EXPRESSION_LVL4 = new NonTerminal("EXPRESSION LVL 4"); var EXPRESSION_LVL5 = new NonTerminal("EXPRESSION LVL 5"); var EXPRESSION_LVL6 = new NonTerminal("EXPRESSION LVL 6"); var EXPRESSION_LVL7 = new NonTerminal("EXPRESSION LVL 7"); var EXPRESSION_LVL8 = new NonTerminal("EXPRESSION LVL 8"); LIST_OF_VARIABLES.Rule = MakeListRule(LIST_OF_VARIABLES, comma, variable, TermListOptions.AllowEmpty); LIST_OF_ARGUMENTS.Rule = MakeListRule(LIST_OF_ARGUMENTS, null, NAMED_ARGUMENT, TermListOptions.AllowEmpty); LIST_OF_SORT_VARIABLES.Rule = MakeListRule(LIST_OF_SORT_VARIABLES, comma, SORT_VAR, TermListOptions.AllowEmpty); LIST_OF_VALUES.Rule = MakeListRule(LIST_OF_VALUES, null, VALUE); STRING.Rule = dblQuoteString | singleQuoteString ; OPTIONAL_VAR.Rule = variable | Empty ; OPTIONAL_INT.Rule = integer | Empty ; SORT_VAR.Rule = variable + "asc" | variable + "desc" | variable ; VALUE.Rule = STRING | variable | boolean | integer | _decimal ; OPTIONAL_BY_FIELDS.Rule = "by" + LIST_OF_VARIABLES | Empty ; EXPRESSION_LVL0.Rule = EXPRESSION_LVL1 | EXPRESSION_LVL0 + ToTerm("||", "or_op") + EXPRESSION_LVL1 ; EXPRESSION_LVL1.Rule = EXPRESSION_LVL2 | EXPRESSION_LVL1 + ToTerm("&&", "and_op") + EXPRESSION_LVL2 ; EXPRESSION_LVL2.Rule = EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("==", "equal_op") + EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("!=", "ne_op") + EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("~==", "loose_eq_op") + EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("~!=", "loose_eq_op") + EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("like", "like_op") + EXPRESSION_LVL3 | EXPRESSION_LVL2 + ToTerm("match", "match_op") + EXPRESSION_LVL3 ; EXPRESSION_LVL3.Rule = EXPRESSION_LVL4 | EXPRESSION_LVL3 + "<=" + EXPRESSION_LVL4 | EXPRESSION_LVL3 + ">=" + EXPRESSION_LVL4 | EXPRESSION_LVL3 + "<" + EXPRESSION_LVL4 | EXPRESSION_LVL3 + ">" + EXPRESSION_LVL4 ; EXPRESSION_LVL4.Rule = EXPRESSION_LVL5 | EXPRESSION_LVL4 + ToTerm("+", "add_op") + EXPRESSION_LVL5 | EXPRESSION_LVL4 + ToTerm("-", "sub_op") + EXPRESSION_LVL5 ; EXPRESSION_LVL5.Rule = EXPRESSION_LVL6 | EXPRESSION_LVL5 + ToTerm("*", "mult_op") + EXPRESSION_LVL6 | EXPRESSION_LVL5 + ToTerm("/", "div_op") + EXPRESSION_LVL6 | EXPRESSION_LVL5 + ToTerm("%", "mod_op") + EXPRESSION_LVL6 ; EXPRESSION_LVL6.Rule = EXPRESSION_LVL7 | EXPRESSION_LVL7 + ToTerm("^", "pow_op") + EXPRESSION_LVL6 ; EXPRESSION_LVL7.Rule = EXPRESSION_LVL8 | ToTerm("!", "not_op") + EXPRESSION_LVL8 | ToTerm("abs", "round_op") + EXPRESSION_LVL8 | ToTerm("cos", "round_op") + EXPRESSION_LVL8 | ToTerm("ceiling", "round_op") + EXPRESSION_LVL8 | ToTerm("floor", "round_op") + EXPRESSION_LVL8 | ToTerm("log", "round_op") + EXPRESSION_LVL8 | ToTerm("log10", "round_op") + EXPRESSION_LVL8 | ToTerm("round", "round_op") + EXPRESSION_LVL8 | ToTerm("sin", "round_op") + EXPRESSION_LVL8 | ToTerm("tan", "round_op") + EXPRESSION_LVL8 | ToTerm("sqrt", "round_op") + EXPRESSION_LVL8 | ToTerm("lengthof", "length_op") + EXPRESSION_LVL8 | ToTerm("typeof", "type_op") + EXPRESSION_LVL8 | typeConvert + EXPRESSION_LVL8 ; EXPRESSION_LVL8.Rule = VALUE | "(" + EXPRESSION_LVL0 + ")" ; SWITCH_ARGUMENT.Rule = argument + boolean | argument | Empty ; NAMED_ARGUMENT.Rule = argument + VALUE | argument ; FUNCTION.Rule = ToTerm("between") + OPTIONAL_VAR + STRING + STRING + SWITCH_ARGUMENT | "dedup" + LIST_OF_VARIABLES + SWITCH_ARGUMENT | "delete" + LIST_OF_VARIABLES | "eval" + variable + "=" + EXPRESSION_LVL0 | "first" + integer | "last" + integer | "group" + OPTIONAL_VAR + STRING + STRING | "kv" + LIST_OF_VARIABLES + STRING | "rex" + OPTIONAL_VAR + STRING + LIST_OF_ARGUMENTS | "select" + LIST_OF_VARIABLES | "sort" + LIST_OF_SORT_VARIABLES | "stats" + LIST_OF_VARIABLES + OPTIONAL_BY_FIELDS + LIST_OF_ARGUMENTS | "where" + EXPRESSION_LVL0 | "toupper" + LIST_OF_VARIABLES + LIST_OF_ARGUMENTS | "tolower" + LIST_OF_VARIABLES + LIST_OF_ARGUMENTS | "replace" + LIST_OF_VARIABLES + STRING + STRING + LIST_OF_ARGUMENTS | "splice" + OPTIONAL_VAR + STRING + LIST_OF_ARGUMENTS | "concat" + variable + "=" + LIST_OF_VALUES | "padleft" + LIST_OF_VARIABLES + integer + LIST_OF_ARGUMENTS | "padright" + LIST_OF_VARIABLES + integer + LIST_OF_ARGUMENTS | "substr" + OPTIONAL_VAR + integer + OPTIONAL_INT + LIST_OF_ARGUMENTS | "split" + OPTIONAL_VAR + STRING | "readlines" + STRING + LIST_OF_ARGUMENTS ; PIPELINE.Rule = MakeListRule(PIPELINE, pipe, FUNCTION); Root = PIPELINE; }
public OOPGrammar() { var identifier = new IdentifierTerminal("identifier"); var numberLiteral = new NumberLiteral("numberLiteral"); var stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral"); var charLiteral = new StringLiteral("charLiteral", "'", StringOptions.IsChar); var SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029"); var DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); var fullIdentifier = new NonTerminal("fullIdentifier"); var boolean = new NonTerminal("boolean"); var range = new NonTerminal("range"); var varType = new NonTerminal("varType"); var variableDeclaration = new NonTerminal("variableDeclaration"); var varOrConst = new NonTerminal("varOrConst"); var idenList = new NonTerminal("identifierList"); var typeSpecifier = new NonTerminal("typeSpecifier"); var result = new NonTerminal("result"); var recordList = new NonTerminal("recordList"); var type = new NonTerminal("type"); var assignment = new NonTerminal("assignment"); var setEqual = new NonTerminal("setEqual"); var assignmentOp = new NonTerminal("assignmentOp"); var expr = new NonTerminal("expr"); var binOp = new NonTerminal("binOp", "operator"); var binExpr = new NonTerminal("binExpr"); var unOp = new NonTerminal("unOp"); var unExpr = new NonTerminal("unExpr"); var parExpr = new NonTerminal("parExpr"); var and = new NonTerminal("and"); var or = new NonTerminal("or"); var not = new NonTerminal("not"); var functionCall = new NonTerminal("functionCall"); var args = new NonTerminal("args"); var loop = new NonTerminal("loop"); var forLoop = new NonTerminal("forLoop"); var optDecreasing = new NonTerminal("optDecreasing"); var optIncrementBy = new NonTerminal("optIncrementBy"); var exitLoop = new NonTerminal("exitLoop"); var ifBlock = new NonTerminal("ifBlock"); var elseIfBlock = new NonTerminal("elseIfBlock"); var optElseBlock = new NonTerminal("optElseBlock"); var caseBlock = new NonTerminal("caseBlock"); var labelBlock = new NonTerminal("labelBlock"); var functionDefinition = new NonTerminal("functionDefinition"); var optParams = new NonTerminal("optParams"); var parameters = new NonTerminal("parameters"); var parameter = new NonTerminal("parameter"); var functionHeader = new NonTerminal("functionHeader"); var overrideName = new NonTerminal("overrideName"); var externalOverrideName = new NonTerminal("externalOverrideName"); var externalDeclaration = new NonTerminal("externalDeclaration"); var statement = new NonTerminal("statement"); var program = new NonTerminal("program"); var importOrInclude = new NonTerminal("importOrInclude"); var importSection = new NonTerminal("importSection"); var import = new NonTerminal("import"); var include = new NonTerminal("include"); var unit = new NonTerminal("unit"); var uncheckedStatement = new NonTerminal("unchecked"); fullIdentifier.Rule = identifier | identifier + "." + fullIdentifier | functionCall + "." + fullIdentifier; typeSpecifier.Rule = ToTerm(":") + varType; boolean.Rule = ToTerm("true") | "false"; varType.Rule = ToTerm("int") | "nat" | "string" | "real" | "boolean" | "array" + range + "of" + varType | ToTerm("flexible") + "array" + range + "of" + varType | "record" + recordList + "end" + "record" | "int1" | "int2" | "int4" | "real1" | "real2" | "real4" | "nat1" | "nat2" | "nat4" | ToTerm("char") + "(" + numberLiteral + ")" | ToTerm("string") + "(" + numberLiteral + ")" | fullIdentifier; range.Rule = expr + ".." + expr | "char" | fullIdentifier; idenList.Rule = identifier + "," + idenList | identifier; varOrConst.Rule = ToTerm("var") | "const"; variableDeclaration.Rule = varOrConst + idenList | varOrConst + idenList + setEqual | varOrConst + idenList + typeSpecifier | varOrConst + idenList + typeSpecifier + setEqual; result.Rule = "result" + expr | "return" + expr; recordList.Rule = idenList + typeSpecifier + recordList | Empty; type.Rule = "type" + identifier + typeSpecifier; assignment.Rule = fullIdentifier + setEqual | functionCall + setEqual; setEqual.Rule = assignmentOp + expr; assignmentOp.Rule = ToTerm(":=") | "+=" | "-=" | "*=" | "/=" | "div=" | "mod=" | "rem=" | "shl=" | "shr=" | "xor="; binOp.Rule = ToTerm("-") | "*" | "/" | "**" | "+" | "div" | "mod" | and | or | "=" | ">" | "<" | ">=" | "<=" | "~=" | "not="; binOp.Precedence = 1; unOp.Rule = not | "-"; unOp.Precedence = 2; binExpr.Rule = expr + PreferShiftHere() + binOp + expr; unExpr.Rule = unOp + expr; parExpr.Rule = "(" + expr + ")"; and.Rule = ToTerm("and") | "&"; or.Rule = ToTerm("or") | "|"; not.Rule = ToTerm("not") | "~" | "!"; expr.Rule = numberLiteral | identifier | stringLiteral | charLiteral | binExpr | unExpr | parExpr | functionCall; //expr.Rule = numberLiteral | identifier | BinExpr | ParExpr | stringLiteral | charLiteral | unExpr | functionCall | memberCall | boolean | initExpr; args.Rule = MakeStarRule(args, ToTerm(","), (expr | identifier + ":=" + expr)); functionCall.Rule = fullIdentifier + "(" + args + ")"; loop.Rule = "loop" + program + "end" + "loop"; optDecreasing.Rule = "decreasing" | Empty; optIncrementBy.Rule = "by" + expr | Empty; forLoop.Rule = "for" + optDecreasing + identifier + ":" + range + optIncrementBy + program + "end" + "for"; exitLoop.Rule = ToTerm("exit") | ToTerm("exit") + "when" + expr; ifBlock.Rule = ToTerm("if") + expr + ToTerm("then") + program + elseIfBlock + optElseBlock + ToTerm("end") + "if"; elseIfBlock.Rule = ToTerm("elsif") + expr + ToTerm("then") + program + elseIfBlock | Empty; optElseBlock.Rule = ToTerm("else") + program | Empty; caseBlock.Rule = ToTerm("case") + fullIdentifier + "of" + labelBlock + "end case"; labelBlock.Rule = ToTerm("label") + expr + ":" + program + labelBlock | ToTerm("label") + ":" + labelBlock | Empty; overrideName.Rule = stringLiteral; externalOverrideName.Rule = overrideName | Empty; externalDeclaration.Rule = "external" + externalOverrideName + functionHeader; optParams.Rule = ToTerm("(") + parameters + ")" | ToTerm("(") + ")" | Empty; parameters.Rule = parameter + "," + parameters | parameter; parameter.Rule = idenList + typeSpecifier | "var" + idenList + typeSpecifier; functionHeader.Rule = "function" + identifier + optParams + typeSpecifier | "fcn" + identifier + optParams + typeSpecifier | "procedure" + identifier + optParams | "proc" + identifier + optParams; functionDefinition.Rule = functionHeader + program + "end" + identifier; importOrInclude.Rule = import | include; import.Rule = "import" + fullIdentifier | "import" + fullIdentifier + "in" + stringLiteral; include.Rule = "include" + stringLiteral; importSection.Rule = MakeStarRule(importSection, importOrInclude); unit.Rule = "unit" + importSection + program | importSection + program; uncheckedStatement.Rule = ToTerm("unchecked"); statement.Rule = assignment | functionDefinition | variableDeclaration | functionCall | loop | forLoop | exitLoop | ifBlock | caseBlock | type | result | uncheckedStatement; //Statement.Rule = functionCall | memberCall | iden | variableDeclaration | ifBlock | caseBlock | functionCall | functionDefinition | io | assignment | result | loop | forLoop | type | newer | exitLoop | externalDeclaration; program.Rule = statement + program | Empty; this.Root = unit; }
public Gramatica() : base(caseSensitive: false) { #region ER /*NUMERO ENTERO*/ RegexBasedTerminal numentero = new RegexBasedTerminal("Int", "[0-9]+"); /*NUMERO DECIMAL*/ RegexBasedTerminal numdecimal = new RegexBasedTerminal("double", "[0-9]+[.][0-9]+"); /*IDENTIFICADOR*/ IdentifierTerminal id = new IdentifierTerminal("id"); /*STRING*/ //CommentTerminal cadena = new CommentTerminal("String", "\"", ".", "\""); StringLiteral cadena = TerminalFactory.CreateCSharpString("String"); /*STRING*/ CommentTerminal importaciones = new CommentTerminal("String", "\"", ".[.].", "\""); /*CHAR*/ StringLiteral caracter = TerminalFactory.CreateCSharpChar("Char"); CommentTerminal comentarioLinea = new CommentTerminal("comentarioLinea", "//", "\n", "\r\n"); CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "/*", "*/"); #endregion //--------------------------------------RESERVADAS------------------------------------------------ #region Terminal //TIPO DATO var rint = ToTerm("Int"); var rdouble = ToTerm("Double"); var rstring = ToTerm("String"); var rchar = ToTerm("Char"); var rbool = ToTerm("Boolean"); var rvoid = ToTerm("Void"); //PALABRAS RESERVADAS var importar = ToTerm("Import"); var retornar = ToTerm("Return"); var rprint = ToTerm("Print"); var rmain = ToTerm("Main"); var comparar = ToTerm("CompareTo"); var rGetUser = ToTerm("GetUser"); var rbreak = ToTerm("Break"); //OPERACIONES ARITMETICAS var mas = ToTerm("+"); var menos = ToTerm("-"); var por = ToTerm("*"); var dividir = ToTerm("/"); var modulo = ToTerm("%"); var potencia = ToTerm("^"); //OPERACIONES RELACIONALES var igual2 = ToTerm("=="); var diferente = ToTerm("!="); var menor = ToTerm("<"); var mayor = ToTerm(">"); var menorigual = ToTerm("<="); var mayorigual = ToTerm(">="); //OPERACIONES LOGICAS var rand = ToTerm("&&"); var ror = ToTerm("||"); var rxor = ToTerm("|&"); var rnot = ToTerm("!"); //OPERACIONES ESPECIALES var incremento = ToTerm("++"); var decremento = ToTerm("--"); var masigual = ToTerm("+="); var menosigual = ToTerm("-="); //SENTENCIAS var rif = ToTerm("If"); var relse = ToTerm("Else"); var relseif = ToTerm("Else if"); var rswitch = ToTerm("Switch"); var rcase = ToTerm("Case"); var defecto = ToTerm("Default"); var rfor = ToTerm("For"); var rdo = ToTerm("Do"); var rwhile = ToTerm("While"); //BOOLEANOS var rtrue = ToTerm("true"); var rfalse = ToTerm("false"); //VARIOS var igual1 = ToTerm("="); var dospuntos = ToTerm(":"); var coma = ToTerm(","); var fin = ToTerm(";"); var apar = ToTerm("("); var cpar = ToTerm(")"); var alla = ToTerm("{"); var clla = ToTerm("}"); var acor = ToTerm("["); var ccor = ToTerm("]"); #endregion #region No terminales NonTerminal INICIO = new NonTerminal("INICIO"); NonTerminal IMPORTE = new NonTerminal("IMPORTE"); NonTerminal IMPORTES = new NonTerminal("IMPORTES"); NonTerminal CUERPO = new NonTerminal("CUERPO"); NonTerminal CONTENIDOGENERAL = new NonTerminal("CONTENIDOGENERAL"); NonTerminal ASIGNA = new NonTerminal("ASIGNA"); NonTerminal DECLARA = new NonTerminal("DECLARA"); NonTerminal LISTA_IDS = new NonTerminal("LISTA_IDS"); NonTerminal TIPODATO = new NonTerminal("TIPODATO"); NonTerminal VALOR = new NonTerminal("VALOR"); NonTerminal EXPRESION = new NonTerminal("EXPRESION"); NonTerminal METODO = new NonTerminal("METODO"); NonTerminal LISTAPARAMETROS = new NonTerminal("LISTAPARAMETROS"); NonTerminal CUERPOMETODO = new NonTerminal("CUERPOMETODO"); NonTerminal LLAMADAMETODO = new NonTerminal("LLAMADAMETODO"); NonTerminal IMPRIMIR = new NonTerminal("IMPRIMIR"); NonTerminal PARAMETROSLLAMADOS = new NonTerminal("PARAMETROSLLAMADOS"); NonTerminal OPCIONAL = new NonTerminal("OPCIONAL"); NonTerminal SENTENCIARETURN = new NonTerminal("SENTENCIARETURN"); NonTerminal SENTENCIAWHILE = new NonTerminal("SENTENCIAWHILE"); NonTerminal SENTENCIADOWHILE = new NonTerminal("SENTENCIADOWHILE"); NonTerminal SENTENCIASWITCH = new NonTerminal("SENTENCIASWITCH"); NonTerminal CASO = new NonTerminal("CASO"); NonTerminal CASOS = new NonTerminal("CASOS"); NonTerminal DEFECTO = new NonTerminal("DEFECTO"); NonTerminal CONTENIDOSWITCH = new NonTerminal("CONTENIDOSWITCH"); NonTerminal LISTA_ARRAY = new NonTerminal(" LISTA_ARRAY"); NonTerminal CONDICION = new NonTerminal("CONDICION"); NonTerminal CONDICIONPRIMA = new NonTerminal("CONDICIONPRIMA"); NonTerminal CONDICIONAL = new NonTerminal("CONDICIONAL"); NonTerminal LOGICOS = new NonTerminal("LOGICOS"); NonTerminal RELACIONAL = new NonTerminal("RELACIONAL"); NonTerminal SENTENCIAIF = new NonTerminal("SENTENCIAIF"); NonTerminal SENTENCIAIFAUX = new NonTerminal("SENTENCIAIFAUX"); NonTerminal SENTPRIMA = new NonTerminal("SENTPRIMA"); NonTerminal SENTENCIAELSEIF = new NonTerminal("SENTENCIAELSEIF"); NonTerminal SENTENCIA = new NonTerminal("SENTENCIA"); NonTerminal SENTENCIAS = new NonTerminal("SENTENCIAS"); NonTerminal SENTENCIAFOR = new NonTerminal("SENTENCIAFOR"); NonTerminal ASIGNACION_CORTO = new NonTerminal("ASIGNACION_CORTO"); NonTerminal C = new NonTerminal("C"); NonTerminal D = new NonTerminal("D"); NonTerminal OPMATEMATICA = new NonTerminal("OPMATEMATICA"); NonTerminal OP = new NonTerminal("OP"); NonTerminal E = new NonTerminal("E"); NonTerminal L = new NonTerminal("L"); NonTerminal R = new NonTerminal("R"); NonTerminal INVOCAR = new NonTerminal("INVOCAR"); NonTerminal LIST_ATRIBUTO = new NonTerminal("LIST_ATRIBUTO"); NonTerminal ACCESO_VECTOR = new NonTerminal("ACCESO_VECTOR"); NonTerminal ATRIBUTO = new NonTerminal("ATRIBUTO"); #endregion #region Gramatica INICIO.Rule = IMPORTES + CUERPO; IMPORTES.Rule = IMPORTES + IMPORTE | IMPORTE | Empty; IMPORTE.Rule = importar + importaciones + fin; CUERPO.Rule = CUERPO + CONTENIDOGENERAL | CONTENIDOGENERAL; CONTENIDOGENERAL.Rule = DECLARA | ASIGNA | METODO; DECLARA.Rule = id + dospuntos + TIPODATO + VALOR | LISTA_IDS + dospuntos + TIPODATO + VALOR | id + dospuntos + TIPODATO + acor + E + ccor + VALOR; ASIGNA.Rule = id + igual1 + C + fin | id + igual1 + alla + LISTA_ARRAY + clla + fin | id + acor + E + ccor + igual1 + C + fin | id + acor + E + ccor + igual1 + id + acor + E + ccor + fin; VALOR.Rule = igual1 + C + fin | fin | alla + LISTA_ARRAY + clla + fin; LISTA_IDS.Rule = LISTA_IDS + coma + id | id; LISTA_ARRAY.Rule = LISTA_ARRAY + coma + C | C; TIPODATO.Rule = rint | rdouble | rstring | rchar | rbool | rvoid; METODO.Rule = id + dospuntos + TIPODATO + apar + LISTAPARAMETROS + cpar + alla + SENTENCIAS + clla | rmain + dospuntos + TIPODATO + apar + LISTAPARAMETROS + cpar + alla + SENTENCIAS + clla; LISTAPARAMETROS.Rule = LISTAPARAMETROS + coma + id + dospuntos + TIPODATO | id + dospuntos + TIPODATO | Empty; SENTENCIAS.Rule = SENTENCIAS + SENTENCIA | SENTENCIA; SENTENCIA.Rule = ASIGNA | DECLARA | LLAMADAMETODO + fin | IMPRIMIR | SENTENCIAFOR | SENTENCIAIF | SENTENCIARETURN | SENTENCIAWHILE | SENTENCIADOWHILE | SENTENCIASWITCH | Empty; //---------LLAMADA A METODO LLAMADAMETODO.Rule = id + apar + PARAMETROSLLAMADOS + cpar | id + apar + cpar; PARAMETROSLLAMADOS.Rule = PARAMETROSLLAMADOS + coma + C | C; //---------PRINT IMPRIMIR.Rule = rprint + apar + C + cpar; //---------RETURN SENTENCIARETURN.Rule = C + fin | fin; //---------FOR //falta contenido SENTENCIAFOR.Rule = rfor + apar + id + dospuntos + TIPODATO + igual1 + E + fin + C + fin + OP + cpar + alla + SENTENCIAS + clla; //---------IF SENTENCIAIF.Rule = rif + SENTENCIAIFAUX; SENTENCIAIFAUX.Rule = apar + C + cpar + alla + SENTENCIAS + clla + SENTENCIAELSEIF; SENTENCIAIFAUX.ErrorRule = SyntaxError + "}"; SENTENCIAELSEIF.Rule = relse + SENTPRIMA | Empty; SENTENCIAELSEIF.ErrorRule = SyntaxError + "}"; SENTPRIMA.Rule = rif + SENTENCIAIFAUX | alla + SENTENCIAS + clla; //---------WHILE SENTENCIAWHILE.Rule = rwhile + apar + C + cpar + alla + SENTENCIAS + clla; SENTENCIAWHILE.ErrorRule = SyntaxError + "}"; //---------DO WHILE SENTENCIADOWHILE.Rule = rdo + alla + SENTENCIAS + clla + rwhile + apar + C + cpar + fin; SENTENCIADOWHILE.ErrorRule = SyntaxError + ";"; ///--------SWITCH SENTENCIASWITCH.Rule = rswitch + apar + E + cpar + alla + SENTENCIAS + clla; SENTENCIASWITCH.ErrorRule = SyntaxError + "}"; CONTENIDOSWITCH.Rule = CASOS + DEFECTO | CASOS | DEFECTO | Empty; CASOS.Rule = CASOS + CASO | CASO; //---FALTA CONTENIDO CASO.Rule = rcase + C + dospuntos + SENTENCIAS + rbreak + fin; //---FALTA CONTENIDO DEFECTO.Rule = defecto + SENTENCIAS + dospuntos; //CONDICION ASIGNACION_CORTO.Rule = id + OP; OP.Rule = incremento | decremento; C.Rule = C + L + C | E + R + E | menos + E | E; R.Rule = igual2 | diferente | menor | mayor | menorigual | mayorigual; L.Rule = ror | rand | rxor | rnot; E.Rule = E + mas + E | E + menos + E | E + por + E | E + dividir + E | E + modulo + E | E + potencia + E | apar + E + cpar | id | numentero | numdecimal | cadena | caracter | rtrue | rfalse; INVOCAR.Rule = id + apar + LIST_ATRIBUTO + cpar | ACCESO_VECTOR; LIST_ATRIBUTO.Rule = LIST_ATRIBUTO + coma + ATRIBUTO | ATRIBUTO | Empty; ATRIBUTO.Rule = E; #endregion #region PREFERENCIAS Root = INICIO; NonGrammarTerminals.Add(comentarioLinea); NonGrammarTerminals.Add(comentarioBloque); MarkPunctuation(";", "(", ")", "{", "}", ":", "=", "[", "]", ","); this.RegisterOperators(1, Associativity.Left, mas, menos); this.RegisterOperators(2, Associativity.Left, por, dividir, modulo); this.RegisterOperators(3, Associativity.Right, potencia); this.RegisterOperators(5, igual2, diferente, menor, mayor, menorigual, mayorigual); this.RegisterOperators(6, Associativity.Left, ror); this.RegisterOperators(7, Associativity.Left, rxor); this.RegisterOperators(8, Associativity.Left, rand); this.RegisterOperators(9, Associativity.Left, diferente); this.RegisterOperators(10, apar, cpar); #endregion }
private void InitializeSyntax() { #region Identifiers var id_literal = TerminalFactory.CreateCSharpIdentifier("IDENTIFICADOR"); var number_literal = TerminalFactory.CreateCSharpNumber("NUMERO"); var string_literal = TerminalFactory.CreateCSharpString("CADENA"); var true_literal = ToTerm("TRUE", "LOGICO_TRUE"); var false_literal = ToTerm("FALSE", "LOGICO_FALSE"); #endregion #region NonTerminal NonTerminal program = new NonTerminal("PROGRAMA"); NonTerminal define_dec = new NonTerminal("DEFINIR"); NonTerminal define_list = new NonTerminal("DEFINICIONES"); NonTerminal import_dec = new NonTerminal("IMPORTAR"); NonTerminal import_list = new NonTerminal("IMPORTACIONES"); NonTerminal member = new NonTerminal("MIEMBRO"); NonTerminal member_list = new NonTerminal("MIEMBROS"); NonTerminal var_dec = new NonTerminal("VARIABLE"); NonTerminal var_type = new NonTerminal("TIPO"); NonTerminal var_dec_list = new NonTerminal("VARIABLES"); NonTerminal var_dec_list_names = new NonTerminal("LISTA_VARIABLES"); NonTerminal var_dec_asign = new NonTerminal("VARIABLE_DECLARACION"); NonTerminal function_dec = new NonTerminal("FUNCION"); NonTerminal function_type = new NonTerminal("TIPO_FUNCION"); NonTerminal parameters = new NonTerminal("PARAMETROS"); NonTerminal parameter = new NonTerminal("PARAMETRO"); NonTerminal var_asign = new NonTerminal("ASIGNACION_VARIABLE"); NonTerminal print = new NonTerminal("MOSTRAR"); NonTerminal statements = new NonTerminal("SENTENCIAS"); NonTerminal statement = new NonTerminal("SENTENCIA"); NonTerminal op = new NonTerminal("OPERANDO"); NonTerminal ar = new NonTerminal("OPERACION"); NonTerminal operand = new NonTerminal("OPERANDO"); NonTerminal ao = new NonTerminal("AR_OP"); NonTerminal expression = new NonTerminal("EXPRESION"); NonTerminal co = new NonTerminal("COMPARADOR"); NonTerminal bo = new NonTerminal("OPERADOR_BOOLEANO"); NonTerminal scope = new NonTerminal("AMBITO"); NonTerminal if_block = new NonTerminal("SI"); NonTerminal else_dec = new NonTerminal("SINO"); #endregion #region Gramaticas #region Program NonTerminal program_member = new NonTerminal("MIEMBRO_PROGRAMA"); program.Rule = MakeStarRule(program, program_member); program_member.Rule = import_dec + ";" | define_dec + ";" | var_dec + ToTerm(";") | function_dec; #endregion #region Import import_dec.Rule = "Importar" + string_literal; #endregion #region Definir define_dec.Rule = "Definir" + string_literal | "Definir" + number_literal; #endregion #region Funciones function_dec.Rule = ToTerm("Vacio") + id_literal + ToTerm("(") + parameters + ToTerm(")") + scope | var_type + id_literal + ToTerm("(") + parameters + ToTerm(")") + scope; function_type.Rule = var_type | ToTerm("Vacio"); parameters.Rule = MakeStarRule(parameters, ToTerm(","), parameter); parameter.Rule = var_type + id_literal; NonTerminal func_call = new NonTerminal("LLAMADA_FUNCION"); NonTerminal func_call_params = new NonTerminal("PARAMETROS_LLAMADA"); func_call.Rule = id_literal + ToTerm("(") + func_call_params + ToTerm(")"); func_call_params.Rule = MakeStarRule(func_call_params, ToTerm(","), expression); NonTerminal func_return = new NonTerminal("RETORNO") { Rule = "Retorno" + expression | "Retorno" }; #endregion #region Variables var_dec.Rule = var_type + var_dec_list_names | var_type + var_dec_list_names + ToTerm("=") + expression; var_type.Rule = ToTerm("Int") | ToTerm("Char") | ToTerm("Bool") | ToTerm("String") | ToTerm("Double"); var_dec_list_names.Rule = MakePlusRule(var_dec_list_names, ToTerm(","), id_literal); var_asign.Rule = id_literal + ToTerm("=") + expression; #endregion #region Expresion op.Rule = string_literal | number_literal | id_literal | true_literal | false_literal | func_call; ar.Rule = ar + ToTerm("+") + ar | ar + ToTerm("-") + ar | ar + ToTerm("*") + ar | ar + ToTerm("/") + ar | ar + ToTerm("^") + ar | ar + ToTerm("~") + ar | ar + ToTerm("%") + ar | ToTerm("(") + ar + ToTerm(")") | ToTerm("-") + ar | op; ao.Rule = ToTerm("+") | ToTerm("-") | ToTerm("/") | ToTerm("*"); expression.Rule = expression + bo + expression | ToTerm("!") + operand | operand; operand.Rule = ar | ar + co + ar; bo.Rule = ToTerm("&&") | ToTerm("||") | ToTerm("|&"); co.Rule = ToTerm(">") | ToTerm(">=") | ToTerm("<") | ToTerm("<=") | ToTerm("==") | ToTerm("!="); #endregion #region print print.Rule = ToTerm("Mostrar") + ToTerm("(") + func_call_params + ToTerm(")"); #endregion #region If Else if_block.Rule = ToTerm("Si") + "(" + expression + ")" + scope | ToTerm("Si") + "(" + expression + ")" + scope + else_dec; else_dec.Rule = ToTerm("Sino") + scope; #endregion #region While NonTerminal while_block = new NonTerminal("MIENTRAS") { Rule = "Mientras" + ToTerm("(") + expression + ToTerm(")") + scope }; #endregion #region Repetir NonTerminal repeat_block = new NonTerminal("REPETIR") { Rule = ToTerm("Hasta") + ToTerm("(") + expression + ToTerm(")") + scope }; #endregion #region Para NonTerminal for_var_asign = new NonTerminal("VARIABLE") { Rule = ToTerm("Double") + id_literal + "=" + expression }; NonTerminal for_var_action = new NonTerminal("ACCION_FOR") { Rule = ToTerm("++") | ToTerm("--") }; NonTerminal for_block = new NonTerminal("PARA") { Rule = ToTerm("Para") + ToTerm("(") + for_var_asign + ";" + expression + ";" + for_var_action + ToTerm(")") + scope }; #endregion #region Break NonTerminal break_stmt = new NonTerminal("DETENER") { Rule = ToTerm("Detener") }; #endregion #region Continue NonTerminal continue_stmt = new NonTerminal("CONTINUAR") { Rule = ToTerm("Continuar") }; #endregion #region Selecciona NonTerminal switch_block = new NonTerminal("SELECCIONA"); NonTerminal switch_body = new NonTerminal("CASOS"); NonTerminal case_block = new NonTerminal("CASO"); NonTerminal def_block = new NonTerminal("DEFECTO"); NonTerminal case_list = new NonTerminal("LISTA_CASOS"); switch_block.Rule = "Selecciona" + ToTerm("(") + expression + ToTerm(")") + switch_body; case_block.Rule = expression + ToTerm(":") + statements; case_list.Rule = MakePlusRule(case_list, case_block); switch_body.Rule = ToTerm("{") + case_list + def_block + ToTerm("}") | ToTerm("{") + case_list + ToTerm("}"); def_block.Rule = "Defecto" + ToTerm(":") + statements; #endregion #region Statements scope.Rule = ToTerm("{") + statements + ToTerm("}"); statements.Rule = MakeStarRule(statements, statement); statement.Rule = var_dec + ";" | var_asign + ";" | if_block | switch_block | while_block | repeat_block | for_block | func_call + ";" | func_return + ";" | print + ";" | continue_stmt + ";" | break_stmt + ";"; statement.ErrorRule = SyntaxError + ";" | SyntaxError + "}"; #endregion #endregion #region Preferencias MarkReservedWords("Importar", "Definir", "Int", "String", "Bool", "Char", "Double", "Vacio", "Si", "Sino", "true", "false", "Retorno", "Continuar", "Detener", "Mientras", "Para"); MarkTransient(scope, member, member_list, statement, var_type, for_var_action); RegisterBracePair("(", ")"); RegisterBracePair("{", "}"); RegisterOperators(1, Associativity.Left, ToTerm("+"), ToTerm("-")); RegisterOperators(2, Associativity.Left, ToTerm("/"), ToTerm("*"), ToTerm("%")); RegisterOperators(3, Associativity.Left, ToTerm("^")); //comparissons RegisterOperators(4, Associativity.Left, ToTerm("<"), ToTerm(">"), ToTerm("<="), ToTerm(">="), ToTerm("~")); //booleans RegisterOperators(5, Associativity.Left, ToTerm("||")); RegisterOperators(6, Associativity.Left, ToTerm("|&")); RegisterOperators(7, Associativity.Left, ToTerm("&&")); RegisterOperators(8, Associativity.Right, ToTerm("!")); RegisterOperators(9, Associativity.Left, ToTerm("("), ToTerm(")")); Root = program; #endregion }
public SparkGrammar() : base(true) { var program = new NonTerminal("Program"); var statement = new NonTerminal("Statement"); var assignStmt = new NonTerminal("AssignStatement"); var commandStmt = new NonTerminal("CommandStatement"); var assignRHS = new NonTerminal("AssignRHS"); var createLayer = new NonTerminal("CreateLayer"); var createNetwork = new NonTerminal("CreateNetwork"); var createTrainer = new NonTerminal("CreateTrainer"); var runNetwork = new NonTerminal("RunNetwork"); var loadFile = new NonTerminal("LoadFile"); var convertData = new NonTerminal("ConvertData"); var findError = new NonTerminal("FindError"); var basicNetwork = new NonTerminal("BasicNetwork"); var advancedNetwork = new NonTerminal("AdvancedNetwork"); var matrixLoadType = new NonTerminal("MatrixLoadType"); var convertToVector = new NonTerminal("ConvertToVector"); var convertToIndices = new NonTerminal("ConvertToIndices"); var supportedFileTypes = new NonTerminal("SupportedFileTypes"); var printStatement = new NonTerminal("PrintStatement"); var trainStatement = new NonTerminal("TrainStatement"); var saveStatement = new NonTerminal("SaveStatement"); var kvPair = new NonTerminal("KeyValuePair"); var identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); var number = TerminalFactory.CreateCSharpNumber("Number"); var str = TerminalFactory.CreateCSharpString("string"); program.Rule = statement + ";" | statement + ";" + program; statement.Rule = assignStmt | commandStmt; assignStmt.Rule = identifier + "=" + assignRHS; assignRHS.Rule = createLayer | createNetwork | createTrainer | runNetwork | loadFile | convertData | findError; createLayer.Rule = ToTerm("layer") + "with" + kvPair; createNetwork.Rule = basicNetwork | advancedNetwork; basicNetwork.Rule = identifier + "->" + identifier; advancedNetwork.Rule = createNetwork + "->" + identifier; runNetwork.Rule = ToTerm("run") + identifier + "on" + identifier; loadFile.Rule = ToTerm("load") + str + "as" + matrixLoadType | ToTerm("load") + supportedFileTypes + str + "as" + matrixLoadType; matrixLoadType.Rule = ToTerm("row") + "major" | ToTerm("row") + "major" + "with" + "headers" | ToTerm("column") + "major"; createTrainer.Rule = ToTerm("trainer") + "of" + "type" + identifier + "with" + kvPair; kvPair.Rule = identifier + "=" + (number | identifier) | identifier + "=" + (number | identifier) + "," + kvPair; convertData.Rule = convertToVector | convertToIndices; convertToVector.Rule = ToTerm("convert") + identifier + "to" + "class" + "vector" | ToTerm("convert") + identifier + "to" + "class" + "vector" + "of" + "size" + "=" + number; convertToIndices.Rule = ToTerm("convert") + identifier + "to" + "class" + "indices"; findError.Rule = ToTerm("count") + "mismatches" + "between" + identifier + "and" + identifier | ToTerm("get") + "mismatches" + "between" + identifier + "and" + identifier; commandStmt.Rule = printStatement | trainStatement | saveStatement; printStatement.Rule = ToTerm("print") + identifier; trainStatement.Rule = ToTerm("train") + identifier + "with" + identifier + "on" + "inputs" + identifier + "and" + "targets" + identifier; saveStatement.Rule = ToTerm("save") + identifier + "to" + str | ToTerm("save") + identifier + "as" + supportedFileTypes + "to" + str; supportedFileTypes.Rule = ToTerm("csv") | "tsv" | "ssv"; MarkPunctuation("layer", "run", "train", "trainer", "on", "and", "inputs", "targets", "major", "load", "save", "print", "type", "indices", "convert", "class", "vector", "of", "mismatches", "between", "size", "as", "to", "with", "of", "as", ";", ",", "=", "->"); this.Root = program; }
public TuringGrammarBroken() { //Expr -> n | v | Expr BinOp Expr | UnOP Expr | ( Expr ) //BinOp -> + | - | * | / | ** //UnOp -> - //ExprLine -> Expr EOF //1. Terminals Terminal num = new NumberLiteral("number"); Terminal iden = new IdentifierTerminal("identifier"); Terminal stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral"); Terminal charLiteral = new StringLiteral("charLiteral", "'", StringOptions.IsChar); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //2. Non-Terminals var expandedIdentifier = new NonTerminal("expandedIndentifier"); var Expr = new NonTerminal("expr"); var BinOp = new NonTerminal("binOp", "operator"); var BinExpr = new NonTerminal("binExpr"); var unOp = new NonTerminal("unOp"); var unExpr = new NonTerminal("unExpr"); var ParExpr = new NonTerminal("parExpr"); var Statement = new NonTerminal("statement"); var Program = new NonTerminal("program"); var setEqual = new NonTerminal("setEqual"); var varType = new NonTerminal("varType"); var variableDeclaration = new NonTerminal("variableDeclaration"); var varOrConst = new NonTerminal("varOrConst"); var idenList = new NonTerminal("identifierList"); var assignment = new NonTerminal("assignment"); var typeSpecifier = new NonTerminal("typeSpecifier"); var ifBlock = new NonTerminal("ifBlock"); var elseIfBlock = new NonTerminal("elseIfBlock"); var optElseBlock = new NonTerminal("optElseBlock"); var caseBlock = new NonTerminal("caseBlock"); var labelBlock = new NonTerminal("labelBlock"); var functionCall = new NonTerminal("functionCall"); var args = new NonTerminal("args"); var functionDefinition = new NonTerminal("functionDefinition"); var optParams = new NonTerminal("optParams"); var parameters = new NonTerminal("parameters"); var parameter = new NonTerminal("parameter"); var io = new NonTerminal("io"); var optSameLine = new NonTerminal("optionalSameLine"); var putItem = new NonTerminal("putItem"); var widthExpn = new NonTerminal("widthExpn"); var fractionWidth = new NonTerminal("fractionWidth"); var exponentWidth = new NonTerminal("exponentWidth"); var streamNumber = new NonTerminal("streamNumber"); var putItems = new NonTerminal("putItems"); var loop = new NonTerminal("loop"); var forLoop = new NonTerminal("forLoop"); var optDecreasing = new NonTerminal("optDecreasing"); var optIncrementBy = new NonTerminal("optIncrementBy"); var exitLoop = new NonTerminal("exitLoop"); var initExpr = new NonTerminal("initExpr"); var and = new NonTerminal("and"); var or = new NonTerminal("or"); var not = new NonTerminal("not"); var result = new NonTerminal("result"); var recordList = new NonTerminal("recordList"); var type = new NonTerminal("type"); var memberCall = new NonTerminal("memberCall"); var range = new NonTerminal("range"); var boolean = new NonTerminal("boolean"); var ioArgs = new NonTerminal("ioArgs"); var newer = new NonTerminal("new"); var assignmentOp = new NonTerminal("assignmentOp"); var overrideName = new NonTerminal("overrideName"); var externalOverrideName = new NonTerminal("externalOverrideName"); var externalDeclaration = new NonTerminal("externalDeclaration"); var functionHeader = new NonTerminal("functionHeader"); var importOrInclude = new NonTerminal("importOrInclude"); var importSection = new NonTerminal("importSection"); var import = new NonTerminal("import"); var include = new NonTerminal("include"); var unit = new NonTerminal("unit"); //3. BNF rules varType.Rule = ToTerm("int") | "nat" | "string" | "real" | "boolean" | "array" + range + "of" + varType | ToTerm("flexible") + "array" + range + "of" + varType | "record" + recordList + "end" + "record" | "int1" | "int2" | "int4" | "real1" | "real2" | "real4" | "nat1" | "nat2" | "nat4" | ToTerm("char") + "(" + num + ")" | ToTerm("string") + "(" + num + ")" | iden; range.Rule = Expr + ".." + Expr | "char" | iden; setEqual.Rule = assignmentOp + Expr; assignmentOp.Rule = ToTerm(":=") | "+=" | "-=" | "*=" | "/=" | "div=" | "mod=" | "rem=" | "shl=" | "shr=" | "xor="; typeSpecifier.Rule = ToTerm(":") + varType; Expr.Rule = num | iden | BinExpr | ParExpr | stringLiteral | charLiteral | unExpr | functionCall | memberCall | boolean | initExpr; initExpr.Rule = ToTerm("init") + "(" + args + ")"; BinOp.Rule = ToTerm("-") | "*" | "/" | "**" | "+" | "div" | "mod" | and | or | "=" | ">" | "<" | ">=" | "<=" | "~=" | "not="; BinOp.Precedence = 1; unOp.Rule = not | "-"; unOp.Precedence = 2; BinExpr.Rule = Expr + PreferShiftHere() + BinOp + Expr; unExpr.Rule = unOp + Expr; ParExpr.Rule = "(" + Expr + ")"; boolean.Rule = ToTerm("true") | "false"; assignment.Rule = expandedIdentifier + setEqual; args.Rule = MakeStarRule(args, ToTerm(","), Expr); //args.Rule = Expr + "," + args | Expr; functionCall.Rule = iden + "(" + args + ")"; overrideName.Rule = stringLiteral; externalOverrideName.Rule = overrideName | Empty; externalDeclaration.Rule = "external" + externalOverrideName + functionHeader; optSameLine.Rule = ToTerm("..") | Empty; io.Rule = ToTerm("put") + ":" + streamNumber + "," + putItem + putItems + optSameLine | ToTerm("get") + args | ToTerm("put") + putItem + putItems + optSameLine | ToTerm("get") + ":" + args | ToTerm("open") + ":" + iden + "," + Expr + "," + ioArgs | ToTerm("close") + ":" + iden; putItem.Rule = Expr | Expr + ":" + widthExpn | Expr + ":" + widthExpn + ":" + fractionWidth | Expr + ":" + widthExpn + ":" + fractionWidth + ":" + exponentWidth | "skip"; putItems.Rule = "," + putItem + putItems | Empty; ioArgs.Rule = ToTerm("get") | "put" | "write" | "read" | "seek" | "tell" | ioArgs + PreferShiftHere() + "," + ioArgs; streamNumber.Rule = widthExpn.Rule = fractionWidth.Rule = exponentWidth.Rule = Expr; newer.Rule = ToTerm("new") + iden + "," + Expr; optParams.Rule = ToTerm("(") + parameters + ")" | ToTerm("(") + ")" | Empty; parameters.Rule = parameter + "," + parameters | parameter; parameter.Rule = idenList + typeSpecifier | "var" + idenList + typeSpecifier; //functionHeader.Rule = (ToTerm("function") | "fcn") + iden + optParams + typeSpecifier | (ToTerm("procedure") | "proc") + iden + optParams; functionHeader.Rule = "function" + iden + optParams + typeSpecifier | "fcn" + iden + optParams + typeSpecifier | "procedure" + iden + optParams | "proc" + iden + optParams; functionDefinition.Rule = functionHeader + Program + "end" + iden; //"function" + iden + optParams + typeSpecifier + Program + "end" + iden //| "fcn" + iden + optParams + typeSpecifier + Program + "end" + iden //| "procedure" + iden + optParams + Program + "end" + iden //| "proc" + iden + optParams + Program + "end" + iden; ifBlock.Rule = ToTerm("if") + Expr + ToTerm("then") + Program + elseIfBlock + optElseBlock + ToTerm("end") + "if"; elseIfBlock.Rule = ToTerm("elsif") + Expr + ToTerm("then") + Program + elseIfBlock | Empty; optElseBlock.Rule = ToTerm("else") + Program | Empty; caseBlock.Rule = ToTerm("case") + iden + "of" + labelBlock + "end case"; labelBlock.Rule = ToTerm("label") + Expr + ":" + Program + labelBlock | ToTerm("label") + ":" + labelBlock | Empty; idenList.Rule = iden + "," + idenList | iden; varOrConst.Rule = ToTerm("var") | "const"; variableDeclaration.Rule = varOrConst + idenList | varOrConst + idenList + setEqual | varOrConst + idenList + typeSpecifier | varOrConst + idenList + typeSpecifier + setEqual; loop.Rule = "loop" + Program + "end" + "loop"; optDecreasing.Rule = "decreasing" | Empty; optIncrementBy.Rule = "by" + Expr | Empty; forLoop.Rule = "for" + optDecreasing + iden + ":" + range + optIncrementBy + Program + "end" + "for"; exitLoop.Rule = ToTerm("exit") | ToTerm("exit") + "when" + Expr; and.Rule = ToTerm("and") | "&"; or.Rule = ToTerm("or") | "|"; not.Rule = ToTerm("not") | "~" | "!"; result.Rule = "result" + Expr | "return" + Expr; recordList.Rule = idenList + typeSpecifier + recordList | Empty; type.Rule = "type" + iden + typeSpecifier; memberCall.Rule = expandedIdentifier + PreferShiftHere() + "." + expandedIdentifier; //memberCall.Rule = iden + "." + functionCall | iden + "." + iden | iden + "." + memberCall; importOrInclude.Rule = import | include; import.Rule = "import" + expandedIdentifier | "import" + expandedIdentifier + "in" + stringLiteral; include.Rule = "include" + stringLiteral; importSection.Rule = MakeStarRule(importSection, importOrInclude); unit.Rule = "unit" + importSection + Program | importSection + Program; expandedIdentifier.Rule = iden | functionCall | memberCall; //Statement.Rule = functionCall | memberCall | iden | variableDeclaration | ifBlock | caseBlock | functionCall | functionDefinition | io | assignment | result | loop | forLoop | type | newer | exitLoop | externalDeclaration; Statement.Rule = functionCall | expandedIdentifier | variableDeclaration | ifBlock | caseBlock | functionDefinition | io | assignment | result | loop | forLoop | type | newer | exitLoop | externalDeclaration; Program.Rule = Statement + Program | Empty; this.Root = unit; //4. Set operator precendence and associativity RegisterOperators(05, Associativity.Left, "not"); RegisterOperators(10, Associativity.Left, "=", "not=", ">=", "<=", "<", ">", "!=", "~="); RegisterOperators(30, Associativity.Left, "+", "-"); RegisterOperators(40, Associativity.Left, "*", "/", "div", "mod"); RegisterOperators(50, Associativity.Right, "**"); //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree MarkPunctuation("(", ")", ",", "external", "if", "end", "then", "elsif", "else", "init", "loop", "for", "by", ":", "..", "import", "include", "in", ".", "type", "record"); RegisterBracePair("(", ")"); //MarkTransient(Expr, BinOp, ParExpr, assignmentOp, varOrConst); MarkTransient(Expr, BinOp, ParExpr, assignmentOp, varOrConst, expandedIdentifier, overrideName, externalOverrideName, importOrInclude); MarkReservedWords("not=", "init"); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF;//| LanguageFlags.CreateAst; }
public Grammar() : base(caseSensitive: false) { #region ER RegexBasedTerminal num = new RegexBasedTerminal("num", "[0-9]+"); RegexBasedTerminal dec = new RegexBasedTerminal("dec", "[0-9]+[.][0-9]+"); RegexBasedTerminal rtrue = new RegexBasedTerminal("rtrue", "true|verdadero"); RegexBasedTerminal rfalse = new RegexBasedTerminal("rfalse", "false|falso"); CommentTerminal com_linea = new CommentTerminal("comentariolinea", ">>", "\n", "\r\n"); CommentTerminal comentarioBloque = new CommentTerminal("comentarioBloque", "<-", "->"); CommentTerminal com_multi = new CommentTerminal("comentariomulti", "<-", "->"); StringLiteral StringLiteral = TerminalFactory.CreateCSharpString("String"); StringLiteral CharLiteral = TerminalFactory.CreateCSharpChar("Char"); IdentifierTerminal identifier = new IdentifierTerminal("Identifier"); NonGrammarTerminals.Add(com_linea); NonGrammarTerminals.Add(comentarioBloque); NonGrammarTerminals.Add(com_multi); #endregion #region Terminales /*simbolos*/ var igual = ToTerm("="); var aumento = ToTerm("++"); var decremento = ToTerm("--"); var punto = ToTerm("."); /*aritmeticos*/ var mas = ToTerm("+"); var menos = ToTerm("-"); var por = ToTerm("*"); var entre = ToTerm("/"); var elevado = ToTerm("^"); /*relacionales*/ var igualLogico = ToTerm("=="); var desigual = ToTerm("!="); var mayor = ToTerm(">"); var mayorigual = ToTerm(">="); var menor = ToTerm("<"); var menorigual = ToTerm("<="); /*logicos*/ var or = ToTerm("||"); var and = ToTerm("&&"); var not = ToTerm("!"); /*tipos de dato*/ var rint = ToTerm("int"); var rdouble = ToTerm("double"); var rbool = ToTerm("bool"); var rchar = ToTerm("char"); var rstring = ToTerm("string"); var rarray = ToTerm("array"); /*Reservadas*/ var rclase = ToTerm("clase"); var rimportar = ToTerm("importar"); var rvoid = ToTerm("void"); var rpublico = ToTerm("publico"); var rprivado = ToTerm("privado"); var rreturn = ToTerm("return"); var rnew = ToTerm("new"); var roverride = ToTerm("override"); var rmain = ToTerm("main"); var rprint = ToTerm("print"); var rshow = ToTerm("show"); /*sentencias*/ var rif = ToTerm("if"); var relse = ToTerm("else"); var rfor = ToTerm("for"); var rrepeat = ToTerm("repeat"); var rwhile = ToTerm("while"); var rcomprobar = ToTerm("comprobar"); var rcaso = ToTerm("caso"); var rsalir = ToTerm("salir"); var rdefecto = ToTerm("defecto"); var rhacer = ToTerm("hacer"); var rmientras = ToTerm("mientras"); var rcontinuar = ToTerm("continuar"); /*figure*/ var raddfigure = ToTerm("addfigure"); var rcircle = ToTerm("circle"); var rtriangle = ToTerm("triangle"); var rsquare = ToTerm("square"); var rline = ToTerm("line"); var rfigure = ToTerm("figure"); #endregion #region No Terminales NonTerminal S = new NonTerminal("S"), E = new NonTerminal("E"), FUNCION = new NonTerminal("Funcion"), PARAMFUNCION = new NonTerminal("ParamFuncion"), BLOQUE = new NonTerminal("BLOQUE"), LISTA_BLOQUE = new NonTerminal("LISTA_BLOQUE"), ASIGNACION = new NonTerminal("Asignacion"), DECLARACION = new NonTerminal("Declaracion"), METODOS = new NonTerminal("Metodos"), SENTENCIAS = new NonTerminal("Sentencias"), LID = new NonTerminal("ListaId"), T_DATO = new NonTerminal("TipoDato"), DIM = new NonTerminal("Dimension"), LDIM = new NonTerminal("LDim"), DIM1 = new NonTerminal("Dim1"), DIM2 = new NonTerminal("Dim2"), DIM3 = new NonTerminal("Dim3"), LISTACLASE = new NonTerminal("ListaClase"), BLOCKCLASE = new NonTerminal("Bloqueclase"), LPARAMETROS = new NonTerminal("ListaParametros"), VISIBILIDAD = new NonTerminal("Visibilidad"), OVERRIDE = new NonTerminal("Override"), LISTAMSENTENCIA = new NonTerminal("ListaMSentencia"), MSENTENCIA = new NonTerminal("MSentencia"), INMETODO = new NonTerminal("InMetodo"), BLOQUESHOW = new NonTerminal("BloqueShow"), BLOQUEPRINT = new NonTerminal("BloquePrint"), BLOQUEIF = new NonTerminal("BloqueIf"), BLOQUEREPETIR = new NonTerminal("BloqueRepetir"), BLOQUEFOR = new NonTerminal("BloqueFor"), BLOQUEWHILE = new NonTerminal("BloqueWhile"), BLOQUEELSEIF = new NonTerminal("BloqueElseIf"), BLOQUEHACER = new NonTerminal("BloqueHacer"), BLOQUECOMPROBAR = new NonTerminal("BloqueComprobar"), BLOQUECASO = new NonTerminal("BloqueCaso"), ADDFIGURE = new NonTerminal("AddFigure"), FIGURE = new NonTerminal("Figure"), TFIGURE = new NonTerminal("TFigure"), B3 = new NonTerminal("B3"), B2 = new NonTerminal("B2"), MAIN = new NonTerminal("Main"), L1 = new NonTerminal("L1"), C1 = new NonTerminal("C1"), D1 = new NonTerminal("D1"), IF = new NonTerminal("IF"), ElseIF = new NonTerminal("ELSEIF"), ELSE = new NonTerminal("ELSE"), BARREGLO = new NonTerminal("BArreglo"), T_DATO1 = new NonTerminal("TipoDato"); #endregion #region Gramaticas S.Rule = LISTACLASE; LISTACLASE.Rule = MakePlusRule(LISTACLASE, BLOCKCLASE); BLOCKCLASE.Rule = rclase + identifier + ToTerm("{") + LISTA_BLOQUE + ToTerm("}") //3 ya | rclase + identifier + rimportar + LID + ToTerm("{") + LISTA_BLOQUE + ToTerm("}") //5 ya | rclase + identifier + ToTerm("{") + ToTerm("}") //2 ya | rclase + identifier + rimportar + LID + ToTerm("{") + ToTerm("}"); //4 ya LISTA_BLOQUE.Rule = MakePlusRule(LISTA_BLOQUE, BLOQUE); BLOQUE.Rule = VISIBILIDAD + DECLARACION | DECLARACION | ASIGNACION | VISIBILIDAD + METODOS | METODOS | MAIN ; MAIN.Rule = rmain + ToTerm("(") + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); METODOS.Rule = identifier + rvoid + OVERRIDE + ToTerm("(") + LPARAMETROS + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") //4 hijos | identifier + rvoid + OVERRIDE + ToTerm("(") + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") //3 hijos | identifier + T_DATO + OVERRIDE + ToTerm("(") + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") //3 hijos | identifier + T_DATO + OVERRIDE + ToTerm("(") + LPARAMETROS + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") //4 hijos | identifier + rarray + T_DATO + DIM + OVERRIDE + ToTerm("(") + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") //5 hijos | identifier + rarray + T_DATO + DIM + OVERRIDE + ToTerm("(") + LPARAMETROS + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); //6 hijos OVERRIDE.Rule = roverride | Empty; INMETODO.Rule = LISTAMSENTENCIA | Empty; LISTAMSENTENCIA.Rule = MakePlusRule(LISTAMSENTENCIA, MSENTENCIA); MSENTENCIA.Rule = VISIBILIDAD + DECLARACION | DECLARACION | ASIGNACION | BLOQUESHOW //YA | BLOQUEPRINT //YA | BLOQUEREPETIR //YA | BLOQUEWHILE //YA | BLOQUEIF //YA | BLOQUEHACER //YA | BLOQUEFOR //YA | BLOQUECOMPROBAR //YA | ADDFIGURE //YA | FIGURE //YA | FUNCION + ToTerm(";") | D1 + ToTerm(";") | rcontinuar + ToTerm(";") //YA | rsalir + ToTerm(";") //YA | rreturn + E + ToTerm(";"); //YA BLOQUEIF.Rule = IF | IF + ELSE | IF + BLOQUEELSEIF | IF + BLOQUEELSEIF + ELSE; IF.Rule = rif + ToTerm("(") + E + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); ELSE.Rule = relse + ToTerm("{") + INMETODO + ToTerm("}"); ElseIF.Rule = relse + rif + ToTerm("(") + E + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); BLOQUEELSEIF.Rule = MakePlusRule(BLOQUEELSEIF, ElseIF); BLOQUEREPETIR.Rule = rrepeat + ToTerm("(") + E + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); BLOQUEWHILE.Rule = rwhile + ToTerm("(") + E + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); BLOQUEPRINT.Rule = rprint + ToTerm("(") + E + ToTerm(")") + ToTerm(";"); BLOQUESHOW.Rule = rshow + ToTerm("(") + E + ToTerm(",") + E + ToTerm(")") + ToTerm(";") | rshow + ToTerm("(") + E + ToTerm(")") + ToTerm(";"); BLOQUEHACER.Rule = rhacer + ToTerm("{") + INMETODO + ToTerm("}") + rmientras + ToTerm("(") + E + ToTerm(")") + ToTerm(";"); BLOQUEFOR.Rule = rfor + ToTerm("(") + T_DATO + identifier + igual + E + ToTerm(";") + E + ToTerm(";") + ASIGNACION + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}") | rfor + ToTerm("(") + identifier + igual + E + ToTerm(";") + E + ToTerm(";") + ASIGNACION + ToTerm(")") + ToTerm("{") + INMETODO + ToTerm("}"); BLOQUECOMPROBAR.Rule = rcomprobar + ToTerm("(") + E + ToTerm(")") + ToTerm("{") + BLOQUECASO + ToTerm("}"); BLOQUECASO.Rule = MakePlusRule(BLOQUECASO, C1); C1.Rule = rcaso + E + ToTerm(":") + INMETODO | rdefecto + ToTerm(":") + INMETODO; FIGURE.Rule = rfigure + ToTerm("(") + E + ToTerm(")") + ToTerm(";"); ADDFIGURE.Rule = raddfigure + ToTerm("(") + TFIGURE + ToTerm(")") + ToTerm(";"); TFIGURE.Rule = rcircle + ToTerm("(") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(")") | rtriangle + ToTerm("(") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(")") | rsquare + ToTerm("(") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(")") | rline + ToTerm("(") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(",") + E + ToTerm(")"); DECLARACION.Rule = T_DATO + LID + ToTerm(";") | identifier + identifier + ToTerm(";") | T_DATO + LID + igual + E + ToTerm(";") | T_DATO + rarray + LID + DIM + ToTerm(";") | identifier + identifier + igual + rnew + identifier + ToTerm("(") + ToTerm(")") + ToTerm(";") | identifier + identifier + igual + E + ToTerm(";") | T_DATO + rarray + LID + DIM + igual + LDIM + ToTerm(";"); ASIGNACION.Rule = identifier + igual + E + ToTerm(";") //2 hijos ya | identifier + igual + rnew + identifier + ToTerm("(") + ToTerm(")") + ToTerm(";") //3 hijos ya | identifier + DIM + igual + E + ToTerm(";") //3 hijos ya | D1 + DIM + igual + E + ToTerm(";") | D1 + DIM + aumento + ToTerm(";") | D1 + DIM + decremento + ToTerm(";") | identifier + DIM + aumento + ToTerm(";") | identifier + DIM + decremento + ToTerm(";") | identifier + aumento + ToTerm(";") //2 hijos ya | identifier + decremento + ToTerm(";") //2 hijos ya | identifier + aumento | identifier + decremento | D1 + igual + E + ToTerm(";") //2 hijos pendiente | D1 + aumento + ToTerm(";") | D1 + decremento + ToTerm(";") ; LDIM.Rule = ToTerm("{") + DIM1 + ToTerm("}") | ToTerm("{") + DIM2 + ToTerm("}") | ToTerm("{") + DIM3 + ToTerm("}"); DIM3.Rule = MakePlusRule(DIM3, ToTerm(","), B3); B3.Rule = ToTerm("{") + DIM2 + ToTerm("}"); DIM2.Rule = MakePlusRule(DIM2, ToTerm(","), B2); B2.Rule = ToTerm("{") + DIM1 + ToTerm("}"); DIM1.Rule = MakePlusRule(DIM1, ToTerm(","), E); LID.Rule = MakePlusRule(LID, ToTerm(","), identifier); LPARAMETROS.Rule = MakePlusRule(LPARAMETROS, ToTerm(","), L1); L1.Rule = T_DATO + identifier | T_DATO + rarray + identifier + DIM; T_DATO.Rule = rint | rchar | rdouble | rbool | rstring | identifier; T_DATO1.Rule = rint | rchar | rdouble | rbool | rstring; VISIBILIDAD.Rule = rprivado | rpublico; DIM.Rule = ToTerm("[") + E + ToTerm("]") | ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]") | ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]"); E.Rule = E + or + E | E + and + E | not + E | E + mayor + E | E + mayorigual + E | E + menor + E | E + menorigual + E | E + igualLogico + E | E + desigual + E | E + mas + E | E + menos + E | E + por + E | E + entre + E | E + elevado + E | menos + E | D1 + aumento | D1 + decremento | dec | rtrue | rfalse | StringLiteral | CharLiteral | num | ToTerm("(") + E + ToTerm(")") | D1 | BARREGLO | BARREGLO + aumento | BARREGLO + decremento; BARREGLO.Rule = D1 + ToTerm("[") + E + ToTerm("]") | D1 + ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]") | D1 + ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]") + ToTerm("[") + E + ToTerm("]"); D1.Rule = MakePlusRule(D1, punto, identifier) | MakePlusRule(D1, punto, FUNCION); FUNCION.Rule = identifier + ToTerm("(") + PARAMFUNCION + ToTerm(")") | identifier + ToTerm("(") + ToTerm(")"); PARAMFUNCION.Rule = MakePlusRule(PARAMFUNCION, ToTerm(","), E); #endregion #region Preferencias this.Root = S; this.MarkTransient(T_DATO, OVERRIDE, INMETODO, VISIBILIDAD, B2, B3); this.RegisterOperators(1, Associativity.Left, or); this.RegisterOperators(2, Associativity.Left, and); this.RegisterOperators(3, Associativity.Right, not); this.RegisterOperators(4, Associativity.Left, mayor, mayorigual, menor, menorigual, igualLogico, desigual); this.RegisterOperators(5, Associativity.Left, mas, menos); this.RegisterOperators(6, Associativity.Left, por, entre); this.RegisterOperators(7, Associativity.Left, elevado); this.RegisterOperators(8, Associativity.Left, aumento, decremento); this.MarkPunctuation("(", ")", ",", ";", ":", "[", "]", "{", "}", "="); #endregion }
public EntropyGrammar() : base(false) // turns off case-sensitivity { #region definitions #region literals // Str StringLiteral stringLiteral = TerminalFactory.CreateCSharpString("StringLiteral"); // Char StringLiteral charLiteral = TerminalFactory.CreateCSharpChar("CharLiteral"); // Real NumberLiteral number = CreateRealNumber("Number"); #endregion #region non-terminals NonTerminal program = new NonTerminal("program"); //, typeof(ProgramNode)); this.Root = program; // specify the non-terminal which is the root of the AST NonTerminal programDeclaration = new NonTerminal("programDeclaration"); NonTerminal statementList = new NonTerminal("statementList"); //, typeof(StatementListNode)); NonTerminal emptyStatement = new NonTerminal("emptyStatement"); NonTerminal statement = new NonTerminal("statement"); //, typeof(StatementNode)); NonTerminal printStatement = new NonTerminal("printStatement"); NonTerminal ifStatement = new NonTerminal("ifStatement"); //, typeof(IfStatementNode)); NonTerminal whileLoop = new NonTerminal("whileLoop"); NonTerminal expression = new NonTerminal("expression"); //, typeof(ExpressionNode)); NonTerminal binaryOperator = new NonTerminal("binaryOperator"); //, typeof(BinaryOperatorNode)); NonTerminal assignment = new NonTerminal("assignmentOperator"); NonTerminal localVariableDeclaration = new NonTerminal("localVariableDeclaration"); NonTerminal conditionalExpression = new NonTerminal("conditionalExpression"); NonTerminal functionDeclaration = new NonTerminal("functionDeclaration"); #endregion #region terminals CommentTerminal singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); NonGrammarTerminals.Add(singleLineComment); CommentTerminal delimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(delimitedComment); IdentifierTerminal variable_id = TerminalFactory.CreateCSharpIdentifier("variable_id"); IdentifierTerminal namespace_id = TerminalFactory.CreateCSharpIdentifier("namespace_id"); IdentifierTerminal function_id = TerminalFactory.CreateCSharpIdentifier("function_id"); IdentifierTerminal program_id = TerminalFactory.CreateCSharpIdentifier("program_id"); IdentifierTerminal identifier_id = CreateCSharpIdentifier("identifier_id"); NonTerminal datatype = new NonTerminal("datatype"); //identifierTerminal.("set", "to", "if", "freight", "cost", "is", "loop", "through", "order"); this.MarkPunctuation(";", "[", "]", "(", ")"); #endregion #endregion #region grammar //<Program> ::= "Program" <ProgramName> <StatementList> <FunctionList> "End" "Program" programDeclaration.Rule = ToTerm("Program") + namespace_id + program_id + "[" + statementList + "]"; program.Rule = programDeclaration; // +Symbol("End") + Symbol("Program"); datatype.Rule = ToTerm("char") | "real" | "string"; #region statements //<StatementList> ::= <Statement>* statementList.Rule = MakeStarRule(statementList, null, statement); statement.Rule = emptyStatement | printStatement | ifStatement | whileLoop | localVariableDeclaration | assignment; emptyStatement.Rule = ToTerm(";"); //setVariable + ";" | ifStatement | orderLoop | expression + ";"; // printStatement.Rule = ToTerm("print") + (stringLiteral | charLiteral) + ";"; printStatement.Rule = ToTerm("print") + expression + ";"; //<IfStatement> ::= "if" <Expression> "[" <StatementList> "]" ifStatement.Rule = ToTerm("if") + expression + "[" + statementList + "]"; whileLoop.Rule = ToTerm("while") + expression + "[" + statementList + "]"; assignment.Rule = "let" + identifier_id + (ToTerm("=") | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=") + expression + ";"; //functionDeclaration.Rule = "function" + identifier_id + "(" + localVariableDeclaration.Rule = ToTerm("declare") + identifier_id + datatype + ";"; // identifier_id #endregion #region expressions //<Expression> ::= <number> | <variable> | <string> // | <Expression> <BinaryOperator> <Expression> // | "(" <Expression> ")" expression.Rule = number | variable_id | stringLiteral | charLiteral | expression + binaryOperator + expression | conditionalExpression | "(" + expression + ")"; //<BinaryOperator> ::= "+" | "-" | "*" | "/" | "<" | ">" | "<=" | ">=" | "is" binaryOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "%"; // "==" conditionalExpression.Rule = expression + (ToTerm("<") | ">" | "<=" | ">=") + expression; #endregion #endregion }
public CompsciSpecParser() { //Expr -> n | v | Expr BinOp Expr | UnOP Expr | ( Expr ) //BinOp -> + | - | * | / | ** //UnOp -> - //ExprLine -> Expr EOF //1. Terminals //Terminal num = new NumberLiteral("number"); Terminal id = new IdentifierTerminal("id"); Terminal explicitStringConstant = TerminalFactory.CreateCSharpString("explicitStringConstant"); Terminal explicitIntegerConstant = new NumberLiteral("explicitIntegerConstant", NumberOptions.IntOnly); Terminal explicitRealConstant = new NumberLiteral("explicitRealConstant", NumberOptions.None); Terminal explicitCharConstant = new StringLiteral("Terminal explicitCharConstant", "'", StringOptions.IsChar); //Terminal stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //2. Non-Terminals var variableId = new NonTerminal("variableId"); var variableReference = new NonTerminal("variableReference"); var constantId = new NonTerminal("constantId"); var constantReference = new NonTerminal("constantReference"); var explicitTrueFalseConstant = new NonTerminal("explicitTrueFalseConstant"); var explicitConstant = new NonTerminal("explicitConstant"); var infixOperator = new NonTerminal("infixOperator"); var prefixOperator = new NonTerminal("prefixOperator"); var leftPosition = new NonTerminal("leftPosition"); var rightPosition = new NonTerminal("rightPosition"); var charPosition = new NonTerminal("charPosition"); var stringReference = new NonTerminal("stringReference"); var substring = new NonTerminal("substring"); var functionId = new NonTerminal("functionId"); var moduleId = new NonTerminal("moduleId"); var classId = new NonTerminal("classId"); var pointerId = new NonTerminal("pointerId"); var functionRefence = new NonTerminal("functionReference"); var functionCall = new NonTerminal("functionCall"); var setTypeId = new NonTerminal("setTypeId"); var membersOfSet = new NonTerminal("membersOfSet"); var setConstructor = new NonTerminal("setConstructor"); var enumeratedTypeId = new NonTerminal("enumeratedTypeId"); var enumeratedId = new NonTerminal("enumeratedId"); var enumeratedValue = new NonTerminal("enumeratedValue"); var expn = new NonTerminal("expn"); var expnList = new NonTerminal("expnList"); var fieldId = new NonTerminal("fieldId"); var componentSelector = new NonTerminal("componentSelector"); var maximumLength = new NonTerminal("maximumLength"); var numberOfCharacters = new NonTerminal("numberOfCharacters"); var standardType = new NonTerminal("standardType"); var subrangeType = new NonTerminal("subrangeType"); var typeDeclaration = new NonTerminal("typeDeclaration"); var stringType = new NonTerminal("stringType"); var idList = new NonTerminal("idList"); var enumeratedType = new NonTerminal("enumeratedType"); var indexType = new NonTerminal("indexType"); var indexTypeList = new NonTerminal("indexTypeList"); var arrayFlexible = new NonTerminal("arrayFlexible"); var arrayType = new NonTerminal("arrayType"); var setType = new NonTerminal("setType"); var recordField = new NonTerminal("recordField"); var recordFieldList = new NonTerminal("recordFieldList"); var recordType = new NonTerminal("recordType"); var labelExpn = new NonTerminal("labelExpn"); var labelExpnList = new NonTerminal("labelExpnList"); var unionLabelList = new NonTerminal("unionLabelList"); var unionEndList = new NonTerminal("unionEndList"); var unionEndLabel = new NonTerminal("unionEndLabel"); var unionType = new NonTerminal("unionType"); var collectionId = new NonTerminal("collectionId"); var pointerType = new NonTerminal("pointerType"); var namedType = new NonTerminal("namedType"); var typeSpec = new NonTerminal("typeSpec"); var subprogramType = new NonTerminal("subprogramType"); var paramDeclaration = new NonTerminal("paramDeclaration"); var paramList = new NonTerminal("paramList"); var subParams = new NonTerminal("subParams"); var subPervasive = new NonTerminal("subPervasive"); var subDevice = new NonTerminal("subDevice"); var subprogramHeader = new NonTerminal("subprogramHeader"); var subBody = new NonTerminal("subBody"); var trueFalseExpn = new NonTerminal("trueFalseExpn"); var subPre = new NonTerminal("subPre"); var initList = new NonTerminal("initList"); var subInit = new NonTerminal("subInit"); var subPost = new NonTerminal("subPost"); var subExcept = new NonTerminal("subExcept"); var subprogramDeclaration = new NonTerminal("subprogramDeclaration"); var assignmentOp = new NonTerminal("assignmentOp"); var assignmentStatement = new NonTerminal("assignmentStatement"); var beginStatement = new NonTerminal("beginStatement"); var bindList = new NonTerminal("bindList"); var bindDeclaration = new NonTerminal("bindDeclaration"); var compileTimeExpn = new NonTerminal("compileTimeExpn"); var compileTimeExpnList = new NonTerminal("compileTimeExpnList"); var caseLabel = new NonTerminal("caseLabel"); var caseLabelList = new NonTerminal("caseLabelList"); var caseLabels = new NonTerminal("caseLabels"); var caseDefaultLabel = new NonTerminal("caseDefaultLabel"); var caseStatement = new NonTerminal("caseStatement"); var typeId = new NonTerminal("typeId"); var targetType = new NonTerminal("targetType"); var compileTimeIntExpn = new NonTerminal("compileTimeIntExpn"); var sizeSpec = new NonTerminal("sizeSpec"); var typeCheat = new NonTerminal("typeCheat"); var classMonitor = new NonTerminal("classMonitor"); var inheritItem = new NonTerminal("inheritItem"); var classInherit = new NonTerminal("classInherit"); var implementItem = new NonTerminal("implementItem"); var classImplement = new NonTerminal("classImplement"); var implementByItem = new NonTerminal("implementByItem"); var classBy = new NonTerminal("classBy"); var howImport = new NonTerminal("howImport"); var importItem = new NonTerminal("importItem"); var importList = new NonTerminal("importList"); var classImport = new NonTerminal("classImport"); var exportMethod = new NonTerminal("exportMethod"); var howExport = new NonTerminal("howExport"); var exportItem = new NonTerminal("exportItem"); var exportList = new NonTerminal("exportList"); var classExport = new NonTerminal("classExport"); var classDeclaration = new NonTerminal("classDeclaration"); var fileNumber = new NonTerminal("fileNumber"); var closeStatement = new NonTerminal("closeStatement"); var collectionCheck = new NonTerminal("collectionCheck"); var collectionDeclaration = new NonTerminal("collectionDeclaration"); var comparisonOperator = new NonTerminal("comparisonOperator"); var conditionArray = new NonTerminal("conditionArray"); var conditionOption = new NonTerminal("conditionOption"); var conditionDeclaration = new NonTerminal("conditionDeclaration"); var constTypeSpec = new NonTerminal("constTypeSpec"); var initializingValue = new NonTerminal("initializingValue"); var constPervasive = new NonTerminal("constPervasive"); var constRegister = new NonTerminal("constRegister"); var constantDeclaration = new NonTerminal("constantDeclaration"); var declaration = new NonTerminal("declaration"); var deferredDeclaration = new NonTerminal("deferredDeclaration"); var exitStatement = new NonTerminal("exitStatement"); var externalOverrideName = new NonTerminal("externalOverrideName"); var externalAddressSpec = new NonTerminal("externalAddressSpec"); var externalTypeSpec = new NonTerminal("externalTypeSpec"); var externalExpn = new NonTerminal("externalExpn"); var externalDeclaration = new NonTerminal("externalDeclaration"); var increment = new NonTerminal("increment"); var forIncrement = new NonTerminal("forIncrement"); var integerExpn = new NonTerminal("integerExpn"); var rangeId = new NonTerminal("rangeId"); var forRange = new NonTerminal("forRange"); var forId = new NonTerminal("forId"); var forDecreasing = new NonTerminal("forDecreasing"); var forStatement = new NonTerminal("forStatement"); var forExpnLIst = new NonTerminal("forExpnList"); var forkParams = new NonTerminal("forParams"); var forkRefExpnRef = new NonTerminal("forkRefExpnRef"); var forkRefExpn = new NonTerminal("forkRefExpn"); var forkReference = new NonTerminal("forReference"); var addressReference = new NonTerminal("addressReference"); var booleanVariableReference = new NonTerminal("booleanVariableReference"); var processId = new NonTerminal("processId"); var forkStatement = new NonTerminal("forkStatement"); //new rules var deviceSpecification = new NonTerminal("deviceSpecification"); var exceptionHandler = new NonTerminal("exceptionHandler"); var statementsAndDeclarations = new NonTerminal("statementsAndDeclarations"); var fileName = new NonTerminal("fileName"); var procedureDeclaration = new NonTerminal("procedureDeclaration"); var functionDeclaration = new NonTerminal("functionDeclaration"); //var moduleDeclaration = new NonTerminal("moduleDeclaration"); //var monitorDeclaration = new NonTerminal("monitorDeclaration"); //var processDeclaration = new NonTerminal("processDeclaration"); var variableDeclaration = new NonTerminal("variableDeclaration"); var overrideName = new NonTerminal("overrideName"); var addressSpec = new NonTerminal("addressSpec"); var forkExpnList = new NonTerminal("forkExpnList"); var statements = new NonTerminal("statements"); var putStatement = new NonTerminal("putStatement"); var putItem = new NonTerminal("putItem"); var getStatement = new NonTerminal("getStatement"); var getItem = new NonTerminal("getItem"); var openStatement = new NonTerminal("openStatement"); var capability = new NonTerminal("capability"); var streamNumber = new NonTerminal("streamNumber"); var widthExpn = new NonTerminal("widthExpn"); var fractionWidth = new NonTerminal("fractionWidth"); var exponentWidth = new NonTerminal("exponentWidth"); var fileNumberVariable = new NonTerminal("fileNumberVariable"); var loopStatement = new NonTerminal("loopStatement"); var functionHeader = new NonTerminal("functionHeader"); var procedureHeader = new NonTerminal("procedureHeader"); //3. BNF Rules variableId.Rule = id; variableReference.Rule = variableId | variableId + PreferShiftHere() + componentSelector; constantId.Rule = id; constantReference.Rule = constantId | constantId + PreferShiftHere() + componentSelector; explicitTrueFalseConstant.Rule = ToTerm("true") | "false"; explicitConstant.Rule = explicitStringConstant | explicitIntegerConstant | explicitRealConstant | explicitTrueFalseConstant | explicitCharConstant; infixOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "div" | "mod" | "rem" | "**" | "<" | ">" | "=" | "<=" | ">=" | "not=" | "and" | "or" | "=>" | "in" | "not" + "in" | "shr" | "shl" | "xor"; prefixOperator.Rule = ToTerm("+") | "-" | "not" | "#" | "^"; leftPosition.Rule = expn | "*" | "*" + "-" + expn; rightPosition.Rule = expn | "*" | "*" + "-" + expn; charPosition.Rule = expn | "*" | "*" + "-" + expn; stringReference.Rule = variableReference; substring.Rule = stringReference + "(" + leftPosition + ".." + rightPosition + ")" | stringReference + "(" + charPosition + ")"; functionId.Rule = variableReference; moduleId.Rule = variableReference; classId.Rule = variableReference; pointerId.Rule = variableReference; functionRefence.Rule = moduleId + "." + functionId | functionId | classId + "(" + pointerId + ")" + "." + functionId | pointerId + "->" + functionId; functionCall.Rule = functionRefence | functionRefence + "(" + ")" | functionRefence + "(" + expnList + ")"; setTypeId.Rule = variableReference; membersOfSet.Rule = expnList | "all"; setConstructor.Rule = setTypeId + "(" + membersOfSet + ")" | setTypeId + "(" + ")"; enumeratedTypeId.Rule = variableReference; enumeratedId.Rule = id; enumeratedValue.Rule = enumeratedTypeId + "." + enumeratedId; expn.Rule = explicitConstant | variableReference | constantReference | expn + infixOperator + expn | prefixOperator + expn | "(" + expn + ")" | substring | functionCall | setConstructor | enumeratedValue; expnList.Rule = expn | expn + "," + expn; fieldId.Rule = id; componentSelector.Rule = "(" + expnList + ")" | "." + fieldId; maximumLength.Rule = expn; numberOfCharacters.Rule = expn; standardType.Rule = ToTerm("int") | "real" | stringType | "boolean" | "nat" | "int1" | "int2" | "int4" | "nat1" | "nat2" | "nat4" | "real4" | "real8" | "char" | "char" + "(" + numberOfCharacters + ")"; subrangeType.Rule = expn + ".." + expn; typeDeclaration.Rule = "type" + id + ":" + typeSpec | "type" + id + ":" + "forward"; stringType.Rule = "string" | "string" + PreferShiftHere() + "(" + maximumLength + ")"; idList.Rule = id | id + PreferShiftHere() + "," + idList; enumeratedType.Rule = "enum" + "(" + idList + ")"; indexType.Rule = subrangeType | enumeratedType | namedType | "char" | "boolean"; indexTypeList.Rule = indexType | indexType + "," + indexTypeList; arrayFlexible.Rule = "flexible" | Empty; arrayType.Rule = arrayFlexible + "array" + indexTypeList + "of" + typeSpec; setType.Rule = "set" + "of" + typeSpec; recordField.Rule = idList + ":" + typeSpec; recordFieldList.Rule = recordField | recordField + recordFieldList; recordType.Rule = "record" + recordFieldList + "end" + "record"; labelExpn.Rule = expn; labelExpnList.Rule = labelExpn | labelExpn + "," + labelExpnList; unionLabelList.Rule = "label" + labelExpnList + ":" + idList + ":" + typeSpec | "label" + labelExpnList + ":"; unionEndLabel.Rule = "label" + ":" + idList + ":" + typeSpec | "label" + ":"; unionType.Rule = "union" + ":" + indexType + "of" + unionLabelList + "end" + "union" | "union" + id + ":" + indexType + "of" + unionLabelList + "end" + "union" | "union" + ":" + indexType + "of" + unionLabelList + unionEndLabel + "end" + "union" | "union" + id + ":" + indexType + "of" + unionLabelList + unionEndLabel + "end" + "union"; collectionId.Rule = variableReference; pointerType.Rule = "pointer" + "to" + collectionId | "unchecked" + "pointer" + "to" + collectionId | "^" + collectionId | "pointer" + "to" + classId | "unchecked" + "pointer" + "to" + classId | "^" + classId | "pointer" + "to" + typeSpec | "unchecked" + "pointer" + "to" + typeSpec | "^" + typeSpec; namedType.Rule = variableReference; typeSpec.Rule = ToTerm("int") | "real" | "boolean" | stringType | subrangeType | enumeratedType | arrayType | setType | recordType | unionType | pointerType | namedType | "nat" | "int1" | "int2" | "int4" | "nat1" | "nat2" | "nat4" | "real4" | "real8" | "char" | "char" + "(" + numberOfCharacters + ")" | subprogramType; subprogramType.Rule = subprogramHeader; paramDeclaration.Rule = idList + ":" + typeSpec | "var" + idList + ":" + typeSpec | subprogramHeader; paramList.Rule = paramDeclaration | paramDeclaration + "," + paramList; subParams.Rule = "(" + paramList + ")" | "(" + ")" | Empty; subPervasive.Rule = "pervasive" | Empty; subDevice.Rule = ":" + deviceSpecification | Empty; //subprogramHeader.Rule = "procedure" + subPervasive + id + subParams + subDevice // | "function" + subPervasive + id + subParams + ":" + typeSpec // | "function" + subPervasive + id + subParams + id + ":" + typeSpec; subBody.Rule = "body" | Empty; trueFalseExpn.Rule = expn; subPre.Rule = "pre" + trueFalseExpn | Empty; initList.Rule = id + ":=" + expn | id + ":=" + expn + "," + initList; subInit.Rule = "init" + initList | Empty; subPost.Rule = "post" + trueFalseExpn | Empty; subExcept.Rule = exceptionHandler | Empty; //subprogramDeclaration.Rule = subBody + subprogramHeader + subPre + subInit + subPost + subExcept + statementsAndDeclarations + "end" + id // | "body" + id + statementsAndDeclarations + "end" + id; assignmentOp.Rule = ToTerm(":=") | "+=" | "-=" | "*=" | "/=" | "div=" | "mod=" | "rem=" | "shl=" | "shr=" | "xor="; assignmentStatement.Rule = variableReference + assignmentOp + expn; beginStatement.Rule = "begin" + statementsAndDeclarations + "end"; bindList.Rule = id + "to" + variableReference | "var" + id + "to" + variableReference | id + "to" + variableReference + "," + bindList | "var" + id + "to" + variableReference + "," + bindList | "register" + id + "to" + variableReference | "var" + "register" + id + "+to" + variableReference | "register" + id + "to" + variableReference + "," + bindList | "var" + "register" + id + "to" + variableReference + "," + bindList; bindDeclaration.Rule = "bind" + bindList; compileTimeExpn.Rule = expn; compileTimeExpnList.Rule = compileTimeExpn | compileTimeExpn + "," + compileTimeExpnList; caseLabel.Rule = "label" + compileTimeExpnList + ":" + statementsAndDeclarations; caseLabelList.Rule = caseLabel | caseLabel + "," + caseLabelList; caseLabels.Rule = caseLabelList | Empty; caseDefaultLabel.Rule = "label" + ":" + statementsAndDeclarations | Empty; caseStatement.Rule = "case" + expn + "of" + caseLabels + caseDefaultLabel + "end" + "case"; typeId.Rule = variableId | id + ":" + variableReference; targetType.Rule = typeId | "int" | "int1" | "int2" | "int4" | "nat" | "nat1" | "nat2" | "nat4" | "boolean" | "char" | "string" | "char" + "(" + numberOfCharacters + ")" | "string" + "(" + maximumLength + ")" | "addressint"; compileTimeIntExpn.Rule = expn; sizeSpec.Rule = ":" + compileTimeIntExpn | Empty; typeCheat.Rule = "cheat" + "(" + targetType + "," + expn + sizeSpec + ")" | "#" + expn | id + ":" + "cheat" + typeSpec; classMonitor.Rule = "monitor" | Empty; inheritItem.Rule = id; classInherit.Rule = "inherit" + inheritItem | Empty; implementItem.Rule = id; classImplement.Rule = "implement" + implementItem | Empty; implementByItem.Rule = id; classBy.Rule = "implement" + "by" + implementByItem | Empty; howImport.Rule = ToTerm("var") | "const" | "forward" | Empty; importItem.Rule = howImport + id | howImport + id + "in" + fileName | "(" + howImport + id + ")" | "(" + howImport + id + "in" + fileNumber + ")"; importList.Rule = importItem | importItem + "," + importList; classImport.Rule = "import" + importList | Empty; exportMethod.Rule = ToTerm("var") | "unqualified" | "pervasive" | "opaque"; howExport.Rule = exportMethod + howExport | Empty; exportItem.Rule = howExport + id; exportList.Rule = exportItem | exportItem + "," + exportList; classExport.Rule = "export" + exportList | "export" + "all" | Empty; classDeclaration.Rule = classMonitor + "class" + id + classInherit + classImplement + classBy + classImport + classExport + statementsAndDeclarations + "end" + id; fileNumber.Rule = expn; closeStatement.Rule = "close" + ":" + fileNumber | "close" + "(" + fileNumber + ":" + "int" + ")"; collectionCheck.Rule = "unchecked" | Empty; collectionDeclaration.Rule = "var" + idList + ":" + collectionCheck + "collection" + "of" + typeSpec | "var" + idList + ":" + collectionCheck + "collection" + "of" + "forward" + typeId; comparisonOperator.Rule = ToTerm("<") | ">" | "=" | "<=" | ">=" | "not="; conditionArray.Rule = "array" + indexTypeList + "of" | Empty; conditionOption.Rule = ToTerm("priority") | "deferred" | "timeout" | Empty; conditionDeclaration.Rule = "var" + idList + ":" + conditionArray + conditionOption + "condition"; constTypeSpec.Rule = ":" + typeSpec | Empty; initializingValue.Rule = expn | "init" + "(" + initializingValue + "," + initializingValue + ")"; constPervasive.Rule = "pervasive" | Empty; constRegister.Rule = "register" | Empty; constantDeclaration.Rule = "const" + constPervasive + constRegister + id + constTypeSpec + ":=" + initializingValue; declaration.Rule = constantDeclaration | typeDeclaration | bindDeclaration | procedureDeclaration | functionDeclaration | variableDeclaration | conditionDeclaration //| monitorDeclaration | moduleDeclaration| processDeclaration | classDeclaration; deferredDeclaration.Rule = "deferred" + subprogramHeader; exitStatement.Rule = "exit" + "when" + trueFalseExpn;// | "exit"; externalOverrideName.Rule = overrideName | Empty; externalAddressSpec.Rule = addressSpec | Empty; externalTypeSpec.Rule = ":" + typeSpec | Empty; externalExpn.Rule = ":=" + expn | Empty; externalDeclaration.Rule = "external" + externalOverrideName + subprogramHeader | "external" + externalAddressSpec + "var" + id + externalTypeSpec + externalExpn; increment.Rule = expn; forIncrement.Rule = "by" + increment | Empty; integerExpn.Rule = expn; rangeId.Rule = variableDeclaration; forRange.Rule = integerExpn + ".." + integerExpn | rangeId; forId.Rule = id | Empty; forDecreasing.Rule = "decreasing" | Empty; forStatement.Rule = "for" + forDecreasing + forId + ":" + forRange + forIncrement + statementsAndDeclarations + "end" + "for"; forkExpnList.Rule = expnList | Empty; forkParams.Rule = "(" + forkExpnList + ")" | Empty; forkRefExpnRef.Rule = "," + addressReference | Empty; forkRefExpn.Rule = "," + expn + forkRefExpnRef | Empty; forkReference.Rule = ":" + booleanVariableReference + forkRefExpn | Empty; addressReference.Rule = variableReference; booleanVariableReference.Rule = variableReference; processId.Rule = variableReference; forkStatement.Rule = "fork" + processId + forkParams + forkReference; //new rules deviceSpecification.Rule = explicitIntegerConstant; exceptionHandler.Rule = "handler" + "(" + id + ")" + statementsAndDeclarations + "end" + "handler"; fileName.Rule = explicitStringConstant; overrideName.Rule = explicitStringConstant; addressSpec.Rule = compileTimeExpn; procedureDeclaration.Rule = subprogramDeclaration;//seems a little redudant functionDeclaration.Rule = subprogramDeclaration; //processDeclaration.Rule = forkStatement; statementsAndDeclarations.Rule = declaration + statementsAndDeclarations | statements + statementsAndDeclarations | Empty; statements.Rule = forStatement | forkStatement | exitStatement | closeStatement | assignmentStatement | caseStatement | beginStatement | putStatement | getStatement | loopStatement; variableDeclaration.Rule = ToTerm("var") + MakePlusRule(variableDeclaration, ToTerm(","), id) + ":=" + expn | "var" + MakePlusRule(variableDeclaration, ToTerm(","), id) + ":" + typeSpec + (":=" + initializingValue | Empty); putStatement.Rule = ToTerm("put") + (":" + streamNumber + "," | Empty) + MakePlusRule(putStatement, ToTerm(","), putItem) + (".." | Empty); putItem.Rule = expn + (":" + widthExpn + (":" + fractionWidth + (":" + exponentWidth | Empty) | Empty) | Empty) | "skip"; getStatement.Rule = ToTerm("get") + (":" + streamNumber + "," | Empty) + MakePlusRule(getStatement, ToTerm(","), getItem); getItem.Rule = variableReference | "skip" | variableReference + ":" + "*" | variableReference + ":" + widthExpn; openStatement.Rule = ToTerm("open") + ":" + fileNumberVariable + "," + fileName + "," + MakePlusRule(openStatement, ToTerm(","), capability); capability.Rule = ToTerm("put") | "get"; closeStatement.Rule = ToTerm("close") + ":" + fileNumber; streamNumber.Rule = widthExpn.Rule = fractionWidth.Rule = exponentWidth.Rule = fileNumber.Rule = expn; loopStatement.Rule = ToTerm("loop") + statementsAndDeclarations + "end" + "loop"; functionDeclaration.Rule = subBody + functionHeader + subPre + subInit + subPost + subExcept + statementsAndDeclarations + "end" + id | "body" + id + statementsAndDeclarations + "end" + id; procedureDeclaration.Rule = subBody + procedureHeader + subPre + subInit + subPost + subExcept + statementsAndDeclarations + "end" + id | "body" + id + statementsAndDeclarations + "end" + id; subprogramDeclaration.Rule = functionDeclaration | procedureDeclaration; functionHeader.Rule = "function" + subPervasive + id + subParams + ":" + typeSpec | "function" + subPervasive + id + subParams + id + ":" + typeSpec; procedureHeader.Rule = "procedure" + subPervasive + id + subParams + subDevice; subprogramHeader.Rule = functionHeader | procedureHeader; //Following are guesses as to the rules, since the spec does not state the rules for them fileNumberVariable.Rule = variableReference; fileName.Rule = explicitStringConstant | variableReference; //variableDeclaration.Rule = collectionDeclaration; //moduleDeclaration.Rule = variableDeclaration; //monitorDeclaration.Rule = variableDeclaration; this.Root = statementsAndDeclarations; //procedureDeclaration = new NonTerminal("procedureDeclaration"); //functionDeclaration = new NonTerminal("functionDeclaration"); //moduleDeclaration = new NonTerminal("moduleDeclaration"); //monitorDeclaration = new NonTerminal("monitorDeclaration"); //processDeclaration = new NonTerminal("processDeclaration"); //variableDeclaration = new NonTerminal("variableDeclaration"); //this.Root = program; //4. Set operator precendence and associativity RegisterOperators(80, Associativity.Left, "**");//this is VERY odd, but Turing simplifies associativity by saying it's all left associative RegisterOperators(60, "*", "/", "div", "mod"); RegisterOperators(50, "+", "-"); RegisterOperators(40, "<", ">", "=", "<=", ">=", "not="); RegisterOperators(30, "not"); RegisterOperators(20, "and"); RegisterOperators(10, "or"); //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree MarkPunctuation("(", ")", ","); RegisterBracePair("(", ")"); //MarkTransient(Expr, BinOp, ParExpr); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public SLAngGrammer() : base() { StringLiteral stringLiteral = TerminalFactory.CreateCSharpString("StringLiteral"); StringLiteral charLiteral = TerminalFactory.CreateCSharpChar("CharLiteral"); NumberLiteral number = TerminalFactory.CreateCSharpNumber("Number"); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); CommentTerminal delimitedComment = new CommentTerminal("DelimitedComment", "/[", "]/"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "--", "\r", "\n", "\u2085", "\u2028", "\u2029"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(delimitedComment); #region Terminals KeyTerm colon = ToTerm(":"); KeyTerm dot = ToTerm("."); KeyTerm comma = ToTerm(","); KeyTerm propertyIs = ToTerm("->"); KeyTerm lbr = ToTerm("{"); KeyTerm rbr = ToTerm("}"); KeyTerm lpar = ToTerm("("); KeyTerm rpar = ToTerm(")"); KeyTerm scopeIn = ToTerm("::"); KeyTerm suchThat = ToTerm("|"); KeyTerm _package = ToTerm("package"); KeyTerm context = ToTerm("context"); KeyTerm body = ToTerm("body"); KeyTerm def = ToTerm("def"); KeyTerm derive = ToTerm("derive"); KeyTerm In = ToTerm("in"); KeyTerm inv = ToTerm("inv"); KeyTerm let = ToTerm("let"); KeyTerm post = ToTerm("post"); KeyTerm pre = ToTerm("pre"); KeyTerm Static = ToTerm("static"); KeyTerm self = ToTerm("self"); KeyTerm result = ToTerm("result"); KeyTerm equalsTo = ToTerm("="); KeyTerm _null = ToTerm("null"); KeyTerm invalid = ToTerm("invalid"); KeyTerm not = ToTerm("not"); KeyTerm and = ToTerm("and"); KeyTerm or = ToTerm("or"); KeyTerm xor = ToTerm("xor"); #endregion #region NonTerminal var specification = new NonTerminal("specification"); var specificationBody = new NonTerminal("specificationBody"); var package = new NonTerminal("package"); var packages = new NonTerminal("packages"); var oclPackage = new NonTerminal("oclPackage"); var emofOclPackage = new NonTerminal("emofOclPackage"); var packageBody = new NonTerminal("packageBody"); var packageBodyItem = new NonTerminal("packageBodyItem"); var contextExp = new NonTerminal("contextExp"); var classType = new NonTerminal("classType"); var enumeration = new NonTerminal("enumeration"); var primitive = new NonTerminal("primitive"); var primitiveType = new NonTerminal("primitiveType"); var primitiveTypes = new NonTerminal("primitiveTypes"); var delimitedIdentifier = new NonTerminal("delimitedIdentifier"); var classSignature = new NonTerminal("classSignature"); var classBody = new NonTerminal("classBody"); var classBodyItem = new NonTerminal("classBodyItem"); var invExp = new NonTerminal("invExp"); var functionDefination = new NonTerminal("functionDefination"); var attributeDiclaration = new NonTerminal("attributeDiclaration"); var emofAttributeDiclaration = new NonTerminal("emofAttributeDiclaration"); var oclAttributeDiclaration = new NonTerminal("oclAttributeDiclaration"); var type = new NonTerminal("type"); var expression = new NonTerminal("expression"); var customType = new NonTerminal("customType"); var collectionTpye = new NonTerminal("collectionTpye"); var fullType = new NonTerminal("fullType"); var globalType = new NonTerminal("globalType"); var setType = new NonTerminal("setType"); var orderedSetType = new NonTerminal("orderedSetType"); var sequenceType = new NonTerminal("sequenceType"); var bagType = new NonTerminal("bagType"); var functionSignature = new NonTerminal("functionSignature"); var functionSignatureBody = new NonTerminal("functionSignatureBody"); var functionBody = new NonTerminal("functionBody"); var oclFunctionSignature = new NonTerminal("oclFunctionSignature"); var emofFunctionSignature = new NonTerminal("emofFunctionSignature"); var argumentList = new NonTerminal("argumentList"); var variableDiclaration = new NonTerminal("variableDiclaration"); var emofFunctionBody = new NonTerminal("emofFunctionBody"); var oclFunctionBody = new NonTerminal("oclFunctionBody"); var singleValueCollectionMember = new NonTerminal("singleValueCollectionMember"); var booleanValueCollection = new NonTerminal("booleanValueCollection"); var letExp = new NonTerminal("letExp"); var ifThenElseExp = new NonTerminal("ifThenElseExp"); var collectionValueExp = new NonTerminal("collectionValueExp"); var sum = new NonTerminal("sum"); var size = new NonTerminal("size"); var first = new NonTerminal("first"); var last = new NonTerminal("last"); var at = new NonTerminal("at"); var indexOf = new NonTerminal("indexOf"); var countOperation = new NonTerminal("countOperation"); var maxOperation = new NonTerminal("maxOperation"); var minOperation = new NonTerminal("minOperation"); var valueExp = new NonTerminal("valueExp"); var includesOperation = new NonTerminal("includesOperation"); var includesAllOperation = new NonTerminal("includesAllOperation"); var excludesOperation = new NonTerminal("excludesOperation"); var excludesAllOperation = new NonTerminal("excludesAllOperation"); var isEmptyOperation = new NonTerminal("isEmptyOperation"); var notEmptyOperation = new NonTerminal("notEmptyOperation"); var specialIteratorBodyExp = new NonTerminal("specialIteratorBodyExp"); var existsExp = new NonTerminal("existsExp"); var forAllExp = new NonTerminal("forAllExp"); var isUniqueExp = new NonTerminal("isUniqueExp"); var anyExp = new NonTerminal("anyExp"); var oneExp = new NonTerminal("oneExp"); var selectExp = new NonTerminal("selectExp"); var includingOperation = new NonTerminal("includingOperation"); var excludingOperation = new NonTerminal("excludingOperation"); var collect = new NonTerminal("collect"); var subOrderedSet = new NonTerminal("subOrderedSet"); var symmetricDifference = new NonTerminal("symmetricDifference"); var prepend = new NonTerminal("prepend"); var append = new NonTerminal("append"); var insertAt = new NonTerminal("insertAt"); var intersection = new NonTerminal("intersection"); var union = new NonTerminal("union"); var asBag = new NonTerminal("asBag"); var asSequence = new NonTerminal("asSequence"); var asOrderdSet = new NonTerminal("asOrderdSet"); var asSet = new NonTerminal("asSet"); var flatten = new NonTerminal("flatten"); var subSequence = new NonTerminal("subSequence"); var andExp = new NonTerminal("andExp"); var orExp = new NonTerminal("orExp"); var notExp = new NonTerminal("notExp"); var xorExp = new NonTerminal("xorExp"); var impliesExp = new NonTerminal("impliesExp"); var comparisonOperator = new NonTerminal("comparisonOperator"); var arithmaticOperator = new NonTerminal("arithmaticOperator"); var oclInvExp = new NonTerminal("oclInvExp"); var emofInvExp = new NonTerminal("emofInvExp"); var operationContextExp = new NonTerminal("operationContextExp"); var attributeContextExp = new NonTerminal("attributeContextExp"); var classContextExp = new NonTerminal("classContextExp"); var classContextSignature = new NonTerminal("classContextSignature"); var attributeContextbody = new NonTerminal("attributeContextbody"); var attributeContextbodyItem = new NonTerminal("attributeContextbodyItem"); var deriveExp = new NonTerminal("deriveExp"); var initExp = new NonTerminal("initExp"); var operationContextBodyExps = new NonTerminal("operationContextBodyExps"); var operationContextSignature = new NonTerminal("operationContextSignature"); var operationContextBodyItem = new NonTerminal("operationContextBodyItem"); var preCondition = new NonTerminal("preCondition"); var postCondition = new NonTerminal("postCondition"); var bodyExp = new NonTerminal("bodyExp"); var iterateExp = new NonTerminal("iterateExp"); var productExp = new NonTerminal("productExp"); var tupleExp = new NonTerminal("tupleExp"); var rejectExp = new NonTerminal("rejectExp"); var collection = new NonTerminal("collection"); var tuplElementList = new NonTerminal("tuplElementList"); var tupleElement = new NonTerminal("tupleElement"); var binaryOperator = new NonTerminal("binaryOperator"); var parameterList = new NonTerminal("parameterList"); var structuralExp = new NonTerminal("structuralExp"); var setLiteral = new NonTerminal("setLiteral"); var bagLiteral = new NonTerminal("orderedSetLiteral"); var orderedSetLiteral = new NonTerminal(""); var sequenceLiteral = new NonTerminal("sequenceLiteral"); var tupleLiteral = new NonTerminal("tupleLiteral"); var literalList = new NonTerminal("literalList"); var iteratorList = new NonTerminal("iteratorList"); var iteratorInitializationList = new NonTerminal("iteratorInitializationList"); var iteratorInitialization = new NonTerminal("iteratorInitialization"); var collectionValue = new NonTerminal("collectionValue"); var ArrayType = new NonTerminal("ArrayType"); var binaryBooleanOperator = new NonTerminal("binaryBooleanOperator"); var oclIsTypeOf = new NonTerminal("oclIsTypeOf"); var ValueExp = new NonTerminal("ValueExp"); var unValueExp = new NonTerminal("unValueExp"); var instanceMemberAccess = new NonTerminal("instanceMemberAccess"); var instanceMathodAccess = new NonTerminal("instanceMathodAccess"); #endregion #region Rules #region specification specification.Rule = "specification" + identifier + lbr + specificationBody + rbr; specificationBody.Rule = MakePlusRule(packages, package); #endregion #region package package.Rule = oclPackage | emofOclPackage; oclPackage.Rule = _package + identifier + packageBody + "endpackage"; emofOclPackage.Rule = _package + identifier + lbr + packageBody + rbr; packageBody.Rule = MakeStarRule(packageBody, null, packageBodyItem); packageBodyItem.Rule = primitive | enumeration | classType | contextExp | package; #endregion #region primitive primitive.Rule = "primitive" + primitiveTypes + identifier + "IDENTICAL"; primitiveTypes.Rule = ToTerm("Real") | ToTerm("Integer") | ToTerm("String") | ToTerm("Boolean"); #endregion #region enumeration enumeration.Rule = "enumeration" + identifier + lbr + delimitedIdentifier + rbr; delimitedIdentifier.Rule = MakePlusRule(delimitedIdentifier, comma, identifier); #endregion #region class classType.Rule = classSignature + lbr + classBody + rbr; classSignature.Rule = ToTerm("class") + identifier | ToTerm("abstract") + ToTerm("class") + identifier | ToTerm("abstract") + ToTerm("class") + identifier + ToTerm("extends") + identifier | ToTerm("class") + identifier + ToTerm("extends") + type; classBody.Rule = MakeStarRule(classBody, classBodyItem); classBodyItem.Rule = attributeDiclaration | functionDefination | invExp; #endregion #region attribute attributeDiclaration.Rule = oclAttributeDiclaration | emofAttributeDiclaration; oclAttributeDiclaration.Rule = def + colon + identifier + type + ReduceHere() | def + colon + identifier + type + PreferShiftHere() + equalsTo + expression + ReduceHere() | def + colon + "attr" + identifier + type + PreferShiftHere() + equalsTo + expression + ReduceHere() | def + colon + "attr" + identifier + type + ReduceHere(); emofAttributeDiclaration.Rule = identifier + colon + type + ReduceHere() | ToTerm("component") + identifier + colon + type + ToTerm("opposite") + identifier + ReduceHere() | ToTerm("component") + identifier + colon + type + ToTerm("unique") + ToTerm("opposite") + identifier + ReduceHere() | identifier + colon + type + equalsTo + expression + ReduceHere() | identifier + colon + type + ToTerm("opposite") + identifier + ReduceHere() | identifier + colon + type + ToTerm("unique") + ToTerm("opposite") + identifier + ReduceHere() | identifier + colon + type + ToTerm("unique") + ReduceHere(); #endregion #region type type.Rule = primitiveTypes | customType; customType.Rule = fullType | globalType | ArrayType | collectionTpye | tupleExp; fullType.Rule = identifier + scopeIn + fullType | identifier + ReduceHere(); globalType.Rule = PreferShiftHere() + scopeIn + fullType | PreferShiftHere() + scopeIn + ArrayType; ArrayType.Rule = fullType + "[" + "*" + "]" | fullType + "[" + identifier + "]" | fullType + "[" + number + "]" | fullType + "[" + number + comma + number + "]" | fullType + "[" + number + comma + "*" + "]"; collectionTpye.Rule = setType | orderedSetType | sequenceType | bagType | collection; setType.Rule = "Set(" + customType + ")"; orderedSetType.Rule = "OrderedSet(" + customType + ")"; sequenceType.Rule = "Sequence(" + customType + ")"; bagType.Rule = "Bag(" + customType + ")"; collection.Rule = "Collection(" + customType + ")"; tupleExp.Rule = "Tuple" + lbr + argumentList + rbr; #endregion #region function functionDefination.Rule = functionSignature + functionBody; functionSignature.Rule = oclFunctionSignature | emofFunctionSignature; oclFunctionSignature.Rule = def + colon + functionSignatureBody; functionSignatureBody.Rule = identifier + lpar + argumentList + rpar + colon + type | identifier + lpar + argumentList + rpar + colon + type + ToTerm("ordered") + ToTerm("unique") | identifier + lpar + argumentList + rpar + colon; argumentList.Rule = MakeStarRule(argumentList, comma, variableDiclaration); variableDiclaration.Rule = identifier + PreferShiftHere() + colon + type; emofFunctionSignature.Rule = functionSignatureBody; functionBody.Rule = oclFunctionBody | emofFunctionBody; oclFunctionBody.Rule = equalsTo + expression; emofFunctionBody.Rule = equalsTo + lbr + expression + rbr; #endregion #region expression expression.Rule = valueExp | structuralExp; #endregion #region valueExp valueExp.Rule = // ValueExp + ReduceHere() | unValueExp + ReduceHere() | valueExp + PreferShiftHere() + binaryOperator + valueExp | ToTerm("not") + valueExp | lpar + valueExp + rpar; #endregion #region unValueExp unValueExp.Rule = booleanValueCollection | ToTerm("false") | ToTerm("true") | collectionValue | tupleLiteral | singleValueCollectionMember | collectionValueExp | iterateExp | stringLiteral | charLiteral | number | self | oclIsTypeOf | unValueExp + lpar + parameterList + rpar | instanceMemberAccess | instanceMathodAccess | ToTerm("-") + number; #endregion #region ValueExp ValueExp.Rule = fullType + dot + instanceMemberAccess | globalType + dot + instanceMemberAccess | ValueExp + dot + identifier + lpar + parameterList + rpar; #endregion #region instanceMemberAccess instanceMemberAccess.Rule = MakePlusRule(instanceMemberAccess, dot, identifier); instanceMathodAccess.Rule = unValueExp + dot + identifier + lpar + parameterList + rpar; #endregion #region parameterList parameterList.Rule = MakeStarRule(parameterList, comma, expression); #endregion #region booleanExp booleanValueCollection.Rule = includesOperation | includesAllOperation | excludesOperation | excludesAllOperation | isEmptyOperation | notEmptyOperation | existsExp | forAllExp | isUniqueExp | anyExp | oneExp; #endregion #region oclBuildInMethods oclIsTypeOf.Rule = valueExp + dot + ToTerm("oclIsTypeOf") + lpar + type + rpar; #endregion #region binaryOperator binaryOperator.Rule = comparisonOperator | arithmaticOperator | binaryBooleanOperator; arithmaticOperator.Rule = ToTerm("/") | ToTerm("div") | ToTerm("*") | ToTerm("+") | ToTerm("-"); comparisonOperator.Rule = ToTerm(">") | ToTerm("<") | ToTerm(">=") | ToTerm("<=") | ToTerm("<>") | equalsTo; binaryBooleanOperator.Rule = ToTerm("and") | ToTerm("or") | ToTerm("xor") | ToTerm("implies"); #endregion #region booleanValueCollection includesOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("includes") + lpar + valueExp + rpar; includesAllOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("includesAll") + lpar + identifier + rpar; excludesOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("excludes") + lpar + identifier + rpar; excludesAllOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("excludesAll") + lpar + identifier + rpar; isEmptyOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("isEmpty") + lpar + rpar; notEmptyOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("notEmpty") + lpar + rpar; existsExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("exists") + lpar + specialIteratorBodyExp + rpar; forAllExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("forAll") + lpar + specialIteratorBodyExp + rpar; isUniqueExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("isUnique") + lpar + specialIteratorBodyExp + rpar; anyExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("any") + lpar + specialIteratorBodyExp + rpar; oneExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("one") + lpar + specialIteratorBodyExp + rpar; specialIteratorBodyExp.Rule = delimitedIdentifier + colon + type + suchThat + valueExp | argumentList + suchThat + valueExp | valueExp; #endregion #region collectionValue collectionValue.Rule = setLiteral | bagLiteral | orderedSetLiteral | sequenceLiteral; setLiteral.Rule = "Set" + lbr + literalList + rbr | "Set" + lpar + type + rpar + lbr + literalList + rbr; bagLiteral.Rule = "Bag" + lbr + literalList + rbr | "Bag" + lpar + type + rpar + lbr + literalList + rbr; orderedSetLiteral.Rule = "OrderedSet" + lbr + literalList + rbr | "OrderedSet" + lpar + type + rpar + lbr + literalList + rbr; sequenceLiteral.Rule = "Sequence" + lbr + literalList + rbr | "Sequence" + lpar + type + rpar + lbr + literalList + rbr; literalList.Rule = MakeStarRule(literalList, comma, valueExp); tupleLiteral.Rule = "Tuple" + lbr + tuplElementList + rbr; tuplElementList.Rule = MakePlusRule(tuplElementList, comma, tupleElement); tupleElement.Rule = variableDiclaration + equalsTo + valueExp | identifier + equalsTo + valueExp; collectionValueExp.Rule = includingOperation | excludingOperation | selectExp | rejectExp | union | intersection | insertAt | append | prepend | symmetricDifference | subOrderedSet | collect | productExp | subSequence | flatten | asSet | asOrderdSet | asSequence | asBag; includingOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("including") + lpar + identifier + rpar; excludingOperation.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("excluding") + lpar + identifier + rpar; selectExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("select") + lpar + specialIteratorBodyExp + rpar; rejectExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("reject") + lpar + specialIteratorBodyExp + rpar; union.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("union") + lpar + valueExp + rpar; intersection.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("intersection") + lpar + identifier + rpar; insertAt.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("insertAt") + lpar + number + comma + identifier + rpar; append.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("append") + lpar + identifier + rpar; prepend.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("prepend") + lpar + identifier + rpar; symmetricDifference.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("symmetricDifference") + lpar + identifier + rpar; subOrderedSet.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("subOrderedSet") + lpar + number + comma + number + rpar; collect.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("collect") + lpar + specialIteratorBodyExp + rpar | valueExp + PreferShiftHere() + propertyIs + ToTerm("collect") + lpar + identifier + rpar | valueExp + dot + identifier + lpar + argumentList + rpar | valueExp + PreferShiftHere() + propertyIs + identifier + lpar + argumentList + rpar; productExp.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("product") + lpar + identifier + rpar; subSequence.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("subSequence") + lpar + number + comma + number + rpar; flatten.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("flatten") + lpar + rpar; asSet.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("asSet") + lpar + rpar; asOrderdSet.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("asOrderdSet") + lpar + rpar; asSequence.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("asSequence") + lpar + rpar; asBag.Rule = valueExp + PreferShiftHere() + propertyIs + ToTerm("asBag") + lpar + rpar; #endregion #region singleValueCollectionMember singleValueCollectionMember.Rule = maxOperation | minOperation | countOperation | at | indexOf | first | last | sum | size; maxOperation.Rule = valueExp + PreferShiftHere() + propertyIs + "max" + lpar + rpar; minOperation.Rule = valueExp + PreferShiftHere() + propertyIs + "min" + lpar + rpar; countOperation.Rule = valueExp + PreferShiftHere() + propertyIs + "count" + lpar + identifier + rpar; at.Rule = valueExp + PreferShiftHere() + propertyIs + "at" + lpar + identifier + rpar; indexOf.Rule = valueExp + PreferShiftHere() + propertyIs + "indexOf" + lpar + identifier + rpar; first.Rule = valueExp + PreferShiftHere() + propertyIs + "first" + lpar + rpar; last.Rule = valueExp + PreferShiftHere() + propertyIs + "last" + lpar + rpar; sum.Rule = valueExp + PreferShiftHere() + propertyIs + "sum" + lpar + rpar; size.Rule = valueExp + PreferShiftHere() + propertyIs + "size" + lpar + rpar; #endregion #region iterateExp iterateExp.Rule = valueExp + PreferShiftHere() + propertyIs + "iterate" + lpar + iteratorList + ";" + iteratorInitializationList + suchThat + expression + rpar; iteratorList.Rule = MakePlusRule(iteratorList, comma, variableDiclaration); iteratorInitializationList.Rule = MakePlusRule(iteratorInitializationList, comma, iteratorInitialization); iteratorInitialization.Rule = variableDiclaration + equalsTo + valueExp; #endregion #region structuralExp structuralExp.Rule = ifThenElseExp | letExp; #endregion #region ifThenElseExp ifThenElseExp.Rule = "if" + valueExp + "then" + expression + "endif" | "if" + valueExp + "then" + expression + "else" + expression + "endif"; #endregion #region letExp letExp.Rule = let + variableDiclaration + equalsTo + valueExp + In + expression | let + identifier + equalsTo + valueExp + In + expression; #endregion #region invExp invExp.Rule = oclInvExp | emofInvExp; oclInvExp.Rule = inv + identifier + colon + expression | inv + colon + expression; emofInvExp.Rule = "invariant" + lbr + expression + rbr; #endregion #region contextExp contextExp.Rule = classContextExp | attributeContextExp | operationContextExp; #endregion #region classContextExp classContextExp.Rule = classContextSignature + classBody; classContextSignature.Rule = context + type | context + identifier + colon + type; classBody.Rule = MakePlusRule(classBody, null, classBodyItem); classBodyItem.Rule = invExp | attributeDiclaration | functionDefination; #endregion #region attributeContextExp attributeContextExp.Rule = context + type + colon + type + attributeContextbody; attributeContextbody.Rule = MakePlusRule(attributeContextbody, null, attributeContextbodyItem); attributeContextbodyItem.Rule = initExp | deriveExp; #endregion #region initExp initExp.Rule = ToTerm("init") + colon + equalsTo + valueExp; #endregion #region deriveExp deriveExp.Rule = ToTerm("derive") + colon + expression; #endregion #region operationContextExp operationContextExp.Rule = operationContextSignature + invExp + operationContextBodyExps; operationContextSignature.Rule = context + customType + PreferShiftHere() + scopeIn + functionSignature; operationContextBodyExps.Rule = MakePlusRule(operationContextBodyExps, null, operationContextBodyItem); operationContextBodyItem.Rule = preCondition | bodyExp | postCondition; #endregion #region preCondition preCondition.Rule = pre + identifier + colon + valueExp | pre + colon + valueExp; #endregion #region bodyExp bodyExp.Rule = body + colon + expression; #endregion #region postCondition postCondition.Rule = post + colon + valueExp | post + identifier + colon + valueExp; #endregion #endregion #region Operator,punctuation MarkPunctuation(",", "(", ")", "{", "}", "[", "]", ":"); MarkMemberSelect(".", "->"); //dot, propertyIs); RegisterOperators(1, lpar, rpar); RegisterOperators(2, "let", "in"); RegisterOperators(3, letExp, In); RegisterOperators(4, dot, scopeIn); RegisterOperators(5, not); RegisterOperators(6, "*", "/"); RegisterOperators(7, letExp, In); RegisterOperators(8, dot, scopeIn); RegisterOperators(9, "+", "-"); RegisterOperators(10, "<", ">", "<=", ">="); RegisterOperators(11, "=", "<>"); RegisterOperators(12, and); RegisterOperators(12, "div", "implies"); RegisterOperators(13, or); RegisterOperators(14, xor); RegisterOperators(15, "=", "<>"); #endregion this.Root = specification; }
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; }
internal virtual void InitProductions() { #region Definitions var statement = new NonTerminal(XpressConstants.Tokens.NonTerminals.Statement); var expression = new NonTerminal(XpressConstants.Tokens.NonTerminals.Expression); var parenExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.ParenExpression); var relationalExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.RelationalExpression); var binaryAdditiveExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryAdditiveExpression); var binaryMultiplicityExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryMultiplicityExpression); var unaryExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.UnaryExpression); var conditionalOperator = new NonTerminal(XpressConstants.Tokens.NonTerminals.ConditionalOperator); var relationalOperator = new NonTerminal(XpressConstants.Tokens.NonTerminals.RelationalOperator); var binaryAdditiveOperator = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryAdditiveOperator); var binaryMultiplicityOperator = new NonTerminal(XpressConstants.Tokens.NonTerminals.BinaryMultiplicityOperator); var unaryOperator = new NonTerminal(XpressConstants.Tokens.NonTerminals.UnaryOperator); var primaryExpression = new NonTerminal(XpressConstants.Tokens.NonTerminals.PrimaryExpression); var nullLiteral = new NonTerminal(XpressConstants.Tokens.NonTerminals.NullLiteral); var booleanLiteral = new NonTerminal(XpressConstants.Tokens.NonTerminals.BooleanLiteral); var identifier = TerminalFactory.CreateCSharpIdentifier(XpressConstants.Tokens.NonTerminals.Identifier); var numberLiteral = TerminalFactory.CreateCSharpNumber(XpressConstants.Tokens.NonTerminals.NumberLiteral); var stringLiteral = TerminalFactory.CreateCSharpString(XpressConstants.Tokens.NonTerminals.StringLiteral); var expressionBegin = ToTerm(XpressConstants.Tokens.Terminals.ExpressionBeginSymbol); var expressionEnd = ToTerm(XpressConstants.Tokens.Terminals.ExpressionEndSymbol); var conditionalAndOperator = ToTerm(XpressConstants.Tokens.Terminals.ConditionalAndOperator); var conditionalOrOperator = ToTerm(XpressConstants.Tokens.Terminals.ConditionalOrOperator); var relationalGreatThanOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalGreatThanOperator); var relationalLessThanOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalLessThanOperator); var relationalGreatThanOrEqualOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalGreatThanOrEqualOperator); var relationalLessThanOrEqualOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalLessThanOrEqualOperator); var relationalEqualityOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalEqualityOperator); var relationalNonEqualityOperator = ToTerm(XpressConstants.Tokens.Terminals.RelationalNonEqualityOperator); var binaryAdditionOperator = ToTerm(XpressConstants.Tokens.Terminals.BinaryAdditionOperator); var binarySubtrationOperator = ToTerm(XpressConstants.Tokens.Terminals.BinarySubtrationOperator); var binaryMultiplicationOperator = ToTerm(XpressConstants.Tokens.Terminals.BinaryMultiplicationOperator); var binaryDivisionOperator = ToTerm(XpressConstants.Tokens.Terminals.BinaryDivisionOperator); var binaryModuloOperator = ToTerm(XpressConstants.Tokens.Terminals.BinaryModuloOperator); var unaryNegationOperator = ToTerm(XpressConstants.Tokens.Terminals.UnaryNegationOperator); var nullValue = ToTerm(XpressConstants.Tokens.Terminals.NullValue); var booleanTrueValue = ToTerm(XpressConstants.Tokens.Terminals.BooleanTrueValue); var booleanFalseValue = ToTerm(XpressConstants.Tokens.Terminals.BooleanFalseValue); stringLiteral.AddStartEnd(XpressConstants.Tokens.Terminals.StringStartEndSymbol, StringOptions.NoEscapes); #endregion // BNF Root = statement; statement.Rule = expression; parenExpression.Rule = expressionBegin + expression + expressionEnd; expression.Rule = expression + conditionalOperator + relationalExpression | relationalExpression; conditionalOperator.Rule = conditionalAndOperator | conditionalOrOperator; relationalExpression.Rule = relationalExpression + relationalOperator + binaryAdditiveExpression | binaryAdditiveExpression; relationalOperator.Rule = relationalGreatThanOperator | relationalGreatThanOrEqualOperator | relationalLessThanOperator | relationalLessThanOrEqualOperator | relationalEqualityOperator | relationalNonEqualityOperator; binaryAdditiveExpression.Rule = binaryAdditiveExpression + binaryAdditiveOperator + binaryMultiplicityExpression | binaryMultiplicityExpression; binaryAdditiveOperator.Rule = binaryAdditionOperator | binarySubtrationOperator; binaryMultiplicityExpression.Rule = binaryMultiplicityExpression + binaryMultiplicityOperator + unaryExpression | unaryExpression; binaryMultiplicityOperator.Rule = binaryMultiplicationOperator | binaryDivisionOperator | binaryModuloOperator; unaryExpression.Rule = unaryOperator + primaryExpression | primaryExpression; unaryOperator.Rule = unaryNegationOperator; primaryExpression.Rule = identifier | numberLiteral | stringLiteral | booleanLiteral | nullLiteral | parenExpression; nullLiteral.Rule = nullValue; booleanLiteral.Rule = booleanTrueValue | booleanFalseValue; }
public JavaStubGrammar() { CommentTerminal single_line_comment = new CommentTerminal("SingleLineComment", "//", "\r", "\n"); CommentTerminal delimited_comment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(single_line_comment); NonGrammarTerminals.Add(delimited_comment); IdentifierTerminal identifier = new IdentifierTerminal("identifier"); KeyTerm keyword_package = Keyword("package"); KeyTerm keyword_import = Keyword("import"); KeyTerm keyword_public = Keyword("public"); KeyTerm keyword_protected = Keyword("protected"); KeyTerm keyword_static = Keyword("static"); KeyTerm keyword_final = Keyword("final"); KeyTerm keyword_abstract = Keyword("abstract"); KeyTerm keyword_synchronized = Keyword("synchronized"); KeyTerm keyword_default = Keyword("default"); KeyTerm keyword_native = Keyword("native"); KeyTerm keyword_volatile = Keyword("volatile"); KeyTerm keyword_transient = Keyword("transient"); KeyTerm keyword_enum = Keyword("enum"); KeyTerm keyword_class = Keyword("class"); KeyTerm keyword_interface = Keyword("interface"); KeyTerm keyword_at_interface = Keyword("@interface"); KeyTerm keyword_extends = Keyword("extends"); KeyTerm keyword_implements = Keyword("implements"); KeyTerm keyword_throw = Keyword("throw"); KeyTerm keyword_throws = Keyword("throws"); KeyTerm keyword_null = Keyword("null"); KeyTerm keyword_super = Keyword("super"); KeyTerm keyword_true = Keyword("true"); KeyTerm keyword_false = Keyword("false"); KeyTerm keyword_new = Keyword("new"); var compile_unit = DefaultNonTerminal("compile_unit"); var opt_package_decl = DefaultNonTerminal("opt_package_declaration"); var package_decl = DefaultNonTerminal("package_declaration"); var imports = DefaultNonTerminal("imports"); var import = DefaultNonTerminal("import"); var type_decls = DefaultNonTerminal("type_decls"); var type_decl = DefaultNonTerminal("type_decl"); var enum_decl = DefaultNonTerminal("enum_decl"); var enum_body = DefaultNonTerminal("enum_body"); var class_decl = DefaultNonTerminal("class_decl"); var opt_generic_arg_decl = DefaultNonTerminal("opt_generic_arg_decl"); var opt_extends_decl = DefaultNonTerminal("opt_extends_decl"); var opt_implements_decl = DefaultNonTerminal("opt_implements_decl"); var implements_decl = DefaultNonTerminal("implements_decl"); var interface_decl = DefaultNonTerminal("interface_decl"); var iface_or_at_iface = DefaultNonTerminal("iface_or_at_iface"); var type_body = DefaultNonTerminal("type_body"); var type_members = DefaultNonTerminal("type_members"); var type_member = DefaultNonTerminal("type_member"); var nested_type_decl = DefaultNonTerminal("nested_type_decl"); var ctor_decl = DefaultNonTerminal("ctor_decl"); var method_decl = DefaultNonTerminal("method_decl"); var field_decl = DefaultNonTerminal("field_decl"); var opt_field_assignment = DefaultNonTerminal("opt_field_assignment"); var static_ctor_decl = DefaultNonTerminal("static_ctor_decl"); var enum_members_decl = DefaultNonTerminal("enum_members_decl"); var enum_member_initializers = DefaultNonTerminal("enum_member_initializers"); var enum_member_initializer = DefaultNonTerminal("enum_member_initializer"); var opt_enum_braces = DefaultNonTerminal("opt_enum_braces"); var opt_final_field_assign = DefaultNonTerminal("opt_final_field_assign"); var final_field_assign = DefaultNonTerminal("final_field_assign"); var terminate_decl_or_body = DefaultNonTerminal("terminate_decl_or_body"); var assignments = DefaultNonTerminal("assignments"); var assignment = DefaultNonTerminal("assignment"); var assign_expr = DefaultNonTerminal("assign_expr"); var rvalue_expressions = DefaultNonTerminal("rvalue_expressions"); var rvalue_expression = DefaultNonTerminal("rvalue_expression"); var array_literal = DefaultNonTerminal("array_literal"); var annotations = DefaultNonTerminal("annotations"); var annotation = DefaultNonTerminal("annotation"); var opt_annotation_args = DefaultNonTerminal("opt_annotation_args"); var annotation_value_assignments = DefaultNonTerminal("annotation_value_assignments"); var annot_assign_expr = DefaultNonTerminal("annot_assign_expr"); var modifiers_then_opt_generic_arg = DefaultNonTerminal("modifiers_then_opt_generic_arg"); var modifier_or_generic_arg = DefaultNonTerminal("modifier_or_generic_arg"); var modifiers = DefaultNonTerminal("modifiers"); var modifier = DefaultNonTerminal("modifier"); var argument_decls = DefaultNonTerminal("argument_decls"); var argument_decl = DefaultNonTerminal("argument_decl"); var comma_separated_types = DefaultNonTerminal("comma_separated_types"); var throws_decl = DefaultNonTerminal("throws_decl"); var opt_throws_decl = DefaultNonTerminal("opt_throws_decl"); var type_name = DefaultNonTerminal("type_name"); var dotted_identifier = DefaultNonTerminal("dotted_identifier"); var array_type = DefaultNonTerminal("array_type"); var vararg_type = DefaultNonTerminal("vararg_type"); var generic_type = DefaultNonTerminal("generic_type"); var generic_definition_arguments = DefaultNonTerminal("generic_definition_arguments"); var generic_definition_argument = DefaultNonTerminal("generic_definition_argument"); var generic_definition_constraints = DefaultNonTerminal("generic_definition_constraints"); var generic_definition_arguments_spec = DefaultNonTerminal("generic_definition_arguments_spec"); var generic_instance_arguments_spec = DefaultNonTerminal("generic_instance_arguments_spec"); var generic_instance_arguments = DefaultNonTerminal("generic_instance_arguments"); var generic_instance_argument = DefaultNonTerminal("generic_instance_argument"); var generic_instance_identifier_or_q = DefaultNonTerminal("generic_instance_identifier_or_q"); var generic_instance_constraints = DefaultNonTerminal("generic_instance_constraints"); var generic_instance_constraints_extends = DefaultNonTerminal("generic_instance_constraints_extends"); var generic_instance_constraints_super = DefaultNonTerminal("generic_instance_constraints_super"); var generic_instance_constraint_types = DefaultNonTerminal("generic_instance_constraint_types"); var impl_expressions = DefaultNonTerminal("impl_expressions"); var impl_expression = DefaultNonTerminal("impl_expression"); var call_super = DefaultNonTerminal("call_super"); var super_args = DefaultNonTerminal("super_args"); var default_value_expr = DefaultNonTerminal("default_value_expr"); var default_value_casted = DefaultNonTerminal("default_value_casted"); var default_value_literal = DefaultNonTerminal("default_value_literal"); var new_array = DefaultNonTerminal("new_array"); var runtime_exception = DefaultNonTerminal("runtime_exception"); var numeric_terminal = TerminalFactory.CreateCSharpNumber("numeric_value_literal"); numeric_terminal.AddPrefix("-", NumberOptions.AllowSign); numeric_terminal.AddPrefix("+", NumberOptions.AllowSign); //numeric_terminal.AddSuffix ("f"); numeric_terminal.AddSuffix("L"); var numeric_literal = DefaultNonTerminal("numeric_literal"); var string_literal = TerminalFactory.CreateCSharpString("string_literal"); var value_literal = DefaultNonTerminal("value_literal"); var identifier_wild = DefaultNonTerminal("identifier_wild"); // <construction_rules> compile_unit.Rule = opt_package_decl + imports + type_decls; opt_package_decl.Rule = package_decl | Empty; package_decl.Rule = keyword_package + dotted_identifier + ";"; imports.Rule = MakeStarRule(imports, import); import.Rule = keyword_import + dotted_identifier + ";"; type_decls.Rule = MakeStarRule(type_decls, type_decl); type_decl.Rule = class_decl | interface_decl | enum_decl; // FIXME: those modifiers_then_opt_generic_arg should be actually just modifiers... see modifiers_then_opt_generic_arg.Rule below. enum_decl.Rule = annotations + modifiers_then_opt_generic_arg + keyword_enum + identifier + opt_implements_decl + "{" + enum_body + "}"; enum_body.Rule = Empty | enum_members_decl + type_members; class_decl.Rule = annotations + modifiers_then_opt_generic_arg + keyword_class + identifier + opt_generic_arg_decl + opt_extends_decl + opt_implements_decl + type_body; interface_decl.Rule = annotations + modifiers_then_opt_generic_arg + iface_or_at_iface + identifier + opt_generic_arg_decl + opt_extends_decl + opt_implements_decl + type_body; iface_or_at_iface.Rule = keyword_interface | keyword_at_interface; opt_generic_arg_decl.Rule = Empty | "<" + generic_definition_arguments + ">"; opt_extends_decl.Rule = Empty | keyword_extends + implements_decl; // when it is used with an interface, it can be more than one... opt_implements_decl.Rule = Empty | keyword_implements + implements_decl; implements_decl.Rule = MakePlusRule(implements_decl, ToTerm(","), type_name); type_body.Rule = T("{") + type_members + T("}"); annotations.Rule = MakeStarRule(annotations, annotation); annotation.Rule = T("@") + dotted_identifier + opt_annotation_args; opt_annotation_args.Rule = Empty | T("(") + annotation_value_assignments + T(")"); annotation_value_assignments.Rule = rvalue_expression | MakeStarRule(annotation_value_assignments, ToTerm(","), annot_assign_expr); annot_assign_expr.Rule = assign_expr | T("{") + rvalue_expressions + T("}"); // HACK: I believe this is an Irony bug that adding opt_generic_arg_decl here results in shift-reduce conflict, but it's too complicated to investigate the actual issue. // As a workaround I add generic arguments as part of this "modifier" so that it can be safely added to a generic method declaration. modifiers_then_opt_generic_arg.Rule = MakeStarRule(modifiers_then_opt_generic_arg, modifier_or_generic_arg); modifiers.Rule = MakeStarRule(modifiers, modifier); modifier_or_generic_arg.Rule = modifier | generic_definition_arguments_spec; modifier.Rule = keyword_public | keyword_protected | keyword_final | keyword_abstract | keyword_synchronized | keyword_default | keyword_native | keyword_volatile | keyword_transient | keyword_static; type_members.Rule = MakeStarRule(type_members, type_member); type_member.Rule = nested_type_decl | ctor_decl | method_decl | field_decl | static_ctor_decl; nested_type_decl.Rule = type_decl; enum_members_decl.Rule = enum_member_initializers + ";"; enum_member_initializers.Rule = MakeStarRule(enum_member_initializers, ToTerm(","), enum_member_initializer); enum_member_initializer.Rule = annotations + identifier + opt_enum_braces; opt_enum_braces.Rule = Empty | "(" + ")"; static_ctor_decl.Rule = annotations + keyword_static + "{" + assignments + "}"; assignments.Rule = MakeStarRule(assignments, assignment); assignment.Rule = assign_expr + ";"; assign_expr.Rule = identifier + "=" + rvalue_expression; rvalue_expressions.Rule = MakeStarRule(rvalue_expressions, ToTerm(","), rvalue_expression); rvalue_expression.Rule = value_literal | new_array | type_name | identifier | array_literal | annotation; array_literal.Rule = "{" + rvalue_expressions + "}"; field_decl.Rule = annotations + modifiers_then_opt_generic_arg + type_name + identifier + opt_field_assignment + ";" + opt_final_field_assign; opt_field_assignment.Rule = Empty | "=" + rvalue_expression; opt_final_field_assign.Rule = Empty | "{" + assign_expr + ";" + "}"; terminate_decl_or_body.Rule = ";" | ("{" + impl_expressions + "}") | (keyword_default + default_value_literal + ";"); ctor_decl.Rule = annotations + modifiers_then_opt_generic_arg + identifier + "(" + argument_decls + ")" + opt_throws_decl + terminate_decl_or_body; // these Empties can make the structure common to method_decl. method_decl.Rule = annotations + modifiers_then_opt_generic_arg + /*opt_generic_arg_decl*/ type_name + identifier + "(" + argument_decls + ")" + opt_throws_decl + terminate_decl_or_body; impl_expressions.Rule = MakeStarRule(impl_expressions, impl_expression); impl_expression.Rule = call_super | runtime_exception | assign_expr; call_super.Rule = keyword_super + "(" + super_args + ")" + ";"; super_args.Rule = MakeStarRule(super_args, ToTerm(","), default_value_expr); default_value_expr.Rule = keyword_null | default_value_casted | default_value_literal; default_value_casted.Rule = "(" + type_name + ")" + default_value_expr; default_value_literal.Rule = numeric_terminal | "\"\"" | "{" + "}" | keyword_true | keyword_false; runtime_exception.Rule = keyword_throw + keyword_new + identifier + "(\"Stub!\"" + ")" + ";"; new_array.Rule = keyword_new + dotted_identifier + "[" + numeric_literal + "]"; argument_decls.Rule = annotations | MakeStarRule(argument_decls, ToTerm(","), argument_decl); argument_decl.Rule = annotations + type_name + identifier; throws_decl.Rule = keyword_throws + comma_separated_types; comma_separated_types.Rule = MakeStarRule(comma_separated_types, ToTerm(","), type_name); opt_throws_decl.Rule = Empty | throws_decl; type_name.Rule = dotted_identifier | array_type | vararg_type | generic_type; vararg_type.Rule = type_name + T("..."); array_type.Rule = type_name + ("[") + T("]"); generic_definition_arguments_spec.Rule = "<" + generic_definition_arguments + ">"; generic_type.Rule = dotted_identifier + generic_instance_arguments_spec; generic_instance_arguments_spec.Rule = "<" + generic_instance_arguments + ">"; generic_definition_arguments.Rule = MakePlusRule(generic_definition_arguments, ToTerm(","), generic_definition_argument); generic_definition_argument.Rule = identifier + generic_definition_constraints; generic_definition_constraints.Rule = Empty | generic_instance_constraints_extends | generic_instance_constraints_super; generic_instance_arguments.Rule = MakePlusRule(generic_instance_arguments, ToTerm(","), generic_instance_argument); generic_instance_argument.Rule = generic_instance_identifier_or_q + generic_instance_constraints; generic_instance_identifier_or_q.Rule = type_name | T("?"); generic_instance_constraints.Rule = Empty | generic_instance_constraints_extends | generic_instance_constraints_super; generic_instance_constraints_extends.Rule = keyword_extends + generic_instance_constraint_types; generic_instance_constraints_super.Rule = keyword_super + generic_instance_constraint_types; generic_instance_constraint_types.Rule = MakePlusRule(generic_instance_constraint_types, ToTerm("&"), type_name); dotted_identifier.Rule = MakePlusRule(dotted_identifier, ToTerm("."), identifier_wild); numeric_literal.Rule = numeric_terminal; numeric_literal.Rule |= "(" + numeric_literal + "/" + numeric_literal + ")"; value_literal.Rule = string_literal | numeric_literal | keyword_null; identifier_wild.Rule = identifier | "*"; // Define AST node creators Func <string, string> stripGenerics = s => s.IndexOf('<') > 0 ? s.Substring(0, s.IndexOf('<')) : s; single_line_comment.AstConfig.NodeCreator = DoNothing; delimited_comment.AstConfig.NodeCreator = DoNothing; identifier.AstConfig.NodeCreator = (ctx, node) => node.AstNode = node.Token.ValueString; compile_unit.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new JavaPackage(null) { Name = (string)node.ChildNodes [0].AstNode, Types = ((IEnumerable <JavaType>)node.ChildNodes [2].AstNode).ToList() }; }; opt_package_decl.AstConfig.NodeCreator = SelectSingleChild; package_decl.AstConfig.NodeCreator = SelectChildValueAt(1); imports.AstConfig.NodeCreator = CreateArrayCreator <object> (); import.AstConfig.NodeCreator = SelectChildValueAt(1); type_decls.AstConfig.NodeCreator = CreateArrayCreator <JavaType> (); type_decl.AstConfig.NodeCreator = SelectSingleChild; opt_generic_arg_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode; }; opt_extends_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode; }; opt_implements_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = node.ChildNodes.Count == 0 ? null : node.ChildNodes [1].AstNode; }; implements_decl.AstConfig.NodeCreator = CreateArrayCreator <string> (); Action <ParseTreeNode, JavaType> fillType = (node, type) => { var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode; var mods = modsOrTps.OfType <string> (); bool isEnum = node.ChildNodes [2].AstNode as string == "enum"; type.Abstract |= mods.Contains("abstract"); type.Static |= mods.Contains("static"); type.Final |= mods.Contains("final"); type.Visibility = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? ""; type.Name = (string)node.ChildNodes [3].AstNode; type.Deprecated = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated"; type.TypeParameters = isEnum ? null : (JavaTypeParameters)node.ChildNodes [4].AstNode; type.Members = (IList <JavaMember>)node.ChildNodes [isEnum ? 6 : 7].AstNode; }; enum_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var type = new JavaClass(null) { Extends = "java.lang.Enum", Final = true }; var methods = new JavaMember [] { new JavaMethod(null) { Deprecated = "not deprecated", Name = "valueOf", // Return needs to be filled later, with full package name. Static = true, Visibility = "public", Parameters = new JavaParameter [] { new JavaParameter(null) { Name = "name", Type = "java.lang.String" } }, }, new JavaMethod(null) { Deprecated = "not deprecated", Name = "values", // Return needs to be filled later, with full package name. Static = true, Visibility = "public", Parameters = new JavaParameter [0], } }; fillType(node, type); node.AstNode = type; }; class_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var exts = ((IEnumerable <string>)node.ChildNodes [5].AstNode) ?? Enumerable.Empty <string> (); var impls = ((IEnumerable <string>)node.ChildNodes [6].AstNode) ?? Enumerable.Empty <string> (); var ext = exts.FirstOrDefault() ?? "java.lang.Object"; var type = new JavaClass(null) { Extends = stripGenerics(ext), ExtendsGeneric = ext, Implements = impls.Select(s => new JavaImplements { Name = stripGenerics(s), NameGeneric = s }).ToArray(), }; fillType(node, type); node.AstNode = type; }; interface_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); bool annot = node.ChildNodes [2].AstNode as string == "@interface"; var exts = ((IEnumerable <string>)node.ChildNodes [5].AstNode) ?? Enumerable.Empty <string> (); var impls = ((IEnumerable <string>)node.ChildNodes [6].AstNode) ?? Enumerable.Empty <string> (); var type = new JavaInterface(null) { Implements = exts.Concat(impls).Select(s => new JavaImplements { Name = stripGenerics(s), NameGeneric = s }).ToList(), }; if (annot) { type.Implements.Add(new JavaImplements { Name = "java.lang.annotation.Annotation", NameGeneric = "java.lang.annotation.Annotation" }); } fillType(node, type); node.AstNode = type; }; iface_or_at_iface.AstConfig.NodeCreator = SelectSingleChild; type_body.AstConfig.NodeCreator = SelectChildValueAt(1); type_members.AstConfig.NodeCreator = CreateArrayCreator <JavaMember> (); type_member.AstConfig.NodeCreator = SelectSingleChild; nested_type_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new JavaNestedType(null) { Type = (JavaType)node.ChildNodes [0].AstNode }; }; Action <ParseTreeNode, JavaMethodBase> fillMethodBase = (node, method) => { bool ctor = node.ChildNodes.Count == 8; var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode; var mods = modsOrTps.OfType <string> (); method.Static = mods.Contains("static"); method.Visibility = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? ""; method.Name = (string)node.ChildNodes [ctor ? 2 : 3].AstNode; method.Parameters = ((IEnumerable <JavaParameter>)node.ChildNodes [ctor ? 4 : 5].AstNode).ToArray(); method.ExtendedSynthetic = mods.Contains("synthetic"); // HACK: Exception "name" can be inconsistent for nested types, and this nested type detection is hacky. Func <string, string> stripPackage = s => { var packageTokens = s.Split('.').TakeWhile(t => !t.Any(c => Char.IsUpper(c))); return(s.Substring(Enumerable.Sum(packageTokens.Select(t => t.Length)) + packageTokens.Count())); }; method.Exceptions = ((IEnumerable <string>)node.ChildNodes [ctor ? 6 : 7].AstNode) ?.Select(s => new JavaException { Type = s, Name = stripPackage(s) }) ?.ToArray(); method.Deprecated = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated"; method.Final = mods.Contains("final"); method.TypeParameters = modsOrTps.OfType <JavaTypeParameters> ().FirstOrDefault(); }; ctor_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var annots = node.ChildNodes [0].AstNode; var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode; var mods = modsOrTps.OfType <string> (); var ctor = new JavaConstructor(null); fillMethodBase(node, ctor); node.AstNode = ctor; }; method_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var annots = node.ChildNodes [0].AstNode; var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode; var mods = modsOrTps.OfType <string> (); var method = new JavaMethod(null) { Return = (string)node.ChildNodes [2].AstNode, Abstract = mods.Contains("abstract"), Native = mods.Contains("native"), Synchronized = mods.Contains("synchronized"), ExtendedSynthetic = mods.Contains("synthetic"), }; fillMethodBase(node, method); node.AstNode = method; }; field_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var annots = node.ChildNodes [0].AstNode; var modsOrTps = (IEnumerable <object>)node.ChildNodes [1].AstNode; var mods = modsOrTps.OfType <string> (); var value = node.ChildNodes [4].AstNode?.ToString(); var type = (string)node.ChildNodes [2].AstNode; node.AstNode = new JavaField(null) { Static = mods.Contains("static"), Visibility = mods.FirstOrDefault(s => s == "public" || s == "protected") ?? "", Type = stripGenerics(type), TypeGeneric = type, Name = (string)node.ChildNodes [3].AstNode, Deprecated = ((IEnumerable <string>)node.ChildNodes [0].AstNode).Any(v => v == "java.lang.Deprecated" || v == "Deprecated") ? "deprecated" : "not deprecated", Value = value == "null" ? null : value, // null will not be explicitly written. Volatile = mods.Contains("volatile"), Final = mods.Contains("final"), Transient = mods.Contains("transient"), }; }; opt_field_assignment.AstConfig.NodeCreator = (ctx, node) => node.AstNode = node.ChildNodes.Count > 0 ? node.ChildNodes [1].AstNode : null; opt_final_field_assign.AstConfig.NodeCreator = (ctx, node) => node.AstNode = node.ChildNodes.Count > 0 ? node.ChildNodes [1].AstNode : null; static_ctor_decl.AstConfig.NodeCreator = DoNothing; // static constructors are ignorable. enum_body.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var ml = new List <JavaMember> (); foreach (var c in node.ChildNodes) { ml.AddRange((IEnumerable <JavaMember>)c.AstNode); } node.AstNode = ml; }; enum_members_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); if (node.ChildNodes.Count > 0) { node.AstNode = ((IEnumerable <string>)node.ChildNodes [0].AstNode) .Select(s => new JavaField(null) { Name = s, Final = true, Deprecated = "not deprecated", Static = true, // Type needs to be filled later, with full package name. Visibility = "public" }); } }; enum_member_initializers.AstConfig.NodeCreator = CreateArrayCreator <string> (); enum_member_initializer.AstConfig.NodeCreator = SelectChildValueAt(1); opt_enum_braces.AstConfig.NodeCreator = DoNothing; terminate_decl_or_body.AstConfig.NodeCreator = DoNothing; // method/ctor body doesn't matter. assignments.AstConfig.NodeCreator = CreateArrayCreator <object> (); assignment.AstConfig.NodeCreator = SelectChildValueAt(0); assign_expr.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new KeyValuePair <string, string?> ((string)node.ChildNodes [0].AstNode, node.ChildNodes [2].AstNode?.ToString()); }; rvalue_expressions.AstConfig.NodeCreator = CreateArrayCreator <object> (); rvalue_expression.AstConfig.NodeCreator = SelectSingleChild; array_literal.AstConfig.NodeCreator = CreateStringFlattener(); annotations.AstConfig.NodeCreator = CreateArrayCreator <string> (); annotation.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node.ChildNodes [1]); // we only care about name. node.AstNode = node.ChildNodes [1].AstNode; }; opt_annotation_args.AstConfig.NodeCreator = DoNothing; annotation_value_assignments.AstConfig.NodeCreator = DoNothing; annot_assign_expr.AstConfig.NodeCreator = DoNothing; modifiers_then_opt_generic_arg.AstConfig.NodeCreator = CreateArrayCreator <object> (); modifier_or_generic_arg.AstConfig.NodeCreator = SelectSingleChild; modifiers.AstConfig.NodeCreator = CreateArrayCreator <string> (); modifier.AstConfig.NodeCreator = CreateStringFlattener(); argument_decls.AstConfig.NodeCreator = CreateArrayCreator <JavaParameter> (); argument_decl.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new JavaParameter(null) { Type = (string)node.ChildNodes [1].AstNode, Name = (string)node.ChildNodes [2].AstNode }; }; opt_throws_decl.AstConfig.NodeCreator = SelectSingleChild; throws_decl.AstConfig.NodeCreator = SelectChildValueAt(1); comma_separated_types.AstConfig.NodeCreator = CreateArrayCreator <string> (); type_name.AstConfig.NodeCreator = SelectSingleChild; dotted_identifier.AstConfig.NodeCreator = CreateStringFlattener("."); array_type.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = node.ChildNodes [0].AstNode + "[]"; }; vararg_type.AstConfig.NodeCreator = CreateStringFlattener(); generic_type.AstConfig.NodeCreator = CreateStringFlattener(); generic_definition_arguments_spec.AstConfig.NodeCreator = SelectChildValueAt(1); generic_instance_arguments_spec.AstConfig.NodeCreator = (ctx, node) => { // It is distinct from generic type parameters definition. ProcessChildren(ctx, node); node.AstNode = "<" + string.Join(", ", (IEnumerable <string>)node.ChildNodes [1].AstNode) + ">"; }; generic_definition_arguments.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new JavaTypeParameters((JavaMethod?)null) { TypeParameters = node.ChildNodes.Select(c => c.AstNode).Cast <JavaTypeParameter> ().ToList() }; }; generic_definition_argument.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); node.AstNode = new JavaTypeParameter(null) { Name = (string)node.ChildNodes [0].AstNode, GenericConstraints = (JavaGenericConstraints)node.ChildNodes [1].AstNode }; }; generic_definition_constraints.AstConfig.NodeCreator = SelectSingleChild; generic_instance_arguments.AstConfig.NodeCreator = CreateArrayCreator <string> (); generic_instance_argument.AstConfig.NodeCreator = CreateStringFlattener(); generic_instance_identifier_or_q.AstConfig.NodeCreator = SelectSingleChild; generic_instance_constraints.AstConfig.NodeCreator = (ctx, node) => { ProcessChildren(ctx, node); var c = (JavaGenericConstraints?)node.ChildNodes.FirstOrDefault()?.AstNode; if (c != null) { node.AstNode = " " + c.BoundsType + " " + string.Join(" & ", c.GenericConstraints.Select(cc => cc.Type)); } }; AstNodeCreator createGenericConstaints = (ctx, node) => { ProcessChildren(ctx, node); var cl = ((IEnumerable <string>)node.ChildNodes [1].AstNode).Select(s => new JavaGenericConstraint { Type = s }); node.AstNode = new JavaGenericConstraints() { BoundsType = (string)node.ChildNodes [0].AstNode, GenericConstraints = cl.Any() ? cl.ToArray() : null, }; }; generic_instance_constraints_extends.AstConfig.NodeCreator = createGenericConstaints; generic_instance_constraints_super.AstConfig.NodeCreator = createGenericConstaints; generic_instance_constraint_types.AstConfig.NodeCreator = CreateArrayCreator <string> (); impl_expressions.AstConfig.NodeCreator = CreateArrayCreator <object> (); impl_expression.AstConfig.NodeCreator = SelectSingleChild; // each expression item is not seriously processed. // They are insignificant except for consts, and for consts they are just string values. call_super.AstConfig.NodeCreator = CreateStringFlattener(); super_args.AstConfig.NodeCreator = CreateStringFlattener(); default_value_expr.AstConfig.NodeCreator = CreateStringFlattener(); default_value_casted.AstConfig.NodeCreator = CreateStringFlattener(); default_value_literal.AstConfig.NodeCreator = CreateStringFlattener(); new_array.AstConfig.NodeCreator = DoNothing; runtime_exception.AstConfig.NodeCreator = CreateStringFlattener(); Func <string, string, string> stripTail = (s, t) => s.EndsWith(t, StringComparison.Ordinal) ? s.Substring(0, s.Length - t.Length) : s; numeric_terminal.AstConfig.NodeCreator = (ctx, node) => node.AstNode = stripTail(stripTail(node.Token.Text, "L"), "f"); numeric_literal.AstConfig.NodeCreator = CreateStringFlattener(); string_literal.AstConfig.NodeCreator = (ctx, node) => node.AstNode = '"' + node.Token.ValueString + '"'; value_literal.AstConfig.NodeCreator = SelectSingleChild; identifier_wild.AstConfig.NodeCreator = SelectSingleChild; this.Root = compile_unit; }
public Gramatica() : base(caseSensitive: true) { #region ER NumberLiteral doble = new NumberLiteral("doble"); IdentifierTerminal id = new IdentifierTerminal("id"); StringLiteral cadena = TerminalFactory.CreateCSharpString("cadena"); StringLiteral carac = TerminalFactory.CreateCSharpChar("cadena"); ConstantTerminal booleano = new ConstantTerminal("booleano"); booleano.Add("true", true); booleano.Add("false", false); CommentTerminal comentario2 = new CommentTerminal("comentario2", "</", "/>"); CommentTerminal comentario1 = new CommentTerminal("comentario1", "-->", "\n", "\r\n"); base.NonGrammarTerminals.Add(comentario2); base.NonGrammarTerminals.Add(comentario1); #endregion #region Terminales var mas = ToTerm("+"); var menos = ToTerm("-"); var mul = ToTerm("*"); var div = ToTerm("/"); var mod = ToTerm("%"); var pot = ToTerm("^"); var parA = ToTerm("("); var parC = ToTerm(")"); var corA = ToTerm("["); var corC = ToTerm("]"); var llavA = ToTerm("{"); var llavC = ToTerm("}"); var pYc = ToTerm(";"); var dosPuntos = ToTerm(":"); var coma = ToTerm(","); var asig = ToTerm("="); var igual = ToTerm("="); var mayor = ToTerm(">"); var menor = ToTerm("<"); var mayorIgual = ToTerm(">="); var menorIgual = ToTerm("<="); var igualIgual = ToTerm("=="); var noIgual = ToTerm("!="); var diferecia = ToTerm("~"); var Mostrar = ToTerm("Mostrar"); var resInt = ToTerm("Entero"); var resDouble = ToTerm("Decimal"); var resString = ToTerm("Texto"); var resChar = ToTerm("Caracter"); var resBool = ToTerm("Booleano"); var resVoid = ToTerm("Vacio"); var OR = ToTerm("||"); var AND = ToTerm("&&"); var NOT = ToTerm("!"); var resReturn = ToTerm("Retorno"); var Es_verdadero = ToTerm("Es_verdadero"); var Es_false = ToTerm("Es_falso"); var Cambiar_A = ToTerm("Cambiar_A"); var Valor = ToTerm("Valor"); var No_cumple = ToTerm("No_cumple"); var Para = ToTerm("Para"); var Hasta_que = ToTerm("Hasta_que"); var Mientras = ToTerm("Mientras_que"); var Romper = ToTerm("Romper"); var Continuar = ToTerm("Continuar"); var DibujarAST = ToTerm("DibujarAST"); var DibujarEXP = ToTerm("DibujarEXP"); var DibujarTS = ToTerm("DibujarTS"); var Principal = ToTerm("Principal"); var Importar = ToTerm("Importar"); var Definir = ToTerm("Definir"); #endregion #region No Terminales NonTerminal S = new NonTerminal("S"), E = new NonTerminal("E"), EXPR = new NonTerminal("EXPR"), EXPL = new NonTerminal("EXPL"), PROGRAMA = new NonTerminal("PROGRAMA"), CUERPOS = new NonTerminal("CUERPOS"), CUERPO = new NonTerminal("CUERPO"), ATRIBUTOS = new NonTerminal("ATRIBUTOS"), ATRIBUTO = new NonTerminal("ATRIBUTO"), DECLARACION = new NonTerminal("DECLARACION"), ASIGNACION = new NonTerminal("ASIGNACION"), PRINCIPAL = new NonTerminal("PRINCIPAL"), METODO = new NonTerminal("METODO"), FUNCION = new NonTerminal("FUNCION"), TIPO = new NonTerminal("TIPO"), MOSTRAR = new NonTerminal("MOSTRAR"), MOST = new NonTerminal("MOST"), DIBUJAR = new NonTerminal("DIBUJAR"), LISTA_ID = new NonTerminal("LISTA_ID"), LISTA_PARAM = new NonTerminal("LISTA_PARAM"), DECLA = new NonTerminal("DECLA"), UNICO = new NonTerminal("UNICO"), UNICOS = new NonTerminal("UNICOS"), LLAMADA = new NonTerminal("LLAMADA"), LLAMFUNC = new NonTerminal("LLAMFUNC"), OPERANDO = new NonTerminal("OPERANDO"), RETORNO = new NonTerminal("RETORNO"), SI = new NonTerminal("SI"), SINO = new NonTerminal("SINO"), SINO_SI = new NonTerminal("SINO_SI"), SINOSI = new NonTerminal("SINOSI"), INTERRUMPIR = new NonTerminal("INTERRUMPIR"), CASO = new NonTerminal("CASO"), CASOS = new NonTerminal("CASOS"), DEFECTO = new NonTerminal("DEFECTO"), MIENTRAS = new NonTerminal("MIENTRAS"), PARA = new NonTerminal("PARA"), OP = new NonTerminal("OP"), HACER = new NonTerminal("HACER"), SALIR = new NonTerminal("SALIR"), DEFINIR = new NonTerminal("DEFINIR"), IMPORTAR = new NonTerminal("IMPORTAR"), IMPORTE = new NonTerminal("IMPORTE"); #endregion #region Gramatica S.Rule = PROGRAMA; PROGRAMA.Rule = CUERPO; CUERPO.Rule = MakePlusRule(CUERPO, CUERPOS); CUERPOS.Rule = METODO | FUNCION | PRINCIPAL | DEFINIR | IMPORTAR | DECLARACION | ASIGNACION; CUERPOS.ErrorRule = SyntaxError + llavC; CUERPOS.ErrorRule = SyntaxError + pYc; IMPORTAR.Rule = Importar + IMPORTE + pYc; IMPORTE.Rule = MakePlusRule(IMPORTE, ToTerm("."), id); DEFINIR.Rule = Definir + cadena + pYc | Definir + doble + pYc; ATRIBUTOS.Rule = MakePlusRule(ATRIBUTOS, ATRIBUTO) | Empty; ATRIBUTO.Rule = DECLARACION | ASIGNACION | DIBUJAR | MOSTRAR | LLAMFUNC | SALIR | SI | INTERRUMPIR | MIENTRAS | PARA | HACER | RETORNO; ATRIBUTO.ErrorRule = SyntaxError + pYc; ATRIBUTO.ErrorRule = SyntaxError + llavC; METODO.Rule = resVoid + id + parA + LISTA_PARAM + parC + llavA + ATRIBUTOS + llavC; FUNCION.Rule = TIPO + id + parA + LISTA_PARAM + parC + llavA + ATRIBUTOS + llavC; PRINCIPAL.Rule = resVoid + Principal + parA + parC + llavA + ATRIBUTOS + llavC; RETORNO.Rule = resReturn + EXPL + pYc; SALIR.Rule = Romper + pYc; DECLARACION.Rule = TIPO + LISTA_ID + pYc; DECLA.Rule = TIPO + id; ASIGNACION.Rule = TIPO + LISTA_ID + asig + EXPL + pYc | id + asig + EXPL + pYc; DIBUJAR.Rule = DibujarAST + parA + E + parC + pYc | DibujarEXP + parA + EXPL + parC + pYc | DibujarTS + parA + parC + pYc; MOSTRAR.Rule = Mostrar + parA + MOST + parC + pYc; MOST.Rule = MakePlusRule(MOST, coma, E); LISTA_ID.Rule = MakePlusRule(LISTA_ID, coma, id); LISTA_PARAM.Rule = MakePlusRule(LISTA_PARAM, coma, DECLA) | MakePlusRule(LISTA_PARAM, coma, E) | Empty; UNICO.Rule = MakePlusRule(UNICO, OPERANDO, UNICOS); UNICOS.Rule = E; LLAMADA.Rule = id + parA + LISTA_PARAM + parC; LLAMFUNC.Rule = LLAMADA + pYc; SI.Rule = Es_verdadero + parA + EXPL + parC + llavA + ATRIBUTOS + llavC + SINO; SINO.Rule = Es_false + llavA + ATRIBUTOS + llavC | Empty; INTERRUMPIR.Rule = Cambiar_A + parA + E + parC + llavA + CASOS + DEFECTO + llavC; CASOS.Rule = MakePlusRule(CASOS, CASO) | Empty; CASO.Rule = Valor + E + dosPuntos + ATRIBUTOS; DEFECTO.Rule = No_cumple + dosPuntos + ATRIBUTOS | Empty; MIENTRAS.Rule = Mientras + parA + EXPL + parC + llavA + ATRIBUTOS + llavC; PARA.Rule = Para + parA + ASIGNACION + EXPL + pYc + OP + parC + llavA + ATRIBUTOS + llavC; OP.Rule = ToTerm("++") | ToTerm("--"); HACER.Rule = Hasta_que + parA + EXPL + parC + llavA + ATRIBUTOS + llavC; OPERANDO.Rule = mas | menos | mul | div | pot | mod; TIPO.Rule = resInt | resDouble | resString | resChar | resBool; E.Rule = E + mas + E | E + menos + E | E + mul + E | E + div + E | E + mod + E | E + pot + E | parA + E + parC | menos + E | LLAMADA | id | doble | cadena | booleano | carac; EXPR.Rule = E + mayor + E | E + menor + E | E + mayorIgual + E | E + menorIgual + E | E + igualIgual + E | E + noIgual + E | E + diferecia + E | E; EXPL.Rule = EXPL + OR + EXPL | EXPL + AND + EXPL | NOT + EXPL | EXPR | parA + EXPL + parC; #endregion #region Preferencias this.Root = S; this.MarkTransient(TIPO, UNICOS, CUERPOS); this.RegisterOperators(1, Associativity.Left, mas, menos); this.RegisterOperators(2, Associativity.Left, mul, div, mod); this.RegisterOperators(3, Associativity.Right, pot); this.RegisterOperators(4, "==", "!=", "<", ">", "<=", ">="); this.RegisterOperators(5, Associativity.Left, OR); this.RegisterOperators(6, Associativity.Left, AND); this.RegisterOperators(7, Associativity.Left, NOT); this.RegisterOperators(8, "(", ")"); this.MarkPunctuation("(", ")", ",", ";", "[", "]", "=", ":", "{", "}"); #endregion }
public TestSchemeFileGrammar() { #region Lexical structure StringLiteral StringLiteral = TerminalFactory.CreateCSharpString("StringLiteral"); NumberLiteral Number = CreateNumberLiteral("Number"); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //Temporarily, treat preprocessor instructions like comments CommentTerminal ppInstruction = new CommentTerminal("ppInstruction", "#", "\n"); NonGrammarTerminals.Add(ppInstruction); //Symbols KeyTerm semi = ToTerm(";", "semi"); NonTerminal semi_opt = new NonTerminal("semi?"); semi_opt.Rule = Empty | semi; KeyTerm dot = ToTerm(".", "dot"); KeyTerm comma = ToTerm(",", "comma"); NonTerminal commas_opt = new NonTerminal("commas_opt"); commas_opt.Rule = MakeStarRule(commas_opt, null, comma); KeyTerm Lbr = ToTerm("{"); KeyTerm Rbr = ToTerm("}"); #endregion #region NonTerminals var qual_name_with_targs = new NonTerminal("qual_name_with_targs"); var qual_name_segment = new NonTerminal("qual_name_segment"); var qual_name_segments_opt = new NonTerminal("qual_name_segments_opt"); var compilation_unit = new NonTerminal("compilation_unit"); var namespace_declaration = new NonTerminal("namespace_declaration"); var namespace_declarations_opt = new NonTerminal("namespace_declarations_opt"); var qualified_identifier = new NonTerminal("qualified_identifier"); var namespace_body = new NonTerminal("namespace_body"); var namespace_member_declaration = new NonTerminal("namespace_member_declaration"); var namespace_member_declarations = new NonTerminal("namespace_member_declarations"); var type_declaration = new NonTerminal("type_declaration"); var type_body = new NonTerminal("type_body"); var type_test_case = new NonTerminal("type_test_case"); var type_test_cases_opt = new NonTerminal("type_test_cases_opt"); var literal = new NonTerminal("literal"); var member = new NonTerminal("member"); var members = new NonTerminal("members"); var nested_members = new NonTerminal("nested_members"); var directive = new NonTerminal("directive"); var directives_opt = new NonTerminal("directives_opt"); var type_body_content = new FreeTextLiteral("type_body_content", FreeTextOptions.AllowEmpty, "}"); #endregion #region operators, punctuation and delimiters this.MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":"); this.MarkTransient(namespace_member_declaration, literal); this.AddTermsReportGroup("assignment", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="); this.AddTermsReportGroup("typename", "bool", "decimal", "float", "double", "string", "object", "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char"); this.AddTermsReportGroup("statement", "if", "switch", "do", "while", "for", "foreach", "continue", "goto", "return", "try", "yield", "break", "throw", "unchecked"); this.AddTermsReportGroup("type declaration", "public", "private", "protected", "static", "internal", "sealed", "abstract", "partial", "class"); this.AddTermsReportGroup("member declaration", "virtual", "override", "readonly", "volatile", "extern"); this.AddTermsReportGroup("constant", Number, StringLiteral); this.AddTermsReportGroup("constant", "true", "false", "null"); this.AddTermsReportGroup("unary operator", "+", "-", "!", "~"); this.AddToNoReportGroup(comma, semi); this.AddToNoReportGroup("var", "const", "new", "++", "--", "this", "base", "checked", "lock", "typeof", "default", "{", "}", "["); #endregion qual_name_segments_opt.Rule = MakeStarRule(qual_name_segments_opt, null, qual_name_segment); qual_name_segment.Rule = dot + identifier | "::" + identifier; qual_name_with_targs.Rule = identifier + qual_name_segments_opt; this.Root = compilation_unit; compilation_unit.Rule = namespace_declarations_opt; namespace_declaration.Rule = "namespace" + qualified_identifier + namespace_body + semi_opt; namespace_declarations_opt.Rule = MakeStarRule(namespace_declarations_opt, null, namespace_declaration); qualified_identifier.Rule = MakePlusRule(qualified_identifier, dot, identifier); namespace_body.Rule = "{" + namespace_member_declarations + "}"; namespace_member_declaration.Rule = namespace_declaration | type_declaration; namespace_member_declarations.Rule = MakePlusRule(namespace_member_declarations, null, namespace_member_declaration); type_declaration.Rule = "type" + identifier + type_body + type_test_cases_opt; type_body.Rule = Lbr + type_body_content + Rbr; type_test_cases_opt.Rule = MakeStarRule(type_test_cases_opt, null, type_test_case); type_test_case.Rule = ".{" + members + "}" + directives_opt; members.Rule = MakeStarRule(members, ToTerm(","), member); member.Rule = literal | nested_members; nested_members.Rule = ("[" + members + "]") | ("{" + members + "}"); literal.Rule = Number | StringLiteral | "true" | "false" | "null"; directive.Rule = "@" + identifier; directives_opt.Rule = MakeStarRule(directives_opt, null, directive); }
public Grammar() { #region 1. Terminals NumberLiteral n = TerminalFactory.CreateCSharpNumber("number"); StringLiteral stringLiteral = TerminalFactory.CreateCSharpString("String"); IdentifierTerminal ident = new IdentifierTerminal("Identifier"); this.MarkReservedWords( "assert", "assume", "axiom", "bool", "break", "bv0", "bv1", "bv2", "bv3", "bv4", "bv5", "bv6", "bv7", "bv8", "bv9", "bv10", "bv11", "bv12", "bv13", "bv14", "bv15", "bv16", "bv17", "bv18", "bv19", "bv20", "bv21", "bv22", "bv23", "bv24", "bv25", "bv26", "bv27", "bv28", "bv29", "bv30", "bv31", "bv32", "bv64", "call", "complete", "const", "div", "else", "ensures", "exists", "extends", "false", "forall", "free", "function", "goto", "havoc", "if", "implementation", "int", "invariant", "lambda", "mod", "modifies", "old", "procedure", "real", "requires", "return", "returns", "then", "true", "type", "unique", "var", "where", "while" ); StringLiteral s = new StringLiteral("String", "'", StringFlags.AllowsDoubledQuote); Terminal dot = ToTerm(".", "dot"); Terminal less = ToTerm("<"); Terminal greater = ToTerm(">"); Terminal iff = ToTerm("<==>"); Terminal implication = ToTerm("==>"); Terminal explication = ToTerm("<=="); Terminal LBracket = ToTerm("["); Terminal RBracket = ToTerm("]"); Terminal LParen = ToTerm("("); Terminal RParen = ToTerm(")"); Terminal RCurly = ToTerm("}"); Terminal LCurly = ToTerm("{"); Terminal LDoubleCurly = ToTerm("{{"); Terminal RDoubleCurly = ToTerm("}}"); Terminal comma = ToTerm(","); Terminal semicolon = ToTerm(";"); Terminal colon = ToTerm(":"); Terminal doubleColon = ToTerm("::"); #endregion #region 2. Non-terminals #region 2.1 Expressions NonTerminal expression = new NonTerminal("Expr"); NonTerminal BinOp = new NonTerminal("BinOp"); NonTerminal LUnOp = new NonTerminal("LUnOp"); NonTerminal RUnOp = new NonTerminal("RUnOp"); NonTerminal ArrayConstructor = new NonTerminal("ArrayConstructor"); #endregion #region 2.2 QualifiedName //Expression List: expr1, expr2, expr3, .. NonTerminal expressionList = new NonTerminal("ExprList"); NonTerminal identList = new NonTerminal("identList"); //A name in form: a.b.c().d[1,2].e .... NonTerminal NewStmt = new NonTerminal("NewStmt"); NonTerminal NewArrStmt = new NonTerminal("NewArrStmt"); NonTerminal QualifiedName = new NonTerminal("QualifiedName"); NonTerminal GenericsPostfix = new NonTerminal("GenericsPostfix"); NonTerminal ArrayExpression = new NonTerminal("ArrayExpression"); NonTerminal FunctionExpression = new NonTerminal("FunctionExpression"); NonTerminal selectExpr = new NonTerminal("selectExpr"); #endregion #region 2.3 Statement NonTerminal Condition = new NonTerminal("Condition"); NonTerminal Statement = new NonTerminal("Statement"); NonTerminal Statements = new NonTerminal("Statements"); //Block NonTerminal blockStatement = new NonTerminal("CompoundStatement"); #endregion #region 2.4 Program and Functions NonTerminal Prog = new NonTerminal("Prog"); NonTerminal anything = new NonTerminal("anything"); // temporary hack NonTerminal declaration = new NonTerminal("declaration"); NonTerminal classDecl = new NonTerminal("class decl"); NonTerminal memberDecl = new NonTerminal("member decl"); NonTerminal fieldDecl = new NonTerminal("field declaration"); NonTerminal idType = new NonTerminal("identifier type"); NonTerminal typeDecl = new NonTerminal("type reference"); NonTerminal methodDecl = new NonTerminal("method declaration"); NonTerminal formalParameters = new NonTerminal("formals"); NonTerminal methodSpec = new NonTerminal("method spec"); NonTerminal formalsList = new NonTerminal("ParamaterListOpt"); NonTerminal functionDecl = new NonTerminal("function declaration"); NonTerminal predicateDecl = new NonTerminal("predicate declaration"); NonTerminal invariantDecl = new NonTerminal("invariant declaration"); NonTerminal Semi = new NonTerminal("semi"); NonTerminal Rhs = new NonTerminal("right-hand side"); NonTerminal FieldInit = new NonTerminal("field init"); NonTerminal FieldInits = new NonTerminal("field inits"); NonTerminal installBounds = new NonTerminal("installBounds"); NonTerminal localVarStmt = new NonTerminal("localVarStmt"); NonTerminal evalstate = new NonTerminal("evalstate"); NonTerminal channelDecl = new NonTerminal("channel declaration"); NonTerminal loopSpec = new NonTerminal("loop specification"); NonTerminal rdPermArg = new NonTerminal("rdPermArg"); #endregion #endregion #region 3. BNF rules Semi.Rule = semicolon; #region 3.1 Expressions selectExpr.Rule = (ToTerm("this") + ".").Q() + QualifiedName; evalstate.Rule = ident + ToTerm(".") + (ToTerm("acquire") | "release" | "fork" + FunctionExpression ) ; rdPermArg.Rule = ToTerm("*") | expression; expression.Rule = ToTerm("true") | "false" | "null" | "maxlock" | "lockbottom" | "this" | "result" | s | n | QualifiedName // The following is needed: to parse "A<B ..." either as comparison or as beginning of GenericsPostfix | QualifiedName + less + expression //| QualifiedName + less + QualifiedName + greater //| NewStmt | NewArrStmt | ArrayExpression | FunctionExpression | ArrayConstructor | expression + BinOp + expression | LUnOp + expression | expression + RUnOp | LParen + expression + RParen | ToTerm("unfolding") + expression + "in" + expression | ToTerm("acc") + "(" + selectExpr + (("," + expression) | Empty) + ")" | ToTerm("old") + "(" + expression + ")" | ToTerm("eval") + "(" + evalstate + "," + expression + ")" | ToTerm("credit") + "(" + expression + "," + expression + ")" | ToTerm("credit") + "(" + expression + ")" | expression + PreferShiftHere() + "?" + expression + ":" + expression | ToTerm("rd") + (ToTerm("holds") + "(" + expression + ")" | "(" + selectExpr + rdPermArg.Q() + ")" ) ; expressionList.Rule = MakePlusRule(expressionList, comma, expression); identList.Rule = MakePlusRule(identList, comma, ident); NewStmt.Rule = "new" + QualifiedName + GenericsPostfix.Q() + LParen + expressionList.Q() + RParen; NewArrStmt.Rule = "new" + QualifiedName + GenericsPostfix.Q() + LBracket + expressionList.Q() + RBracket; BinOp.Rule = ToTerm("+") | "-" | "*" | "div" | "mod" | "^" | "&" | "|" | "&&" | "||" | "==" | "!=" | greater | less | ">=" | "<=" | "is" | "=" | "+=" | "-=" | "." | "==>" | "<==>" | "<<" ; LUnOp.Rule = ToTerm("-") | "~" | "!"; RUnOp.Rule = ToTerm("++") | "--"; ArrayConstructor.Rule = LBracket + expressionList + RBracket; #endregion #region 3.2 QualifiedName ArrayExpression.Rule = QualifiedName + LBracket + expressionList + RBracket; FunctionExpression.Rule = QualifiedName + LParen + expressionList.Q() + RParen; QualifiedName.Rule = ident | QualifiedName + dot + ident; GenericsPostfix.Rule = less + QualifiedName + greater; //ExprList.Rule = Expr.Plus(comma); #endregion #region 3.3 Statement Condition.Rule = LParen + expression + RParen; installBounds.Rule = "installBounds" //= ToTerm("between") + expressionList + "and" + expressionList //| "below" + expressionList //| "below" + expressionList + "above" + expressionList //| "above" + expressionList //| "above" + expressionList + "below" + expressionList ; FieldInit.Rule = ident + ":=" + expression ; FieldInits.Rule = MakeStarRule(FieldInits, ToTerm(","), FieldInit); Rhs.Rule = ToTerm("new") + ident | ToTerm("new") + ident + "{" + FieldInits + "}" | ToTerm("new") + ident + installBounds | ToTerm("new") + ident + "{" + FieldInits + "}" + installBounds | expression ; localVarStmt.Rule = idType + ":=" + Rhs + Semi | idType + Semi ; loopSpec.Rule = ToTerm("invariant") + expression + Semi | "lockchange" + expressionList + Semi ; Statement.Rule = Semi | "if" + Condition + Statement ; Statements.Rule = MakeStarRule(Statements, null, Statement); blockStatement.Rule = LCurly + Statements + RCurly; #endregion #region 3.4 Prog Prog.Rule = anything.Star() + Eof; anything.Rule = ToTerm("assert") | "assume" | "axiom" | "bool" | "break" | "bv0" | "bv1" | "bv2" | "bv3" | "bv4" | "bv5" | "bv6" | "bv7" | "bv8" | "bv9" | "bv10" | "bv11" | "bv12" | "bv13" | "bv14" | "bv15" | "bv16" | "bv17" | "bv18" | "bv19" | "bv20" | "bv21" | "bv22" | "bv23" | "bv24" | "bv25" | "bv26" | "bv27" | "bv28" | "bv29" | "bv30" | "bv31" | "bv32" | "bv64" | "call" | "complete" | "const" | "else" | "ensures" | "exists" | "extends" | "false" | "forall" | "free" | "function" | "goto" | "havoc" | "if" | "implementation" | "int" | "invariant" | "lambda" | "modifies" | "old" | "procedure" | "real" | "requires" | "return" | "returns" | "then" | "true" | "type" | "unique" | "var" | "where" | "while" | ident | "}" | "{" | "(" | ")" | "[" | "]" | "," | ":" | ";" | "." | "`" | "==" | "=" | "!=" | "<" | "<=" | ">=" | ">" | "=>" | ":=" | "+" | "-" | "*" | "/" | "%" | "!!" | "|" | "!" | "&&" | "||" | "==>" | "<==>" | "#" | "$" | "^" | n | stringLiteral ; idType.Rule = ident + ":" + typeDecl | ident ; typeDecl.Rule = (ToTerm("int") | "bool" | "real" | ident) ; fieldDecl.Rule = ToTerm("var") + idType + Semi | ToTerm("ghost") + "var" + idType + Semi ; methodSpec.Rule = (ToTerm("requires") | "ensures" | "lockchange") + expression + Semi; formalsList.Rule = MakeStarRule(formalsList, comma, idType); formalParameters.Rule = LParen + formalsList + RParen; methodDecl.Rule = "method" + ident + formalParameters + (("returns" + formalParameters) | Empty) + methodSpec.Star() + blockStatement; functionDecl.Rule = ToTerm("function") + ident + formalParameters + ":" + typeDecl + methodSpec.Star() + "{" + expression + "}"; predicateDecl.Rule = ToTerm("predicate") + ident + "{" + expression + "}"; invariantDecl.Rule = ToTerm("invariant") + expression + Semi; memberDecl.Rule = fieldDecl | invariantDecl | methodDecl //| conditionDecl | predicateDecl | functionDecl ; classDecl.Rule = (ToTerm("external") | Empty) + "class" + ident + ("module" + ident | Empty) + "{" + memberDecl.Star() + "}"; channelDecl.Rule = ToTerm("channel") + ident + formalParameters + "where" + expression + Semi | ToTerm("channel") + ident + formalParameters + Semi; declaration.Rule = classDecl | channelDecl ; Terminal Comment = new CommentTerminal("Comment", "/*", "*/"); NonGrammarTerminals.Add(Comment); Terminal LineComment = new CommentTerminal("LineComment", "//", "\n"); NonGrammarTerminals.Add(LineComment); #endregion #endregion #region 4. Set starting symbol this.Root = Prog; // Set grammar root #endregion #region 5. Operators precedence RegisterOperators(1, "<==>"); RegisterOperators(2, "+", "-"); RegisterOperators(3, "*", "div", "mod", "!!"); RegisterOperators(4, Associativity.Right, "^"); RegisterOperators(5, "||"); RegisterOperators(6, "&&"); RegisterOperators(7, "==", "=", "!=", ">", "<", ">=", "<="); RegisterOperators(8, "in"); RegisterOperators(9, "-", "!", "++", "--"); RegisterOperators(10, "==>"); RegisterOperators(11, "."); //RegisterOperators(10, Associativity.Right, ".",",", ")", "(", "]", "[", "{", "}"); //RegisterOperators(11, Associativity.Right, "else"); #endregion #region 6. Punctuation symbols RegisterPunctuation("(", ")", "[", "]", "{", "}", ",", ";"); #endregion }
public Gramatica() : base(caseSensitive: true) { #region Terminales //comentarios CommentTerminal simple = new CommentTerminal("simple", "//", "\n", "\r\n"); CommentTerminal multiple = new CommentTerminal("multiple", "/*", "*/"); NonGrammarTerminals.Add(simple); NonGrammarTerminals.Add(multiple); //tipos de datos var entero = ToTerm("Int", "Int"); var cadena = ToTerm("String", "String"); var doble = ToTerm("Double", "Double"); var booleano = ToTerm("Bool", "Bool"); var caracter = ToTerm("Char", "Char"); var vacio = ToTerm("Void", "Void"); //palabras reservadas var importar = ToTerm("Import", "Import"); var retornar = ToTerm("Return", "Return"); var imprimir = ToTerm("Print", "Print"); var principal = ToTerm("Main", "Main"); var comparar = ToTerm("CompareTo", "CompareTo"); var obtenerUsuario = ToTerm("GetUser", "GetUser"); //palabras reservadas de sentencias de control var si = ToTerm("If", "If"); var sino = ToTerm("Else", "Else"); var cambiar = ToTerm("Switch", "Switch"); var caso = ToTerm("Case", "Case"); var defecto = ToTerm("Default", "Default"); var quebrar = ToTerm("Break", "Break"); var para = ToTerm("For", "For"); var mientras = ToTerm("While", "While"); var hacer = ToTerm("Do", "Do"); //operadores aritmeticos var sumar = ToTerm("+", "+"); var restar = ToTerm("-", "-"); var multiplicar = ToTerm("*", "*"); var dividir = ToTerm("/", "/"); var modular = ToTerm("%", "%"); var elevar = ToTerm("^", "^"); var asignacion = ToTerm("=", "="); var incremento = ToTerm("++", "++"); var decremento = ToTerm("--", "--"); //operadores relacionales var menorQue = ToTerm("<", "<"); var mayorQue = ToTerm(">", ">"); var menorIgual = ToTerm("<=", "<="); var mayorIgual = ToTerm(">=", ">="); var equivalente = ToTerm("==", "=="); var noEquivalente = ToTerm("!=", "!="); //operadores logicos var and = ToTerm("&&", "&&"); var or = ToTerm("||", "||"); var xor = ToTerm("|&", "|&"); var not = ToTerm("!", "!"); //punctuation mark var finSentencia = ToTerm(";", ";"); var parentesisA = ToTerm("(", "("); var parentesisC = ToTerm(")", ")"); var llaveA = ToTerm("{", "{"); var llaveC = ToTerm("}", "}"); var dosPuntos = ToTerm(":", ":"); var corcheteA = ToTerm("[", "["); var corcheteC = ToTerm("]", "]"); var coma = ToTerm(",", ","); var punto = ToTerm(".", "."); //valores var numero = TerminalFactory.CreateCSharpNumber("numero"); var identificador = TerminalFactory.CreateCSharpIdentifier("identificador"); var cad = TerminalFactory.CreateCSharpString("cadena"); var falso = ToTerm("False", "falso"); var verdadero = ToTerm("True", "verdadero"); var car = TerminalFactory.CreateCSharpChar("caracter"); #endregion #region Precedencias y puntuaciones this.MarkPunctuation(finSentencia, parentesisA, parentesisC, llaveA, llaveC, dosPuntos, coma, punto); RegisterOperators(1, Associativity.Left, sumar, restar); RegisterOperators(2, Associativity.Left, multiplicar, modular, dividir); RegisterOperators(3, Associativity.Right, elevar); RegisterOperators(5, equivalente, noEquivalente, menorQue, menorIgual, mayorQue, mayorIgual); RegisterOperators(6, Associativity.Left, or); RegisterOperators(7, Associativity.Left, xor); RegisterOperators(8, Associativity.Left, and); RegisterOperators(9, Associativity.Left, not); RegisterOperators(10, parentesisA, parentesisC); #endregion #region No Terminales NonTerminal INICIO = new NonTerminal("INICIO"); NonTerminal DECLARACION = new NonTerminal("DECLARACION"); NonTerminal PRINCIPAL = new NonTerminal("PRINCIPAL"); NonTerminal ASIGNACION = new NonTerminal("ASIGNACION"); NonTerminal WHILE = new NonTerminal("WHILE"); NonTerminal DO_WHILE = new NonTerminal("DO_WHILE"); NonTerminal IF = new NonTerminal("IF"); NonTerminal ELSE = new NonTerminal("ELSE"); NonTerminal FOR = new NonTerminal("FOR"); NonTerminal SWITCH = new NonTerminal("SWITCH"); NonTerminal LISTA_ACCIONES = new NonTerminal("LISTA_ACCIONES"); NonTerminal ACCION = new NonTerminal("ACCION"); NonTerminal IMPORT = new NonTerminal("IMPORT"); NonTerminal ENCABEZADO = new NonTerminal("ENCABEZADO"); NonTerminal TIPO_DATO = new NonTerminal("TIPO_DATO"); NonTerminal LISTA_VARS = new NonTerminal("LISTA_VARS"); NonTerminal EXPRESION_LOGICA = new NonTerminal("EXPRESION_LOGICA"); NonTerminal EXPRESION_RELACIONAL = new NonTerminal("EXPRESION_RELACIONAL"); NonTerminal EXPRESION = new NonTerminal("EXPRESION"); NonTerminal DECLARACION_ARREGLO = new NonTerminal("DECLARACION_ARREGLO"); NonTerminal ASIGNACION_ARREGLO = new NonTerminal("ASIGNACION_ARREGLO"); NonTerminal LISTA_DATOS = new NonTerminal("LISTA_DATOS"); NonTerminal ASIGNACION_POSICION = new NonTerminal("ASIGNACION_POSICION"); NonTerminal SENTENCIA = new NonTerminal("SENTENCIA"); NonTerminal LISTA_SENTENCIAS = new NonTerminal("LISTA_SENTENCIAS"); NonTerminal PROCEDIMIENTO = new NonTerminal("PROCEDIMIENTO"); NonTerminal LISTA_PARAMETROS = new NonTerminal("LISTA_PARAMETROS"); NonTerminal PARAMETRO = new NonTerminal("PARAMETRO"); NonTerminal FUNCION_PRINT = new NonTerminal("FUNCION_PRINT"); NonTerminal FUNCION_COMPARAR = new NonTerminal("FUNCION_COMPARAR"); NonTerminal RETORNO = new NonTerminal("RETORNO"); NonTerminal OBTENER_USUARIO = new NonTerminal("OBTENER_USUARIO"); NonTerminal OPERADOR_RELACIONAL = new NonTerminal("OPERADOR_RELACIONAL"); NonTerminal LLAMADA = new NonTerminal("LLAMADA"); NonTerminal DINCREMENTO = new NonTerminal("DINCREMENTO"); NonTerminal CASE = new NonTerminal("CASE"); NonTerminal DEFAULT = new NonTerminal("DEFAULT"); NonTerminal CUERPO_SWITCH = new NonTerminal("CUERPO_SWITCH"); NonTerminal LISTA_CASE = new NonTerminal("LISTA_CASE"); NonTerminal VALOR = new NonTerminal("VALOR"); NonTerminal OPCION_SENTENCIAS = new NonTerminal("OPCION_SENTENCIAS"); #endregion #region reglas gramaticales //Encabezado ENCABEZADO.Rule = MakePlusRule(ENCABEZADO, IMPORT) | IMPORT; IMPORT.Rule = importar + cad + finSentencia; // Cuerpo principal this.Root = INICIO; INICIO.Rule = ENCABEZADO + LISTA_ACCIONES | ENCABEZADO | LISTA_ACCIONES; LISTA_ACCIONES.Rule = MakePlusRule(LISTA_ACCIONES, ACCION) | ACCION; ACCION.Rule = DECLARACION | PROCEDIMIENTO | PRINCIPAL | ASIGNACION | DECLARACION_ARREGLO | ASIGNACION_POSICION | DINCREMENTO + finSentencia | FUNCION_PRINT + finSentencia; PRINCIPAL.Rule = principal + dosPuntos + vacio + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | principal + dosPuntos + TIPO_DATO + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | principal + dosPuntos + vacio + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | principal + dosPuntos + TIPO_DATO + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC; // Sintaxis de las Declaraciones TIPO_DATO.Rule = entero | doble | cadena | caracter | booleano; LISTA_VARS.Rule = MakePlusRule(LISTA_VARS, coma, identificador); DECLARACION.Rule = LISTA_VARS + dosPuntos + TIPO_DATO + asignacion + EXPRESION_LOGICA + finSentencia | identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION_LOGICA + finSentencia | LISTA_VARS + dosPuntos + TIPO_DATO + finSentencia | identificador + dosPuntos + TIPO_DATO + finSentencia; // Sintaxis de las Asignaciones ASIGNACION.Rule = identificador + asignacion + EXPRESION_LOGICA + finSentencia | identificador + asignacion + llaveA + LISTA_DATOS + llaveC + finSentencia; // Sintaxis de los arreglos DECLARACION_ARREGLO.Rule = identificador + dosPuntos + TIPO_DATO + corcheteA + EXPRESION + corcheteC + finSentencia | identificador + dosPuntos + TIPO_DATO + corcheteA + EXPRESION + corcheteC + asignacion + ASIGNACION_ARREGLO + finSentencia; LISTA_DATOS.Rule = MakePlusRule(LISTA_DATOS, coma, EXPRESION_LOGICA) | EXPRESION_LOGICA; ASIGNACION_ARREGLO.Rule = llaveA + LISTA_DATOS + llaveC | identificador; ASIGNACION_POSICION.Rule = identificador + corcheteA + EXPRESION + corcheteC + asignacion + EXPRESION_LOGICA + finSentencia; //Sintaxis de Metodos y Funciones PROCEDIMIENTO.Rule = identificador + dosPuntos + TIPO_DATO + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | identificador + dosPuntos + vacio + parentesisA + LISTA_PARAMETROS + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | identificador + dosPuntos + TIPO_DATO + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC | identificador + dosPuntos + vacio + parentesisA + parentesisC + llaveA + OPCION_SENTENCIAS + llaveC; PARAMETRO.Rule = identificador + dosPuntos + TIPO_DATO | identificador + dosPuntos + TIPO_DATO + corcheteA + corcheteC; LISTA_PARAMETROS.Rule = MakePlusRule(LISTA_PARAMETROS, coma, PARAMETRO) | PARAMETRO; LISTA_SENTENCIAS.Rule = MakePlusRule(LISTA_SENTENCIAS, SENTENCIA) | SENTENCIA; OPCION_SENTENCIAS.Rule = LISTA_SENTENCIAS | Empty; SENTENCIA.Rule = DECLARACION | ASIGNACION | DECLARACION_ARREGLO | ASIGNACION_POSICION | IF | FOR | SWITCH | WHILE | DO_WHILE | FUNCION_PRINT + finSentencia | DINCREMENTO + finSentencia | LLAMADA + finSentencia | quebrar + finSentencia | RETORNO; RETORNO.Rule = retornar + EXPRESION_LOGICA + finSentencia | retornar + finSentencia; //Funciones nativas FUNCION_PRINT.Rule = imprimir + parentesisA + EXPRESION_LOGICA + parentesisC; FUNCION_COMPARAR.Rule = punto + comparar + parentesisA + EXPRESION + parentesisC; OBTENER_USUARIO.Rule = obtenerUsuario + parentesisA + parentesisC; //If Else IF.Rule = si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC + ELSE | si + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC + ELSE; ELSE.Rule = sino + llaveA + LISTA_SENTENCIAS + llaveC | sino + llaveA + llaveC; //While WHILE.Rule = mientras + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC | mientras + parentesisA + EXPRESION_LOGICA + parentesisC + llaveA + llaveC; //Do While DO_WHILE.Rule = hacer + llaveA + LISTA_SENTENCIAS + llaveC + mientras + parentesisA + EXPRESION_LOGICA + parentesisC + finSentencia | hacer + llaveA + llaveC + mientras + parentesisA + EXPRESION_LOGICA + parentesisC + finSentencia; //For FOR.Rule = para + parentesisA + identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION + finSentencia + EXPRESION_LOGICA + finSentencia + DINCREMENTO + parentesisC + llaveA + LISTA_SENTENCIAS + llaveC | para + parentesisA + identificador + dosPuntos + TIPO_DATO + asignacion + EXPRESION + finSentencia + EXPRESION_LOGICA + finSentencia + DINCREMENTO + parentesisC + llaveA + llaveC; DINCREMENTO.Rule = identificador + incremento | identificador + decremento; //Switch SWITCH.Rule = cambiar + parentesisA + identificador + parentesisC + llaveA + CUERPO_SWITCH + llaveC; CUERPO_SWITCH.Rule = LISTA_CASE | LISTA_CASE + DEFAULT; LISTA_CASE.Rule = MakePlusRule(LISTA_CASE, CASE) | CASE; CASE.Rule = caso + VALOR + dosPuntos + LISTA_SENTENCIAS | caso + VALOR + dosPuntos; VALOR.Rule = cad | numero; DEFAULT.Rule = defecto + dosPuntos + LISTA_SENTENCIAS | defecto + dosPuntos; //Llamadas LLAMADA.Rule = identificador + parentesisA + parentesisC | identificador + parentesisA + LISTA_DATOS + parentesisC; // Expresiones EXPRESION_LOGICA.Rule = EXPRESION_LOGICA + and + EXPRESION_LOGICA | EXPRESION_LOGICA + or + EXPRESION_LOGICA | EXPRESION_LOGICA + xor + EXPRESION_LOGICA | not + EXPRESION_LOGICA | EXPRESION_RELACIONAL; EXPRESION_RELACIONAL.Rule = EXPRESION + OPERADOR_RELACIONAL + EXPRESION | EXPRESION; OPERADOR_RELACIONAL.Rule = menorQue | menorIgual | mayorQue | mayorIgual | equivalente | noEquivalente; EXPRESION.Rule = EXPRESION + sumar + EXPRESION | EXPRESION + restar + EXPRESION | EXPRESION + multiplicar + EXPRESION | EXPRESION + dividir + EXPRESION | EXPRESION + modular + EXPRESION | EXPRESION + elevar + EXPRESION | restar + EXPRESION | parentesisA + EXPRESION_LOGICA + parentesisC | identificador + corcheteA + EXPRESION + corcheteC | identificador | LLAMADA | OBTENER_USUARIO | verdadero | falso | cad | car | numero | identificador + FUNCION_COMPARAR | identificador + corcheteA + EXPRESION + corcheteC + FUNCION_COMPARAR; #endregion }
//TerminalSet _skipTokensInPreview = new TerminalSet(); //used in token preview for conflict resolution public ExpressionGrammar() { //this.GrammarComments = "NOTE: This grammar is just a demo, and it is a broken demo.\r\n" + // "Demonstrates token preview technique to help parser resolve conflicts.\r\n"; #region Lexical structure StringLiteral StringLiteral = TerminalFactory.CreateCSharpString("StringLiteral"); StringLiteral CharLiteral = TerminalFactory.CreateCSharpChar("CharLiteral"); NumberLiteral Number = TerminalFactory.CreateCSharpNumber("Number"); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //Temporarily, treat preprocessor instructions like comments CommentTerminal ppInstruction = new CommentTerminal("ppInstruction", "#", "\n"); NonGrammarTerminals.Add(ppInstruction); //Symbols Terminal colon = new Terminal(":"); //ToTerm(":", "colon"); Terminal semi = ToTerm(";"); //, "semi"); NonTerminal semi_opt = new NonTerminal("semi?"); semi_opt.Rule = Empty | semi; Terminal dot = ToTerm("."); //, "dot"); Terminal comma = ToTerm(","); //, "comma"); NonTerminal comma_opt = new NonTerminal("comma_opt", Empty | comma); NonTerminal commas_opt = new NonTerminal("commas_opt"); commas_opt.Rule = MakeStarRule(commas_opt, null, comma); Terminal qmark = ToTerm("?");//, "qmark"); NonTerminal qmark_opt = new NonTerminal("qmark_opt", Empty | qmark); Terminal Lbr = ToTerm("{"); Terminal Rbr = ToTerm("}"); Terminal Lpar = ToTerm("("); Terminal Rpar = ToTerm(")"); Terminal tgoto = ToTerm("goto"); Terminal yld = ToTerm("yield"); Terminal Lparx = ToTerm("(*"); #endregion #region NonTerminals //B.2.1. Basic concepts var qual_name_with_targs = new NonTerminal("qual_name_with_targs"); var base_type_list = new NonTerminal("base_type_list"); var generic_dimension_specifier = new NonTerminal("generic_dimension_specifier"); var qual_name_segment = new NonTerminal("qual_name_segment"); var qual_name_segments_opt = new NonTerminal("qual_name_segments_opt"); var type_or_void = new NonTerminal("type_or_void", "type or void"); var builtin_type = new NonTerminal("builtin_type", "built-in type"); var type_ref_list = new NonTerminal("type_ref_list"); var identifier_ext = new NonTerminal("identifier_ext"); var identifier_or_builtin = new NonTerminal("identifier_or_builtin"); //B.2.2. Types var type_ref = new NonTerminal("type_ref"); var type_argument_list = new NonTerminal("type_argument_list"); var typearg_or_gendimspec_list = new NonTerminal("typearg_or_gendimspec_list"); var type_argument_list_opt = new NonTerminal("type_argument_list_opt"); var integral_type = new NonTerminal("integral_type"); //B.2.4. Expressions var argument = new NonTerminal("argument"); var argument_list = new NonTerminal("argument_list"); var argument_list_opt = new NonTerminal("argument_list_opt"); var expression = new NonTerminal("expression", "expression"); var expression_list = new NonTerminal("expression_list"); var expression_opt = new NonTerminal("expression_opt"); var conditional_expression = new NonTerminal("conditional_expression"); var lambda_expression = new NonTerminal("lambda_expression"); var query_expression = new NonTerminal("query_expression"); var unary_operator = new NonTerminal("unary_operator"); var assignment_operator = new NonTerminal("assignment_operator"); var primary_expression = new NonTerminal("primary_expression"); var unary_expression = new NonTerminal("unary_expression"); var pre_incr_decr_expression = new NonTerminal("pre_incr_decr_expression"); var post_incr_decr_expression = new NonTerminal("post_incr_decr_expression"); var literal = new NonTerminal("literal"); var parenthesized_expression = new NonTerminal("parenthesized_expression"); var member_access = new NonTerminal("member_access"); var member_access_segment = new NonTerminal("member_access_segment"); var member_access_segments_opt = new NonTerminal("member_access_segments_opt"); var array_indexer = new NonTerminal("array_indexer"); var argument_list_par = new NonTerminal("argument_list_par"); var argument_list_par_opt = new NonTerminal("argument_list_par_opt"); var incr_or_decr = new NonTerminal("incr_or_decr"); var incr_or_decr_opt = new NonTerminal("incr_or_decr_opt"); var creation_args = new NonTerminal("creation_args"); var object_creation_expression = new NonTerminal("object_creation_expression"); var anonymous_object_creation_expression = new NonTerminal("anonymous_object_creation_expression"); var typeof_expression = new NonTerminal("typeof_expression"); var checked_expression = new NonTerminal("checked_expression"); var unchecked_expression = new NonTerminal("unchecked_expression"); var default_value_expression = new NonTerminal("default_value_expression"); //var anonymous_method_expression = new NonTerminal("anonymous_method_expression"); var elem_initializer = new NonTerminal("elem_initializer"); var elem_initializer_list = new NonTerminal("elem_initializer_list"); var elem_initializer_list_ext = new NonTerminal("elem_initializer_list_ext"); var initializer_value = new NonTerminal("initializer_value"); var anonymous_object_initializer = new NonTerminal("anonymous_object_initializer"); var member_declarator = new NonTerminal("member_declarator"); var member_declarator_list = new NonTerminal("member_declarator_list"); var unbound_type_name = new NonTerminal("unbound_type_name"); var generic_dimension_specifier_opt = new NonTerminal("generic_dimension_specifier_opt"); var bin_op_expression = new NonTerminal("bin_op_expression"); var typecast_expression = new NonTerminal("typecast_expression"); var bin_op = new NonTerminal("bin_op", "operator symbol"); //B.2.5. Statements var statement = new NonTerminal("statement", "statement"); var statement_list = new NonTerminal("statement_list"); var statement_list_opt = new NonTerminal("statement_list_opt"); var declaration_statement = new NonTerminal("declaration_statement"); var embedded_statement = new NonTerminal("embedded_statement"); var selection_statement = new NonTerminal("selection_statement"); var iteration_statement = new NonTerminal("iteration_statement"); var block = new NonTerminal("block"); var statement_expression = new NonTerminal("statement_expression"); var statement_expression_list = new NonTerminal("statement_expression_list"); var local_variable_declaration = new NonTerminal("local_variable_declaration"); //var local_constant_declaration = new NonTerminal("local_constant_declaration"); var local_variable_type = new NonTerminal("local_variable_type"); var local_variable_declarator = new NonTerminal("local_variable_declarator"); //var local_variable_declarators = new NonTerminal("local_variable_declarators"); var if_statement = new NonTerminal("if_statement"); var else_clause_opt = new NonTerminal("else_clause_opt"); var while_statement = new NonTerminal("while_statement"); var do_statement = new NonTerminal("do_statement"); var for_statement = new NonTerminal("for_statement"); var for_initializer_opt = new NonTerminal("for_initializer_opt"); var for_condition_opt = new NonTerminal("for_condition_opt"); var for_iterator_opt = new NonTerminal("for_iterator_opt"); var break_statement = new NonTerminal("break_statement"); var continue_statement = new NonTerminal("continue_statement"); var return_statement = new NonTerminal("return_statement"); var identifier_opt = new NonTerminal("identifier_opt"); var resource_acquisition = new NonTerminal("resource_acquisition"); //namespaces, compilation units var qualified_identifier = new NonTerminal("qualified_identifier"); var qualified_alias_member = new NonTerminal("qualified_alias_member"); //B.2.9. Arrays var rank_specifier = new NonTerminal("rank_specifier"); var rank_specifiers = new NonTerminal("rank_specifiers"); var rank_specifiers_opt = new NonTerminal("rank_specifiers_opt"); var dim_specifier = new NonTerminal("dim_specifier"); var dim_specifier_opt = new NonTerminal("dim_specifier_opt"); var list_initializer = new NonTerminal("array_initializer"); var list_initializer_opt = new NonTerminal("array_initializer_opt"); var new_opt = new NonTerminal("new_opt"); #endregion #region operators, punctuation and delimiters RegisterOperators(1, "||"); RegisterOperators(2, "&&"); RegisterOperators(3, "|"); RegisterOperators(4, "^"); RegisterOperators(5, "&"); RegisterOperators(6, "==", "!="); RegisterOperators(7, "<", ">", "<=", ">=", "is", "as"); RegisterOperators(8, "<<", ">>"); RegisterOperators(9, "+", "-"); RegisterOperators(10, "*", "/", "%"); RegisterOperators(-3, "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="); RegisterOperators(-2, "?"); RegisterOperators(-1, "??"); this.MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":"); //this.MarkTransient(/*namespace_member_declaration, member_declaration, type_declaration,*/ statement, embedded_statement, expression, // literal, bin_op, primary_expression, expression); //this.AddTermsReportGroup("assignment", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="); //this.AddTermsReportGroup("typename", "bool", "decimal", "float", "double", "string", "object", // "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char"); //this.AddTermsReportGroup("statement", "if", "switch", "do", "while", "for", "foreach", "continue", "goto", "return", "try", "yield", // "break", "throw", "unchecked", "using"); //this.AddTermsReportGroup("type declaration", "public", "private", "protected", "static", "internal", "sealed", "abstract", "partial", // "class", "struct", "delegate", "interface", "enum"); //this.AddTermsReportGroup("member declaration", "virtual", "override", "readonly", "volatile", "extern"); //this.AddTermsReportGroup("constant", Number, StringLiteral, CharLiteral); //this.AddTermsReportGroup("constant", "true", "false", "null"); //this.AddTermsReportGroup("unary operator", "+", "-", "!", "~"); //this.AddToNoReportGroup(comma, semi); //this.AddToNoReportGroup("var", "const", "new", "++", "--", "this", "base", "checked", "lock", "typeof", "default", // "{", "}", "["); // #endregion #region "<" conflict resolution //var gen_lt = new NonTerminal("gen_lt"); //gen_lt.Rule = CustomActionHere(this.ResolveLessThanConflict) + "<"; #endregion // RULES //B.2.1. Basic concepts //qual_name_with_targs is an alias for namespace-name, namespace-or-type-name, type-name, generic_dimension_specifier.Rule = /*gen_lt +*/ commas_opt + ">"; qual_name_segments_opt.Rule = MakeStarRule(qual_name_segments_opt, null, qual_name_segment); identifier_or_builtin.Rule = identifier | builtin_type; identifier_ext.Rule = identifier_or_builtin | "this" | "base"; qual_name_segment.Rule = dot + identifier | "::" + identifier | type_argument_list; //generic_dimension_specifier.Rule = lt + commas_opt + ">"; generic_dimension_specifier.Rule = /*gen_lt +*/ commas_opt + ">"; qual_name_with_targs.Rule = identifier_or_builtin + qual_name_segments_opt; type_argument_list.Rule = /*gen_lt +*/ type_ref_list + ">"; type_argument_list_opt.Rule = Empty | type_argument_list; typearg_or_gendimspec_list.Rule = type_argument_list | generic_dimension_specifier_opt; //B.2.2. Types type_or_void.Rule = /*qual_name_with_targs |*/ "void"; builtin_type.Rule = integral_type | "bool" | "decimal" | "float" | "double" | "string" | "object"; type_ref.Rule = type_or_void + qmark_opt + rank_specifiers_opt + typearg_or_gendimspec_list; type_ref_list.Rule = MakePlusRule(type_ref_list, comma, type_ref); var comma_list_opt = new NonTerminal("comma_list_opt"); comma_list_opt.Rule = MakeStarRule(comma_list_opt, null, comma); rank_specifier.Rule = "[" + comma_list_opt + "]"; rank_specifiers.Rule = MakePlusRule(rank_specifiers, null, rank_specifier); rank_specifiers_opt.Rule = rank_specifiers.Q(); integral_type.Rule = ToTerm("sbyte") | "byte" | "short" | "ushort" | "int" | "uint" | "long" | "ulong" | "char"; //B.2.4. Expressions argument.Rule = expression | "ref" + identifier | "out" + identifier; argument_list.Rule = MakePlusRule(argument_list, comma, argument); argument_list_opt.Rule = Empty | argument_list; expression.Rule = conditional_expression | bin_op_expression | typecast_expression | primary_expression; expression_opt.Rule = Empty | expression; expression_list.Rule = MakePlusRule(expression_list, comma, expression); unary_operator.Rule = ToTerm("+") | "-" | "!" | "~" | "*"; assignment_operator.Rule = ToTerm("=") | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="; conditional_expression.Rule = expression /*+ PreferShiftHere()*/ + qmark + expression + colon + expression;// + ReduceThis(); bin_op_expression.Rule = expression + bin_op + expression; typecast_expression.Rule = parenthesized_expression + primary_expression; primary_expression.Rule = literal | unary_expression | parenthesized_expression | member_access | pre_incr_decr_expression | post_incr_decr_expression | object_creation_expression | anonymous_object_creation_expression | typeof_expression | checked_expression | unchecked_expression | default_value_expression /*| anonymous_method_expression*/; unary_expression.Rule = unary_operator + primary_expression; dim_specifier.Rule = "[" + expression_list + "]"; dim_specifier_opt.Rule = dim_specifier.Q(); literal.Rule = Number | StringLiteral | CharLiteral | "true" | "false" | "null"; parenthesized_expression.Rule = Lpar + expression + Rpar; pre_incr_decr_expression.Rule = incr_or_decr + member_access; post_incr_decr_expression.Rule = member_access + incr_or_decr; //joined invocation_expr and member_access; for member access left the most general variant member_access.Rule = identifier_ext + member_access_segments_opt; member_access_segments_opt.Rule = MakeStarRule(member_access_segments_opt, null, member_access_segment); member_access_segment.Rule = dot + identifier | array_indexer | argument_list_par | type_argument_list; array_indexer.Rule = "[" + expression_list + "]"; argument_list_par.Rule = Lpar + argument_list_opt + Rpar; argument_list_par_opt.Rule = Empty | argument_list_par; list_initializer.Rule = Lbr + elem_initializer_list_ext + Rbr; list_initializer_opt.Rule = list_initializer.Q(); elem_initializer.Rule = initializer_value | identifier + "=" + initializer_value; elem_initializer_list.Rule = MakePlusRule(elem_initializer_list, comma, elem_initializer); elem_initializer_list_ext.Rule = Empty | elem_initializer_list + comma_opt; initializer_value.Rule = expression | list_initializer; //delegate, anon-object, object object_creation_expression.Rule = "new" + qual_name_with_targs + qmark_opt + creation_args + list_initializer_opt; creation_args.Rule = dim_specifier | rank_specifier | argument_list_par; anonymous_object_creation_expression.Rule = "new" + anonymous_object_initializer; anonymous_object_initializer.Rule = Lbr + Rbr | Lbr + member_declarator_list + comma_opt + Rbr; member_declarator.Rule = expression | identifier + "=" + expression; member_declarator_list.Rule = MakePlusRule(member_declarator_list, comma, member_declarator); //typeof typeof_expression.Rule = "typeof" + Lpar + type_ref + Rpar; generic_dimension_specifier_opt.Rule = Empty /*| gen_lt*/ + commas_opt + ">"; //checked, unchecked checked_expression.Rule = "checked" + parenthesized_expression; unchecked_expression.Rule = "unchecked" + parenthesized_expression; //default-value default_value_expression.Rule = "default" + Lpar + type_ref + Rpar; bin_op.Rule = ToTerm("<") | "||" | "&&" | "|" | "^" | "&" | "==" | "!=" | ">" | "<=" | ">=" | "<<" | ">>" | "+" | "-" | "*" | "/" | "%" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "is" | "as" | "??"; //Queries query_expression.Rule = "from"; //B.2.5. Statements statement.Rule = /*labeled_statement |*/ declaration_statement | embedded_statement; statement.ErrorRule = SyntaxError + semi; //skip all until semicolon statement_list.Rule = MakePlusRule(statement_list, null, statement); statement_list_opt.Rule = Empty | statement_list; declaration_statement.Rule = local_variable_declaration + semi /*| local_constant_declaration*/ + semi; local_variable_declaration.Rule = local_variable_type /*+ local_variable_declarators*/; local_variable_type.Rule = member_access | "var"; // | builtin_type; //to fix the conflict, changing to member-access here local_variable_declarator.Rule = identifier | identifier + "=" + initializer_value; //local_variable_declarators.Rule = MakePlusRule(local_variable_declarators, comma, local_variable_declarator); //local_constant_declaration.Rule = "const" + type_ref /*+ constant_declarators*/; //embedded_statement embedded_statement.Rule = block | semi /*empty_statement*/ | statement_expression + semi | selection_statement | iteration_statement /* | jump_statement | try_statement | checked_statement | unchecked_statement | lock_statement | using_statement | yield_statement*/; block.Rule = Lbr + statement_list_opt + Rbr; //selection (if and switch) selection_statement.Rule = if_statement /*| switch_statement*/; if_statement.Rule = ToTerm("if") + Lpar + expression + Rpar + embedded_statement + else_clause_opt; else_clause_opt.Rule = Empty /*| PreferShiftHere()*/ + "else" + embedded_statement; iteration_statement.Rule = while_statement | do_statement | for_statement /*| foreach_statement*/; while_statement.Rule = "while" + parenthesized_expression + embedded_statement; do_statement.Rule = "do" + embedded_statement + "while" + parenthesized_expression + semi; for_statement.Rule = "for" + Lpar + for_initializer_opt + semi + for_condition_opt + semi + for_iterator_opt + Rpar + embedded_statement; for_initializer_opt.Rule = Empty | local_variable_declaration | statement_expression_list; for_condition_opt.Rule = Empty | expression; for_iterator_opt.Rule = Empty | statement_expression_list; break_statement.Rule = "break" + semi; continue_statement.Rule = "continue" + semi; return_statement.Rule = "return" + expression_opt + semi; identifier_opt.Rule = Empty | identifier; resource_acquisition.Rule = local_variable_declaration | expression; statement_expression.Rule = object_creation_expression | member_access | member_access + assignment_operator + expression | pre_incr_decr_expression | post_incr_decr_expression ; statement_expression_list.Rule = MakePlusRule(statement_expression_list, comma, statement_expression); incr_or_decr_opt.Rule = Empty | ToTerm("++") | "--"; incr_or_decr.Rule = ToTerm("++") | "--"; //B.2.6. Namespaces this.Root = block; qualified_identifier.Rule = MakePlusRule(qualified_identifier, dot, identifier); base_type_list.Rule = MakePlusRule(base_type_list, comma, qual_name_with_targs); new_opt.Rule = Empty | "new"; //_skipTokensInPreview.UnionWith(new Terminal[] { dot, identifier, comma, ToTerm("::"), comma, ToTerm("["), ToTerm("]") }); }
///-------------------------------------------------------------------------------- /// <summary>The default constructor sets up the overall grammar.</summary> /// /// <param name="solution">The solution containing model structure to add to the grammar.</param> ///-------------------------------------------------------------------------------- public CodeTemplateContentGrammar(Solution solution) { bool isFirstItem = true; this.LanguageFlags |= LanguageFlags.CreateAst; this.GrammarComments = "This grammar is used to parse the CONTENT section of an M+ code template."; #region "Literals, Symbols, Operators, Punctuation, etc." // literals StringLiteral StringLiteral = TerminalFactory.CreateCSharpString("StringLiteral"); NumberLiteral Number = TerminalFactory.CreateCSharpNumber("Number"); Number.Options |= NumberOptions.AllowSign; IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); // symbols KeyTerm textOpen = ToTerm(LanguageTerms.TextOpenTag); KeyTerm evalOpen = ToTerm(LanguageTerms.EvalOpenTag); KeyTerm outputOpen = ToTerm(LanguageTerms.OutputOpenTag); KeyTerm propOpen = ToTerm(LanguageTerms.PropOpenTag); KeyTerm close = ToTerm(LanguageTerms.CloseTag); KeyTerm dot = ToTerm("."); KeyTerm comma = ToTerm(","); KeyTerm Lbr = ToTerm("{"); KeyTerm Rbr = ToTerm("}"); KeyTerm Lpar = ToTerm("("); KeyTerm Rpar = ToTerm(")"); KeyTerm slash = ToTerm("/"); // operators RegisterOperators(1, "||"); RegisterOperators(2, "&&"); RegisterOperators(3, "==", "!="); RegisterOperators(4, "<", ">", "<=", ">="); RegisterOperators(5, "."); RegisterOperators(6, "+", "-", "*", "/"); // delimiters and punctuation this.Delimiters = "{}[](),:;+-*/%&|^!~<>="; this.MarkPunctuation("=", ";", ",", "(", ")", "{", "}", ".", LanguageTerms.ProgressTerm, LanguageTerms.TraceTerm, LanguageTerms.DebugTerm, LanguageTerms.WhileTerm, LanguageTerms.VarTerm, LanguageTerms.ParamTerm, LanguageTerms.IfTerm, LanguageTerms.ElseTerm, LanguageTerms.WithTerm, LanguageTerms.ForeachTerm, LanguageTerms.BreakTerm, LanguageTerms.ContinueTerm, LanguageTerms.ClearTerm, LanguageTerms.ReturnTerm, LanguageTerms.SwitchTerm, LanguageTerms.CaseTerm, LanguageTerms.DefaultTerm, LanguageTerms.WhereTerm, LanguageTerms.InTerm, LanguageTerms.LimitTerm, LanguageTerms.SortTerm, LanguageTerms.FromTerm, LanguageTerms.TextOpenTag, LanguageTerms.EvalOpenTag, LanguageTerms.OutputOpenTag, LanguageTerms.PropOpenTag, LanguageTerms.CloseTag); // whitespace and line terminators this.LineTerminators = "\r\n\u2085\u2028\u2029"; this.WhitespaceChars = " \t\r\n\v\u2085\u2028\u2029"; // comments CommentTerminal singleLineComment = new CommentTerminal("singleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal delimitedComment = new CommentTerminal("delimitedComment", "/*", "*/"); TextTerminal templateText = new TextTerminal("templateText", "<%%-", "%%>"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(delimitedComment); #endregion #region "Nodes" // high level nodes var template = new NonTerminal("template", typeof(TemplateNode)); var templateBlock = new NonTerminal("templateBlock"); // statements var statementList = new NonTerminal("statementList", typeof(StatementListNode)); var statement = new NonTerminal("statement"); var ifStatement = new NonTerminal("ifStatement", typeof(IfStatementNode)); var switchStatement = new NonTerminal("switchStatement", typeof(SwitchStatementNode)); var foreachStatement = new NonTerminal("foreachStatement", typeof(ForeachStatementNode)); var whileStatement = new NonTerminal("whileStatement", typeof(WhileStatementNode)); var withStatement = new NonTerminal("withStatement", typeof(WithStatementNode)); var breakStatement = new NonTerminal("breakStatement", typeof(BreakStatementNode)); var clearStatement = new NonTerminal("clearStatement", typeof(ClearTextStatementNode)); var returnStatement = new NonTerminal("returnStatement", typeof(ReturnStatementNode)); var continueStatement = new NonTerminal("continueStatement", typeof(ContinueStatementNode)); var currentItemAssignmentStatement = new NonTerminal("currentItemAssignmentStatement", typeof(CurrentItemAssignmentStatementNode)); var templatePropertyAssignmentStatement = new NonTerminal("templatePropertyAssignmentStatement", typeof(TemplatePropertyAssignmentStatementNode)); var debugStatement = new NonTerminal("debugStatement", typeof(DebugStatementNode)); var traceStatement = new NonTerminal("traceStatement", typeof(TraceStatementNode)); var logStatement = new NonTerminal("logStatement", typeof(LogStatementNode)); var progressStatement = new NonTerminal("progressStatement", typeof(ProgressStatementNode)); var varStatement = new NonTerminal("varStatement", typeof(VarStatementNode)); var paramStatement = new NonTerminal("paramStatement", typeof(ParamStatementNode)); var assignmentStatement = new NonTerminal("assignmentStatement", typeof(AssignmentStatementNode)); // clauses var elseClause = new NonTerminal("elseClause", typeof(ElseClauseNode)); var elseIfList = new NonTerminal("elseIfList", typeof(ElseIfListNode)); var elseIfClause = new NonTerminal("elseIfClause", typeof(ElseIfClauseNode)); var caseList = new NonTerminal("caseList", typeof(CaseListNode)); var caseClause = new NonTerminal("caseClause", typeof(CaseClauseNode)); var defaultClause = new NonTerminal("defaultClause", typeof(DefaultClauseNode)); var caseConditionList = new NonTerminal("caseConditionList", typeof(CaseConditionListNode)); var caseCondition = new NonTerminal("caseCondition", typeof(CaseConditionNode)); var foreachClause = new NonTerminal("foreachClause", typeof(ForeachClauseNode)); var whereClause = new NonTerminal("whereClause", typeof(WhereClauseNode)); var inClause = new NonTerminal("inClause", typeof(InClauseNode)); var limitClause = new NonTerminal("limitClause", typeof(LimitClauseNode)); var sortClause = new NonTerminal("sortClause", typeof(SortClauseNode)); var sortDirectionClause = new NonTerminal("sortDirectionClause", typeof(SortDirectionClauseNode)); var fromClause = new NonTerminal("fromClause", typeof(FromClauseNode)); var templateParameterList = new NonTerminal("templateParameterList", typeof(TemplateParameterListNode)); var templateParameter = new NonTerminal("templateParameter", typeof(TemplateParameterNode)); // expressions var expression = new NonTerminal("expression", typeof(ExpressionNode)); var binOp = new NonTerminal("binOp", "operator symbol", typeof(BinaryOperatorNode)); var mathOp = new NonTerminal("mathOp", "operator symbol", typeof(MathOperatorNode)); var literal = new NonTerminal("literal", typeof(LiteralNode)); var popContext = new NonTerminal("popContext", typeof(PopContextNode)); var thisContext = new NonTerminal("thisContext", typeof(ThisContextNode)); // properties var property = new NonTerminal("property"); var contentProperty = new NonTerminal("contentProperty"); var templateProperty = new NonTerminal("templateProperty", typeof(TemplatePropertyNode)); var inClauseItem = new NonTerminal("inClauseItem", typeof(InClauselItemNode)); var modelContext = new NonTerminal("modelContext", typeof(ModelContextNode)); var currentItem = new NonTerminal("currentItem", typeof(CurrentItemNode)); var modelProperty = new NonTerminal("modelProperty", typeof(ModelPropertyNode)); var assignableProperty = new NonTerminal("assignableProperty", typeof(AssignablePropertyNode)); var configurationProperty = new NonTerminal("configurationProperty", typeof(ConfigurationPropertyNode)); var contextHelper = new NonTerminal("contextHelper", typeof(ContextHelperNode)); var collectionHelper = new NonTerminal("collectionHelper", typeof(CollectionHelperNode)); var parameter = new NonTerminal("parameter", typeof(ParameterNode)); #endregion #region "Rules" // a template consists of any number of template blocks template.Rule = MakeStarRule(template, null, templateBlock); // a template block is a property or an evaluation (a statement list surrounded by eval tags) templateBlock.Rule = property | evalOpen + statementList + close; // a statement list consists of any number of statements statementList.Rule = MakeStarRule(statementList, null, statement); // a statement can be an if, switch, foreach, with, or a property statement.Rule = ifStatement | switchStatement | foreachStatement | whileStatement | withStatement | breakStatement | continueStatement | clearStatement | returnStatement | currentItemAssignmentStatement | templatePropertyAssignmentStatement | traceStatement | logStatement | varStatement | paramStatement | assignmentStatement | property | progressStatement; // var statement varStatement.Rule = ToTerm(LanguageTerms.VarTerm) + identifier | ToTerm(LanguageTerms.VarTerm) + identifier + "=" + parameter; // param statement paramStatement.Rule = ToTerm(LanguageTerms.ParamTerm) + identifier; // assignment statement assignmentStatement.Rule = identifier + "=" + parameter; // if statement ifStatement.Rule = ToTerm(LanguageTerms.IfTerm) + Lpar + expression + Rpar + Lbr + statementList + Rbr + elseIfList + elseClause; elseIfList.Rule = MakeStarRule(elseIfList, null, elseIfClause); elseIfClause.Rule = ToTerm(LanguageTerms.ElseTerm) + LanguageTerms.IfTerm + Lpar + expression + Rpar + Lbr + statementList + Rbr; elseClause.Rule = Empty | ToTerm(LanguageTerms.ElseTerm) + Lbr + statementList + Rbr; // break and return statements, etc. breakStatement.Rule = ToTerm(LanguageTerms.BreakTerm); continueStatement.Rule = ToTerm(LanguageTerms.ContinueTerm); clearStatement.Rule = ToTerm(LanguageTerms.ClearTerm); returnStatement.Rule = ToTerm(LanguageTerms.ReturnTerm); popContext.Rule = dot + dot + slash; thisContext.Rule = ToTerm(LanguageTerms.ThisTerm); // switch statement switchStatement.Rule = ToTerm(LanguageTerms.SwitchTerm) + Lpar + modelProperty + Rpar + Lbr + caseList + defaultClause + Rbr; caseList.Rule = MakePlusRule(caseList, null, caseClause); caseClause.Rule = caseConditionList + statementList + breakStatement; defaultClause.Rule = Empty | ToTerm(LanguageTerms.DefaultTerm) + ":" + statementList; caseConditionList.Rule = MakePlusRule(caseConditionList, null, caseCondition); caseCondition.Rule = ToTerm(LanguageTerms.CaseTerm) + literal + ":"; // a foreach statement consists of a foreach keyword, followed by a model context, // optionally followed by a where clause, and includes a set of statements // or, a foreach statement consists of a Record item foreachStatement.Rule = ToTerm(LanguageTerms.ForeachTerm) + Lpar + foreachClause + Rpar + Lbr + statementList + Rbr; foreachClause.Rule = modelContext + inClause + whereClause + limitClause + sortClause | ToTerm(LanguageTerms.RecordItem) + limitClause; inClause.Rule = Empty | ToTerm(LanguageTerms.InTerm) + inClauseItem; whereClause.Rule = Empty | ToTerm(LanguageTerms.WhereTerm) + expression; limitClause.Rule = Empty | ToTerm(LanguageTerms.LimitTerm) + Number; sortClause.Rule = Empty | ToTerm(LanguageTerms.SortTerm) + modelProperty + sortDirectionClause; sortDirectionClause.Rule = Empty | ToTerm(LanguageTerms.AscTerm) | ToTerm(LanguageTerms.DescTerm); // a while statement consists of a while keyword, followed by an expression, // and includes a set of statements whileStatement.Rule = ToTerm(LanguageTerms.WhileTerm) + Lpar + expression + Rpar + Lbr + statementList + Rbr; // current item assignment statement currentItemAssignmentStatement.Rule = currentItem + "=" + modelContext | currentItem + "=" + "null"; // template property assignment statement templatePropertyAssignmentStatement.Rule = ToTerm(LanguageTerms.TextProperty) + "=" + parameter; // debug statement debugStatement.Rule = ToTerm(LanguageTerms.DebugTerm) + Lpar + parameter + Rpar | ToTerm(LanguageTerms.DebugTerm) + Lpar + parameter + comma + parameter + Rpar; // trace statement traceStatement.Rule = ToTerm(LanguageTerms.TraceTerm) + Lpar + parameter + Rpar | ToTerm(LanguageTerms.TraceTerm) + Lpar + parameter + comma + parameter + Rpar; // log statement logStatement.Rule = ToTerm(LanguageTerms.LogTerm) + Lpar + parameter + comma + parameter + comma + parameter + Rpar; // a with statement consists of a with keyword, followed by a model context, // and includes a set of statements withStatement.Rule = ToTerm(LanguageTerms.WithTerm) + Lpar + modelContext + fromClause + Rpar + Lbr + statementList + Rbr | LanguageTerms.WithTerm + Lpar + currentItem + Rpar + Lbr + statementList + Rbr; fromClause.Rule = Empty | ToTerm(LanguageTerms.FromTerm) + contextHelper; // progress statement progressStatement.Rule = ToTerm(LanguageTerms.ProgressTerm) | LanguageTerms.ProgressTerm + Lpar + parameter + Rpar; // a context helper is one of the specifically supported internal methods to set model context contextHelper.Rule = modelContext + dot + LanguageTerms.FindMethod + Lpar + modelProperty + comma + parameter + Rpar | modelContext + dot + LanguageTerms.FindMethod + Lpar + parameter + Rpar | currentItem + dot + LanguageTerms.FindMethod + Lpar + modelProperty + comma + parameter + Rpar | currentItem + dot + LanguageTerms.FindMethod + Lpar + parameter + Rpar; // a property is a content property or an output property property.Rule = contentProperty | templateText; // a content property can be a template property, model property, or configuration property (template property is lowest precedence) contentProperty.Rule = propOpen + configurationProperty + close | propOpen + parameter + close; // a parameter is a model property or string literal parameter.Rule = modelProperty | literal | parameter + mathOp + parameter; // an in clause item is a collection from a model context, current item, or a special collection inClauseItem.Rule = modelContext | currentItem | collectionHelper; // a collection helper gets specialized collections collectionHelper.Rule = modelContext + dot + LanguageTerms.FindAllMethod + Lpar + modelProperty + comma + parameter + Rpar | currentItem + dot + LanguageTerms.FindAllMethod + Lpar + modelProperty + comma + parameter + Rpar | ToTerm(LanguageTerms.GetEntityAndBasesCollection) | ToTerm(LanguageTerms.GetBaseAndEntitiesCollection) | ToTerm(LanguageTerms.ExtendingEntitiesCollection) | ToTerm(LanguageTerms.PathRelationships); // a current item node is a valid name of a type of node in the model that can be assigned to isFirstItem = true; // add all CurrentItemTypeCode enums to currentItem rule foreach (string key in GrammarHelper.CurrentItemTypes.AllKeys) { if (isFirstItem == true) { currentItem.Rule = ToTerm(key); isFirstItem = false; } else { currentItem.Rule = currentItem.Rule | ToTerm(key); } } // add all ModelObject instances in model to currentItem rule if (solution != null) { foreach (string key in solution.ModelObjectNames.AllKeys) { currentItem.Rule = currentItem.Rule | ToTerm("Current" + key); } } // add all ModelObjectProperty instances in model to currentItem rule if (solution != null) { foreach (string key in solution.ModelObjectPropertyNames.AllKeys) { currentItem.Rule = currentItem.Rule | ToTerm("Current" + key); } } // a model context node is a valid name of a type of node in the model or a pop context directive modelContext.Rule = popContext | popContext + modelContext | thisContext | thisContext + dot + modelContext; // add all ModelContextTypeCode enums to modelContext rule foreach (string key in GrammarHelper.ModelContextTypes.AllKeys) { modelContext.Rule = modelContext.Rule | ToTerm(key); } // add all OtherModelContextTypeCode enums to modelContext rule foreach (string key in GrammarHelper.OtherModelContextTypes.AllKeys) { modelContext.Rule = modelContext.Rule | ToTerm(key); } // add all ModelObject instances in model to modelContext rule if (solution != null) { foreach (string key in solution.ModelObjectNames.AllKeys) { modelContext.Rule = modelContext.Rule | ToTerm(key); } } // add all ModelObjectProperty instances in model to assignableProperty rule if (solution != null) { foreach (string key in solution.ModelObjectPropertyNames.AllKeys) { modelContext.Rule = modelContext.Rule | ToTerm(key); } } // an assignable property is a model property that can have values assigned to it isFirstItem = true; // add all AssignablePropertyCode enums to assignableProperty rule foreach (string key in GrammarHelper.AssignableProperties.AllKeys) { if (isFirstItem == true) { assignableProperty.Rule = ToTerm(key); isFirstItem = false; } else { assignableProperty.Rule = assignableProperty.Rule | ToTerm(key); } } // add all ModelProperty instances in model to assignableProperty rule if (solution != null) { foreach (string key in solution.ModelPropertyNames.AllKeys) { assignableProperty.Rule = assignableProperty.Rule | ToTerm(key); } } // a model property is a valid property name of a node in the model (can refer to other nodes with the dot notation) modelProperty.Rule = assignableProperty | ToTerm(LanguageTerms.ItemIndexProperty) | ToTerm(LanguageTerms.TextProperty) | ToTerm(LanguageTerms.PathProperty) //| ToTerm(LanguageTerms.LibraryDirectoryProperty) | ToTerm(LanguageTerms.IsRelatedToProperty) | modelContext + dot + modelProperty | currentItem + dot + modelProperty | templateProperty | popContext + modelProperty | thisContext + dot + modelProperty | ToTerm(LanguageTerms.ColumnMethod) + Lpar + parameter + Rpar | ToTerm(LanguageTerms.FileMethod) + Lpar + parameter + Rpar | ToTerm(LanguageTerms.FileExistsMethod) + Lpar + parameter + Rpar | ToTerm(LanguageTerms.LogMethod) + Lpar + parameter + comma + parameter + Rpar | ToTerm(LanguageTerms.HasPropertyNamed) + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringStartsWith + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringEndsWith + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringContains + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringRegexReplace + Lpar + parameter + comma + parameter + Rpar | modelProperty + dot + LanguageTerms.StringRegexIsMatch + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringCamelCase + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringCapitalCase + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringCapitalWordCase + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringUnderscoreCase + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringToLower + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringToUpper + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringTrim + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringTrimStart + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringTrimEnd + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringReplace + Lpar + parameter + comma + parameter + Rpar | modelProperty + dot + LanguageTerms.StringFilter + Lpar + parameter + comma + parameter + Rpar | modelProperty + dot + LanguageTerms.StringFilterProtected + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringFilterIgnored + Lpar + Rpar | modelProperty + dot + LanguageTerms.StringSubstring + Lpar + parameter + comma + parameter + Rpar | modelProperty + dot + LanguageTerms.StringSubstring + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringIndexOf + Lpar + parameter + Rpar | modelProperty + dot + LanguageTerms.StringLength; // add all ReadOnlyPropertyCode enums to modelProperty rule foreach (string key in GrammarHelper.ReadOnlyProperties.AllKeys) { modelProperty.Rule = modelProperty.Rule | ToTerm(key); } // a configuration property is one of the specfically supported internal methods to process model data configurationProperty.Rule = ToTerm(LanguageTerms.TabMethod) + Number | ToTerm(LanguageTerms.UseTabsMethod) + "true" | ToTerm(LanguageTerms.UseTabsMethod) + "false" | ToTerm(LanguageTerms.TabStringMethod) + StringLiteral | ToTerm(LanguageTerms.UseProtectedAreasMethod) + "true" | ToTerm(LanguageTerms.UseProtectedAreasMethod) + "false" | ToTerm(LanguageTerms.ProtectedAreaStartMethod) + StringLiteral | ToTerm(LanguageTerms.ProtectedAreaEndMethod) + StringLiteral | ToTerm(LanguageTerms.UseIgnoredAreasMethod) + "true" | ToTerm(LanguageTerms.UseIgnoredAreasMethod) + "false" | ToTerm(LanguageTerms.IgnoredAreaStartMethod) + StringLiteral | ToTerm(LanguageTerms.IgnoredAreaEndMethod) + StringLiteral | ToTerm(LanguageTerms.UserMethod) | ToTerm(LanguageTerms.NowMethod); // a template property from the parser perspective is just an identifier, the interpreter will resolve template references templateProperty.Rule = identifier | identifier + Lpar + templateParameterList + Rpar; // a template parameter list consists of any number of template parameters delimited by commas templateParameterList.Rule = MakeStarRule(templateParameterList, comma, templateParameter); // template parameter templateParameter.Rule = identifier + "=" + parameter; // an expression can be a hierarchy of expressions with binary operators, model properties, and literals expression.Rule = literal | modelProperty | modelContext | currentItem | expression + binOp + expression | expression + mathOp + expression | Lpar + expression + Rpar; // a literal can be a number, string, character, true, false, or null literal.Rule = Number | StringLiteral | "true" | "false" | "null"; // binary operator binOp.Rule = ToTerm("||") | "&&" | "==" | "!=" | "<" | ">" | "<=" | ">="; // math operator mathOp.Rule = ToTerm("+") | "-" | "*" | "/"; #endregion // the template is the root of the grammar this.Root = template; // mark nodes to filter from the parse tree this.MarkTransient(statement, templateBlock, property, contentProperty); }
public Gramatica() : base(caseSensitive: true) { #region ER var numero = TerminalFactory.CreateCSharpNumber("numero"); IdentifierTerminal id = new IdentifierTerminal("id"); StringLiteral cadena = TerminalFactory.CreateCSharpString("cadena"); var caracter = TerminalFactory.CreateCSharpChar("caracter"); #endregion #region Terminales /* OPERADORES ARITMETICOS */ var mas = ToTerm("+"); var menos = ToTerm("-"); var por = ToTerm("*"); var div = ToTerm("/"); /* OPERADORES COMPARAR */ var igual = ToTerm("=="); var menor = ToTerm("<"); var mayor = ToTerm(">"); var menor_igual = ToTerm("<="); var mayor_igual = ToTerm(">="); var diferente = ToTerm("!="); /* OPERADORES LOGICOS * var or = ToTerm("||"); * var and = ToTerm("&&"); * var not = ToTerm("!"); * var nand = ToTerm("!&&"); * var nor = ToTerm("!||"); * var xor = ToTerm("|&"); */ /* TIPOS DE DATOS */ var tipo_cadena = ToTerm("cadena"); var tipo_caracter = ToTerm("caracter"); var tipo_entero = ToTerm("entero"); var tipo_doble = ToTerm("doble"); var tipo_bool = ToTerm("boolean"); /* SENTENCIAS DE CONTROL */ var sentencia_si = ToTerm("si"); var sentencia_sino = ToTerm("sino"); var sentencia_para = ToTerm("para"); var sentencia_mientras = ToTerm("mientras"); var sentencia_hacer = ToTerm("hacer"); #endregion #region No Terminales NonTerminal S = new NonTerminal("S"), PROGRAMA = new NonTerminal("PROGRAMA"), SENTENCIA = new NonTerminal("SENTENCIA"), CONDICION = new NonTerminal("CONDICION"), INICIO_PARA = new NonTerminal("INICIO PARA"), FIN_PARA = new NonTerminal("FIN PARA"), SI = new NonTerminal("SI"), SINO = new NonTerminal("SINO"), PARA = new NonTerminal("PARA"), MIENTRAS = new NonTerminal("MIENTRAS"), HACER = new NonTerminal("HACER"), L_ID = new NonTerminal("LST ID"), ASIGNACION = new NonTerminal("ASIGNACION"), COMPARACION = new NonTerminal("COMPARACION"), DECLARACION = new NonTerminal("DECLARAR"), COMPARAR = new NonTerminal("COMPARAR"), TIPO = new NonTerminal("TIPO"), E = new NonTerminal("E"); #endregion #region Gramatica S.Rule = PROGRAMA; PROGRAMA.Rule = MakePlusRule(PROGRAMA, SENTENCIA); SENTENCIA.Rule = SI | PARA | MIENTRAS | HACER | ASIGNACION; /* * si ( CONDICION ) ¿ SENTENCIA ? sino ¿ SENTENCIA ? * para ( INICIO_PARA ; FIN_PARA; CONDICION) ¿ SENTENCIA ? * mientras ( CONDICION ) ¿ SENTENCIA ? * hacer ¿ SENTENCIA ? mientras ( CONDICION ) $ */ SI.Rule = sentencia_si + ToTerm("(") + COMPARACION + ToTerm(")") + ToTerm("¿") + SENTENCIA + ToTerm("?") + sentencia_sino + ToTerm("¿") + SENTENCIA + ToTerm("?"); PARA.Rule = sentencia_para + ToTerm("(") + ASIGNACION + ToTerm(";") + COMPARACION + ToTerm(";") + COMPARACION + ToTerm(")") + ToTerm("¿") + SENTENCIA + ToTerm("?"); MIENTRAS.Rule = sentencia_mientras + ToTerm("(") + COMPARACION + ToTerm(")") + ToTerm("¿") + SENTENCIA + ToTerm("?"); HACER.Rule = sentencia_hacer + ToTerm("¿") + SENTENCIA + ToTerm("?") + sentencia_mientras + ToTerm("(") + COMPARACION + ToTerm(")") + ToTerm("$"); /* * CONDICION -> COMPARACION * INICIO_PARA -> ASIGNACION * FIN_PARA -> COMPARACION */ ASIGNACION.Rule = DECLARACION + ToTerm("=") + E + ToTerm("$"); DECLARACION.Rule = TIPO + id; COMPARACION.Rule = E + COMPARAR + E; TIPO.Rule = tipo_cadena | tipo_caracter | tipo_doble | tipo_entero | tipo_bool; COMPARAR.Rule = igual | menor | mayor | menor_igual | mayor_igual | diferente; E.Rule = E + mas + E | E + menos + E | E + por + E | E + div + E | ToTerm("(") + E + ToTerm(")") | numero | id | cadena | caracter; #endregion #region Preferencias this.Root = S; this.RegisterOperators(20, Associativity.Left, mas, menos); this.RegisterOperators(30, Associativity.Left, por, div); this.MarkPunctuation("(", ")", ",", ";", "=", "¿", "?", "$"); this.MarkTransient(S, SENTENCIA, TIPO); #endregion }
public Language() : base(false) { CommentTerminal LINE_COMMENT = new CommentTerminal("LINE_COMMENT", ">>", "\n", "\r\n"); CommentTerminal BLOCK_COMMENT = new CommentTerminal("BLOCK_COMMENT", "<-", "->"); NonGrammarTerminals.Add(BLOCK_COMMENT); NonGrammarTerminals.Add(LINE_COMMENT); ////----------------------------------Terminals with precedence KeyTerm increase = ToTerm("++"); KeyTerm decrease = ToTerm("--"); KeyTerm plus = ToTerm("+"); KeyTerm minus = ToTerm("-"); KeyTerm by = ToTerm("*"); KeyTerm divided = ToTerm("/"); KeyTerm power = ToTerm("^"); KeyTerm lessThan = ToTerm("<"); KeyTerm greaterThan = ToTerm(">"); KeyTerm lessThanEqual = ToTerm("<="); KeyTerm greaterThanEqual = ToTerm(">="); KeyTerm doubleEqual = ToTerm("=="); KeyTerm different = ToTerm("!="); KeyTerm not = ToTerm("!"); KeyTerm and = ToTerm("&&"); KeyTerm or = ToTerm("||"); ////----------------------------------precedence this.RegisterOperators(1, Associativity.Left, or); this.RegisterOperators(2, Associativity.Left, and); this.RegisterOperators(3, Associativity.Left, not); this.RegisterOperators(4, Associativity.Left, doubleEqual, different, lessThan, lessThanEqual, greaterThan, greaterThanEqual); this.RegisterOperators(5, Associativity.Left, plus, minus); this.RegisterOperators(6, Associativity.Left, by, divided); this.RegisterOperators(7, Associativity.Left, power); //Regex var integer = new RegexBasedTerminal("int", "[0-9]+"); var tdouble = TerminalFactory.CreateCSharpNumber("double"); var String = TerminalFactory.CreateCSharpString("string"); var caracter = TerminalFactory.CreateCSharpChar("char"); var boolean = new RegexBasedTerminal("bool", "(true)|(false)"); var iden = TerminalFactory.CreateCSharpIdentifier("id"); var hexa = new RegexBasedTerminal("hexa", "^(\\#)[0-9A-F]+$"); //Non terminals var START = new NonTerminal("START"); var BODY = new NonTerminal("BODY"); var DECLARATION = new NonTerminal("DECLARATION"); var DECLARATION2 = new NonTerminal("DECLARATION2"); var ASSIGNATION = new NonTerminal("ASSIGNATION"); var ASSIGN2 = new NonTerminal("ASSIGN2"); var INDEX = new NonTerminal("INDEX"); var DATATYPE = new NonTerminal("DATATYPE"); var OBJECT = new NonTerminal("OBJECT"); var ASSIGN = new NonTerminal("ASSIGN"); var ARRAY = new NonTerminal("ARRAY"); var ARRAY2 = new NonTerminal("ARRAY2"); var ARRAYASIGN = new NonTerminal("ARRAYASIGN"); var ARRAYASIGN2 = new NonTerminal("ARRAYASIGN2"); var ARRAYASIGN3 = new NonTerminal("ARRAYASIGN3"); var ARRAYLIST = new NonTerminal("ARRAYLIST"); var NATIVE = new NonTerminal("NATIVE"); var PRINT = new NonTerminal("PRINT"); var SHOW = new NonTerminal("SHOW"); var IF = new NonTerminal("IF"); var ELSE = new NonTerminal("ELSE"); var FOR = new NonTerminal("FOR"); var REPEAT = new NonTerminal("REPEAT"); var WHILE = new NonTerminal("WHILE"); var VARMANAGMENT = new NonTerminal("VARMANAGMENT"); var UPDATE = new NonTerminal("UPDATE"); var ESINGLE = new NonTerminal("ESINGLE"); var E = new NonTerminal("E"); var ID = new NonTerminal("ID"); var IDPLUS = new NonTerminal("IDPLUS"); var ARRAYS = new NonTerminal("ARRAYS"); var DOWHILE = new NonTerminal("DOWHILE"); var SWITCH = new NonTerminal("SWITCH"); var CASE = new NonTerminal("CASE"); var DEFAULT = new NonTerminal("DEFAULT"); var CASELIST = new NonTerminal("CASELIST"); var FUNCTION = new NonTerminal("FUNCTION"); var FUNCTIONARGS = new NonTerminal("FUNCTIONARGS"); var VISIBILITY = new NonTerminal("VISIBILITY"); var OVERRIDE = new NonTerminal("OVERRIDE"); var PARAMLIST = new NonTerminal("PARAMLIST"); var PARAM = new NonTerminal("PARAM"); var OPTIONAL = new NonTerminal("OPTIONAL"); var RETURN = new NonTerminal("RETURN"); var RETOPTION = new NonTerminal("RETOPTION"); var LISTMETHODS = new NonTerminal("LISTMETHODS"); var CLASS = new NonTerminal("CLASS"); var EXTENDS = new NonTerminal("EXTENDS"); var EXTENDSLIST = new NonTerminal("EXTENDSLIST"); var CALLFUNC = new NonTerminal("CALLFUNC"); var ADDFIGURE = new NonTerminal("ADDFIGURE"); var GEOMETRICAS = new NonTerminal("GEOMETRICAS"); var COLOR = new NonTerminal("COLOR"); var FIGURE = new NonTerminal("FIGURE"); var MAIN = new NonTerminal("MAIN"); var CLASSIMPLEMENTATION = new NonTerminal("CLASSIMPLEMENTATION"); var CFUNCLIST = new NonTerminal("CFUNCLIST"); var LISTCLASSMETHODS = new NonTerminal("LISTCLASSMETHODS"); var LISTCLASSMETHODS2 = new NonTerminal("LISTCLASSMETHODS2"); var LISTOBJECTS = new NonTerminal("LISTCLASSMETHODS2"); ////----------------------------------Innecesary nodes this.MarkPunctuation(".", "(", ")", "{", "}", "[", "]", ";", "=", ",", "importar", "if", "for", "repeat", "mientras", "show", "hacer", "comprobar", "salir", "caso", ":", "print", "defecto", "clase", "addfigure", "main", "return"); this.MarkTransient(DECLARATION2, LISTCLASSMETHODS2, CLASSIMPLEMENTATION, BODY, ASSIGN2, COLOR, ARRAY2, ARRAYASIGN, ARRAYASIGN2, ARRAYASIGN3, NATIVE, VARMANAGMENT, ESINGLE, ASSIGN, ARRAY, ADDFIGURE, RETOPTION); //----------------------------------Grammar START.Rule = MakePlusRule(START, CLASS); CLASS.Rule = "clase" + iden + EXTENDSLIST + "{" + CLASSIMPLEMENTATION + "}"; CLASS.ErrorRule = SyntaxError + "}"; CLASS.ErrorRule = SyntaxError + ";"; CLASSIMPLEMENTATION.Rule = MakeStarRule(CLASSIMPLEMENTATION, LISTCLASSMETHODS); EXTENDSLIST.Rule = MakeStarRule(EXTENDSLIST, ToTerm(","), EXTENDS); EXTENDS.Rule = ToTerm("importar") + ID; LISTMETHODS.Rule = MakePlusRule(LISTMETHODS, BODY); BODY.Rule = ID + ";" | FIGURE | ADDFIGURE | DECLARATION | ASSIGNATION | UPDATE + ";" | PRINT | SHOW | IF | FOR | REPEAT | WHILE | DOWHILE | SWITCH | OPTIONAL + ";" | Empty | CALLFUNC; //methods inside a function DECLARATION.Rule = DATATYPE + DECLARATION2 + ";"; DECLARATION.ErrorRule = SyntaxError + ";"; DECLARATION2.Rule = LISTOBJECTS | ToTerm("array") + ARRAYS; LISTOBJECTS.Rule = MakePlusRule(LISTOBJECTS, ToTerm(","), OBJECT); ARRAYS.Rule = ID + ARRAY; ASSIGN.Rule = ToTerm("=") + E | Empty; ASSIGNATION.Rule = ID + ASSIGN2 + ";"; ASSIGNATION.ErrorRule = SyntaxError + ";"; ASSIGN2.Rule = ToTerm("=") + E | "[" + E + "]" + ASSIGN2; PRINT.Rule = ToTerm("print") + "(" + E + ")" + ";"; PRINT.ErrorRule = SyntaxError + ";"; SHOW.Rule = ToTerm("show") + "(" + E + "," + E + ")" + ";"; SHOW.ErrorRule = SyntaxError + ";"; IF.Rule = ToTerm("if") + "(" + E + ")" + "{" + LISTMETHODS + "}" + ELSE; IF.ErrorRule = SyntaxError + "}"; IF.ErrorRule = SyntaxError + ";"; ELSE.Rule = ToTerm("else") + IF | ToTerm("else") + "{" + LISTMETHODS + "}" | Empty; FOR.Rule = ToTerm("for") + "(" + VARMANAGMENT + E + ";" + UPDATE + ")" + "{" + LISTMETHODS + "}"; FOR.ErrorRule = SyntaxError + "}"; FOR.ErrorRule = SyntaxError + ";"; REPEAT.Rule = ToTerm("repeat") + "(" + E + ")" + "{" + LISTMETHODS + "}"; REPEAT.ErrorRule = SyntaxError + "}"; REPEAT.ErrorRule = SyntaxError + ";"; VARMANAGMENT.Rule = DECLARATION | ASSIGNATION; UPDATE.Rule = ESINGLE + increase | ESINGLE + decrease; WHILE.Rule = ToTerm("mientras") + "(" + E + ")" + "{" + LISTMETHODS + "}"; WHILE.ErrorRule = SyntaxError + "}"; WHILE.ErrorRule = SyntaxError + ";"; DOWHILE.Rule = ToTerm("hacer") + "{" + LISTMETHODS + "}" + ToTerm("mientras") + "(" + E + ")" + ";"; DOWHILE.ErrorRule = SyntaxError + "}"; DOWHILE.ErrorRule = SyntaxError + ";"; SWITCH.Rule = ToTerm("comprobar") + "(" + E + ")" + "{" + CASELIST + DEFAULT + "}"; SWITCH.ErrorRule = SyntaxError + "}"; SWITCH.ErrorRule = SyntaxError + ";"; CASELIST.Rule = MakePlusRule(CASELIST, CASE); CASE.Rule = ToTerm("caso") + E + ":" + LISTMETHODS + ToTerm("salir") + ";"; DEFAULT.Rule = ToTerm("defecto") + ":" + LISTMETHODS + ToTerm("salir") + ";" | Empty; OPTIONAL.Rule = RETURN | ToTerm("continue"); RETURN.Rule = ToTerm("return") + RETOPTION; RETOPTION.Rule = Empty | E; CALLFUNC.Rule = iden + "(" + CFUNCLIST + ")" + ";"; CFUNCLIST.Rule = MakeStarRule(CFUNCLIST, ToTerm(","), E); CALLFUNC.ErrorRule = SyntaxError + ";"; ADDFIGURE.Rule = ToTerm("addfigure") + "(" + GEOMETRICAS + ")" + ";"; GEOMETRICAS.Rule = ToTerm("circle") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + ")" | ToTerm("triangle") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + "," + E + "," + E + ")" | ToTerm("square") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + ")" | ToTerm("line") + "(" + COLOR + "," + E + "," + E + "," + E + "," + E + "," + E + ")"; GEOMETRICAS.ErrorRule = SyntaxError + ";"; COLOR.Rule = Empty | E; //it can be a string or id FIGURE.Rule = ToTerm("figure") + "(" + E + ")" + ";"; //Methods inside a class LISTCLASSMETHODS.Rule = VISIBILITY + LISTCLASSMETHODS2 | MAIN; LISTCLASSMETHODS2.Rule = DECLARATION | FUNCTION; MAIN.Rule = ToTerm("main") + "(" + ")" + "{" + LISTMETHODS + "}"; FUNCTION.Rule = iden + FUNCTIONARGS + "(" + PARAMLIST + ")" + "{" + LISTMETHODS + "}"; FUNCTION.ErrorRule = SyntaxError + "}"; FUNCTION.ErrorRule = SyntaxError + ";"; FUNCTIONARGS.Rule = DATATYPE + OVERRIDE | ToTerm("array") + DATATYPE + INDEX + OVERRIDE | ToTerm("void"); VISIBILITY.Rule = Empty | ToTerm("publico") | ToTerm("privado"); OVERRIDE.Rule = Empty | ToTerm("override"); PARAMLIST.Rule = MakeStarRule(PARAMLIST, ToTerm(","), PARAM); PARAM.Rule = iden + iden | DATATYPE + iden; //datatypes DATATYPE.Rule = ToTerm("int") | "bool" | "string" | "double" | "char" | iden; OBJECT.Rule = ID + ASSIGN; //Making arrays ARRAY.Rule = "=" + ARRAYASIGN | Empty; ARRAYASIGN.Rule = ToTerm("{") + ARRAYASIGN2 + "}"; ARRAYASIGN2.Rule = ARRAYASIGN3 | ARRAYLIST; ARRAYASIGN3.Rule = ARRAYASIGN | MakePlusRule(ARRAYASIGN3, ToTerm(","), ARRAYASIGN); ARRAYLIST.Rule = MakePlusRule(ARRAYLIST, ToTerm(","), E); //Making EXP E.Rule = E + plus + E | E + minus + E | E + by + E | E + divided + E | E + power + E | E + doubleEqual + E | E + different + E | E + lessThan + E | E + greaterThan + E | E + lessThanEqual + E | E + greaterThanEqual + E | E + or + E | E + and + E | not + E | ESINGLE | ToTerm("(") + E + ")" | minus + E; ESINGLE.Rule = NATIVE | ID | ToTerm("new") + iden + "(" + CFUNCLIST + ")"; INDEX.Rule = INDEX + ToTerm("[") + E + "]" | Empty; ID.Rule = iden + IDPLUS; IDPLUS.Rule = INDEX | Empty | "(" + CFUNCLIST + ")" | "." + ID; NATIVE.Rule = integer | caracter | String | boolean | tdouble; this.Root = START; }
public CeciliaGrammar() { #region Lexical rules // keywords var BoolKeyword = new KeyTerm("bool", "bool"); var CharKeyword = new KeyTerm("char", "char"); var StringKeyword = new KeyTerm("string", "string"); var ObjectKeyword = new KeyTerm("object", "object"); var ByteKeyword = new KeyTerm("byte", "byte"); var ShortKeyword = new KeyTerm("short", "short"); var IntKeyword = new KeyTerm("int", "int"); var LongKeyword = new KeyTerm("long", "long"); var UbyteKeyword = new KeyTerm("ubyte", "ubyte"); var UShortKeyword = new KeyTerm("ushort", "short"); var UIntKeyword = new KeyTerm("uint", "int"); var ULongKeyword = new KeyTerm("ulong", "long"); var HalfKeyword = new KeyTerm("half", "half"); var FloatKeyword = new KeyTerm("float", "float"); var DoubleKeyword = new KeyTerm("double", "double"); var DecimalKeyword = new KeyTerm("decimal", "decimal"); var NamespaceKeyword = new KeyTerm("namespace", "namespace"); var PublicKeyword = new KeyTerm("public", "public"); var PrivateKeyword = new KeyTerm("private", "private"); var InternalKeyword = new KeyTerm("internal", "internal"); var UsingKeyword = new KeyTerm("using", "using"); var VarKeyword = new KeyTerm("var", "var"); var ConstKeyword = new KeyTerm("const", "const"); var SwitchKeyword = new KeyTerm("switch", "switch"); var LoopKeyword = new KeyTerm("loop", "loop"); var MacroKeyword = new KeyTerm("macro", "macro"); var TrueKeyword = new KeyTerm("true", "true"); var FalseKeyword = new KeyTerm("false", "false"); var DefaultKeyword = new KeyTerm("default", "default"); var ReturnKeyword = new KeyTerm("return", "return"); //symbols var LParen = ToTerm("("); var RParen = ToTerm(")"); var LBracket = ToTerm("["); var RBracket = ToTerm("]"); var LBrace = ToTerm("{"); var RBrace = ToTerm("}"); var Exclamation = ToTerm("!"); var Dollar = ToTerm("$"); var Percent = ToTerm("%"); var Caret = ToTerm("^"); var Ampersand = ToTerm("&"); var Asterisk = ToTerm("*"); var Minus = ToTerm("-"); var Plus = ToTerm("+"); var Equals = ToTerm("="); var Bar = ToTerm("|"); var Backslash = ToTerm("\\"); var Colon = ToTerm(":"); var SemiColon = ToTerm(";"); var DoubleQuote = ToTerm("\""); var SingleQuote = ToTerm("\'"); var LessThan = ToTerm("<"); var GreaterThan = ToTerm(">"); var Comma = ToTerm(","); var Dot = ToTerm("."); var Question = ToTerm("?"); var Hash = ToTerm("#"); var Slash = ToTerm("/"); var BarBar = ToTerm("||"); var AmpAmp = ToTerm("&&"); var MinusMinus = ToTerm("--"); var PlusPlus = ToTerm("++"); var QuestionQuestion = ToTerm("??"); var EqualsEquals = ToTerm("=="); var ExclamationEquals = ToTerm("!="); var Arrow = ToTerm("=>"); var LessThanEqual = ToTerm("<="); var GreaterThanEqual = ToTerm(">="); var LessThanLessThan = ToTerm("<<"); var GreaterThanGreaterThan = ToTerm(">>"); var PlusEqual = ToTerm("+="); var MinusEqual = ToTerm("-="); var AsteriskEqual = ToTerm("*="); var SlashEqual = ToTerm("/="); var BarEqual = ToTerm("|="); var CaretEqual = ToTerm("^="); var LessThanLessThanEqual = ToTerm("<<="); var GreaterThanGreaterThanEqual = ToTerm(">>="); var SemicolonOpt = new NonTerminal("semicolonOpt"); SemicolonOpt.Rule = SemiColon.Q(); var Identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); var NumberLiteral = TerminalFactory.CreateCSharpNumber("NumberLiteral"); var StringLiteral = TerminalFactory.CreateCSharpString("string_literal"); var SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n"); NonGrammarTerminals.Add(SingleLineComment); #endregion #region non terminals // program and namespace var Program = new NonTerminal("program"); var UsingDirectives = new NonTerminal("using_directives"); var UsingDirective = new NonTerminal("using_directive"); var QualifiedIdentifier = new NonTerminal("qualified_identifier"); var NamespaceMemberDeclarations = new NonTerminal("namespace_member_declarations"); var NamespaceMemberDeclaration = new NonTerminal("namespace_member_declaration"); var NamespaceDeclaration = new NonTerminal("namespace_declaration"); var NamespaceDeclarations = new NonTerminal("namespace_declarations"); // member declaration var TypeDeclaration = new NonTerminal("type_declaration"); var AllMemberModifiers = new NonTerminal("all_member_modifiers"); var AllMemberModifier = new NonTerminal("all_member_modifier"); var MemberDeclaration = new NonTerminal("member_declaration"); var ConstantDeclaration = new NonTerminal("constant_declaration"); var VariableDeclaration = new NonTerminal("variable_declaration"); var MacroDeclaration = new NonTerminal("macro_declaration"); var VariableDeclarators = new NonTerminal("variable_declarators"); var VariableDeclarator = new NonTerminal("variable_declarator"); var TypeAnnotation = new NonTerminal("type_annotation"); var TypeAnnotationOpt = new NonTerminal("type_annotationOpt"); // types var Type = new NonTerminal("type"); var EmbeddedType = new NonTerminal("embedded_type"); var NumberType = new NonTerminal("number_type"); var IntegralNumberType = new NonTerminal("integral_number_type"); var FloatingNumberType = new NonTerminal("floating_number_type"); var OtherBaseType = new NonTerminal("other_base_type"); var SpecialSupportType = new NonTerminal("special_support_type"); var UserDefinitionType = new NonTerminal("user_definition_type"); // expression var Expression = new NonTerminal("expression"); var ConditionalExpression = new NonTerminal("conditional_expression"); var ConditionalExpressionBody = new NonTerminal("conditional_expression_body"); var BinOpExpression = new NonTerminal("bin_op_expression"); var BinOp = new NonTerminal("bin_op"); var AssignmentExpression = new NonTerminal("assignment_expression"); var UnaryExpression = new NonTerminal("unary_expression"); var UnaryOperator = new NonTerminal("unary_operator"); var PrimaryExpression = new NonTerminal("primary_expression"); var AssignmentOperator = new NonTerminal("assignment_operator"); // loop expression var LoopExpression = new NonTerminal("loop_expression"); var LoopCondition = new NonTerminal("loop_condition"); // return expression var ReturnExpression = new NonTerminal("return_expression"); // switch expression var SwitchExpression = new NonTerminal("switch_expression"); var SwitchSection = new NonTerminal("switch_section"); var SwitchLabel = new NonTerminal("switch_label"); // function expression var FunctionExpression = new NonTerminal("function_expression"); var FunctionSignature = new NonTerminal("function_signature"); var FunctionParameterList = new NonTerminal("function_parameter_list"); var FunctionParameter = new NonTerminal("function_parameter"); var FunctionBody = new NonTerminal("function_body"); var Block = new NonTerminal("block"); var ExpressonList = new NonTerminal("expression_list"); var ExpressionListOpt = new NonTerminal("expression_listOpt"); // member access var IndexBracket = new NonTerminal("index_bracket"); var IndexBracketOpt = new NonTerminal("index_bracketOpt"); IndexBracketOpt.Rule = MakeStarRule(IndexBracketOpt, IndexBracket); var MemberAccess = new NonTerminal("member_access"); var MemberAccessSegmentsOpt = new NonTerminal("member_access_segmentsOpt"); var MemberAccessSegment = new NonTerminal("member_access_segment"); // literal var Literal = new NonTerminal("literal"); var BooleanLiteral = new NonTerminal("boolean_literal"); #endregion #region operators punctuation delimiter RegisterOperators(1, BarBar); RegisterOperators(2, AmpAmp); RegisterOperators(3, Bar); RegisterOperators(4, Caret); RegisterOperators(5, Ampersand); RegisterOperators(6, EqualsEquals, ExclamationEquals); RegisterOperators(7, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual); RegisterOperators(8, GreaterThanGreaterThan, LessThanLessThan); RegisterOperators(9, Plus, Minus); RegisterOperators(10, Asterisk, Slash, Percent); RegisterOperators(-1, QuestionQuestion); RegisterOperators(-2, Question); RegisterOperators(-3, Equals, PlusEqual, MinusEqual, AsteriskEqual, SlashEqual, BarEqual, CaretEqual, GreaterThanGreaterThanEqual, LessThanLessThanEqual); MarkPunctuation(";", ",", "(", ")", "{", "}", "[", "]", ":"); MarkTransient(NamespaceMemberDeclaration, MemberDeclaration, Literal, BinOp, PrimaryExpression); AddTermsReportGroup("assignment", Equals, PlusEqual, MinusEqual, AsteriskEqual, SlashEqual, SlashEqual, BarEqual, CaretEqual, GreaterThanGreaterThanEqual, LessThanLessThanEqual); AddTermsReportGroup("unary operator", Plus, Minus, Exclamation); AddToNoReportGroup(Comma, SemiColon); AddToNoReportGroup(VarKeyword, ConstKeyword, PlusPlus, MinusMinus, LBrace, RBrace); #endregion #region Syntax rules // program and namespace Program.Rule = UsingDirectives + NamespaceDeclarations; UsingDirectives.Rule = MakeStarRule(UsingDirectives, null, UsingDirective); UsingDirective.Rule = UsingKeyword + QualifiedIdentifier + SemicolonOpt; QualifiedIdentifier.Rule = MakeStarRule(QualifiedIdentifier, Dot, Identifier); NamespaceDeclaration.Rule = NamespaceKeyword + QualifiedIdentifier + Block + SemicolonOpt; NamespaceDeclarations.Rule = MakeStarRule(NamespaceDeclarations, null, NamespaceDeclaration); NamespaceMemberDeclarations.Rule = MakeStarRule(NamespaceMemberDeclarations, NamespaceMemberDeclaration); NamespaceMemberDeclaration.Rule = NamespaceDeclaration | TypeDeclaration; Block.Rule = LBrace + UsingDirectives + NamespaceMemberDeclarations + RBrace; // member declaration TypeDeclaration.Rule = AllMemberModifiers + MemberDeclaration; AllMemberModifiers.Rule = MakeStarRule(AllMemberModifiers, AllMemberModifier); AllMemberModifier.Rule = PublicKeyword | PrivateKeyword | InternalKeyword; MemberDeclaration.Rule = ConstantDeclaration | VariableDeclaration | MacroDeclaration; ConstantDeclaration.Rule = ConstKeyword + VariableDeclarators; VariableDeclaration.Rule = VarKeyword + VariableDeclarators; MacroDeclaration.Rule = MacroKeyword + VariableDeclarators; VariableDeclarators.Rule = MakePlusRule(VariableDeclarators, Comma, VariableDeclarator); VariableDeclarator.Rule = Identifier + TypeAnnotationOpt + Equals + Expression + SemicolonOpt; TypeAnnotation.Rule = Colon + Type; TypeAnnotationOpt.Rule = TypeAnnotation.Q(); // types Type.Rule = EmbeddedType | UserDefinitionType; EmbeddedType.Rule = NumberType | OtherBaseType | SpecialSupportType; NumberType.Rule = IntegralNumberType | FloatingNumberType | DecimalKeyword; IntegralNumberType.Rule = ByteKeyword | UbyteKeyword | ShortKeyword | UShortKeyword | IntKeyword | UIntKeyword | LongKeyword | ULongKeyword; FloatingNumberType.Rule = HalfKeyword | FloatKeyword | DoubleKeyword; OtherBaseType.Rule = BoolKeyword | CharKeyword; SpecialSupportType.Rule = StringKeyword | ObjectKeyword; UserDefinitionType.Rule = QualifiedIdentifier; #region expressions Expression.Rule = FunctionExpression | BinOpExpression | PrimaryExpression /*| AssignmentExpression | SwitchExpression | LoopExpression | ReturnExpression*/ | ConditionalExpression; ConditionalExpression.Rule = Expression + ConditionalExpressionBody; ConditionalExpressionBody.Rule = PreferShiftHere() + Question + Expression + Colon + Expression; // bin op expression BinOpExpression.Rule = Expression + BinOp + Expression; BinOp.Rule = BarBar | AmpAmp | Bar | Caret | Ampersand | EqualsEquals | ExclamationEquals | GreaterThan | LessThan | GreaterThanEqual | LessThanEqual | GreaterThanGreaterThan | Plus | Minus | Asterisk | Slash | Percent | Equals | PlusEqual | MinusEqual | AsteriskEqual | SlashEqual | BarEqual | CaretEqual | GreaterThanGreaterThanEqual | LessThanLessThanEqual | QuestionQuestion; // primary expresson PrimaryExpression.Rule = Literal | UnaryExpression | MemberAccess; // literal Literal.Rule = NumberLiteral | StringLiteral | TrueKeyword | FalseKeyword; UnaryExpression.Rule = UnaryOperator + PrimaryExpression; UnaryOperator.Rule = Plus | Minus | Exclamation | Asterisk; MemberAccess.Rule = Identifier + MemberAccessSegmentsOpt; MemberAccessSegmentsOpt.Rule = MakeStarRule(MemberAccessSegmentsOpt, MemberAccessSegment); MemberAccessSegment.Rule = Dot + Identifier; // function expression FunctionExpression.Rule = FunctionSignature + Arrow + FunctionBody; FunctionSignature.Rule = LParen + FunctionParameterList + RParen | Identifier; FunctionParameterList.Rule = MakeStarRule(FunctionParameterList, Comma, FunctionParameter); FunctionParameter.Rule = Identifier + TypeAnnotationOpt; FunctionBody.Rule = Expression | Block; ExpressionListOpt.Rule = ExpressonList.Q(); ExpressonList.Rule = MakePlusRule(ExpressonList, Expression); #endregion #endregion Root = Program; }
public TuringGrammarBroken() { //Expr -> n | v | Expr BinOp Expr | UnOP Expr | ( Expr ) //BinOp -> + | - | * | / | ** //UnOp -> - //ExprLine -> Expr EOF MarkReservedWords("not="); //1. Terminals Terminal num = new NumberLiteral("number"); Terminal iden = new IdentifierTerminal("identifier"); Terminal stringLiteral = TerminalFactory.CreateCSharpString("stringLiteral"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "%", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); NonGrammarTerminals.Add(DelimitedComment); //2. Non-Terminals var expandedIdentifier = new NonTerminal("expandedIndentifier"); var Expr = new NonTerminal("expr"); var BinOp = new NonTerminal("binOp", "operator"); var BinExpr = new NonTerminal("binExpr"); var unOp = new NonTerminal("unOp"); var unExpr = new NonTerminal("unExpr"); var ParExpr = new NonTerminal("parExpr"); var Statement = new NonTerminal("statement"); var Program = new NonTerminal("program"); var setEqual = new NonTerminal("setEqual"); var varType = new NonTerminal("varType"); var variableDeclaration = new NonTerminal("variableDeclaration"); var varOrConst = new NonTerminal("varOrConst"); var idenList = new NonTerminal("identifierList"); var assignment = new NonTerminal("assignment"); var typeSpecifier = new NonTerminal("typeSpecifier"); var ifBlock = new NonTerminal("ifBlock"); var elseIfBlock = new NonTerminal("elseIfBlock"); var optElseBlock = new NonTerminal("optElseBlock"); var caseBlock = new NonTerminal("caseBlock"); var labelBlock = new NonTerminal("labelBlock"); var functionCall = new NonTerminal("functionCall"); var optArgs = new NonTerminal("optArgs"); var args = new NonTerminal("args"); var functionDefinition = new NonTerminal("functionDefinition"); var optParams = new NonTerminal("optParams"); var parameters = new NonTerminal("parameters"); var parameter = new NonTerminal("parameter"); var io = new NonTerminal("io"); var optSameLine = new NonTerminal("optionalSameLine"); var loop = new NonTerminal("loop"); var forLoop = new NonTerminal("forLoop"); var exitLoop = new NonTerminal("exitLoop"); var and = new NonTerminal("and"); var or = new NonTerminal("or"); var not = new NonTerminal("not"); var result = new NonTerminal("result"); var recordList = new NonTerminal("recordList"); var type = new NonTerminal("type"); var memberCall = new NonTerminal("memberCall"); var range = new NonTerminal("range"); var boolean = new NonTerminal("boolean"); var ioArgs = new NonTerminal("ioArgs"); var newer = new NonTerminal("new"); //3. BNF rules varType.Rule = ToTerm("int") | "nat" | "string" | "real" | "boolean" | "array" + range + "of" + varType | ToTerm("flexible") + "array" + range + "of" + varType | "record" + recordList + "end" + "record" | "int1" | "int2" | "int4" | "real1" | "real2" | "real4" | "nat1" | "nat2" | "nat4" | ToTerm("char") + "(" + num + ")" | ToTerm("string") + "(" + num + ")" | iden; range.Rule = Expr + ".." + Expr; setEqual.Rule = ToTerm(":=") + Expr; typeSpecifier.Rule = ToTerm(":") + varType; Expr.Rule = num | iden | BinExpr | ParExpr | stringLiteral | unExpr | functionCall | memberCall | boolean; BinOp.Rule = ToTerm("-") | "*" | "/" | "**" | "+" | "div" | "mod" | and | or | "=" | ">" | "<" | ">=" | "<=" | "~=" | "not="; BinOp.Precedence = 1; unOp.Rule = not | "-"; unOp.Precedence = 2; BinExpr.Rule = Expr + BinOp + Expr; unExpr.Rule = unOp + Expr; ParExpr.Rule = "(" + Expr + ")"; boolean.Rule = ToTerm("true") | "false"; assignment.Rule = expandedIdentifier + setEqual; optArgs.Rule = args | Empty; args.Rule = MakePlusRule(args, ToTerm(","), Expr); //args.Rule = Expr + "," + args | Expr; functionCall.Rule = iden + "(" + optArgs + ")"; optSameLine.Rule = ToTerm("..") | Empty; io.Rule = ToTerm("put") + args + optSameLine | ToTerm("get") + args | ToTerm("put") + ":" + args + optSameLine | ToTerm("get") + ":" + args | ToTerm("open") + ":" + iden + "," + Expr + "," + ioArgs; ioArgs.Rule = ToTerm("get") | "put" | "write" | "read" | "seek" | "tell" | ioArgs + "," + ioArgs; newer.Rule = ToTerm("new") + iden + "," + Expr; optParams.Rule = ToTerm("(") + parameters + ")" | ToTerm("(") + ")" | Empty; parameters.Rule = parameter + "," + parameters | parameter; parameter.Rule = idenList + typeSpecifier | "var" + idenList + typeSpecifier; functionDefinition.Rule = "function" + iden + optParams + typeSpecifier + Program + "end" + iden | "fcn" + iden + optParams + typeSpecifier + Program + "end" + iden | "procedure" + iden + optParams + Program + "end" + iden | "proc" + iden + optParams + Program + "end" + iden; ifBlock.Rule = ToTerm("if") + Expr + ToTerm("then") + Program + elseIfBlock + optElseBlock + ToTerm("end") + "if"; elseIfBlock.Rule = ToTerm("elsif") + Expr + ToTerm("then") + Program + elseIfBlock | Empty; optElseBlock.Rule = ToTerm("else") + Program | Empty; caseBlock.Rule = ToTerm("case") + iden + "of" + labelBlock + "end case"; labelBlock.Rule = ToTerm("label") + Expr + ":" + Program + labelBlock | ToTerm("label") + ":" + labelBlock | Empty; idenList.Rule = iden + "," + idenList | iden; varOrConst.Rule = ToTerm("var") | "const"; variableDeclaration.Rule = varOrConst + idenList | varOrConst + idenList + setEqual | varOrConst + idenList + typeSpecifier | varOrConst + idenList + typeSpecifier + setEqual; loop.Rule = "loop" + Program + "end" + "loop"; forLoop.Rule = "for" + ("decreasing" | Empty) + iden + ":" + (range | iden) + Program + "end" + "for"; exitLoop.Rule = ToTerm("exit") | ToTerm("exit") + "when" + Expr; and.Rule = ToTerm("and") | "&"; or.Rule = ToTerm("or") | "|"; not.Rule = ToTerm("not") | "~" | "!"; result.Rule = "result" + Expr | "return" + Expr; recordList.Rule = iden + typeSpecifier + recordList | Empty; type.Rule = "type" + iden + typeSpecifier; memberCall.Rule = expandedIdentifier + "." + expandedIdentifier; //memberCall.Rule = iden + "." + functionCall | iden + "." + iden | iden + "." + memberCall; expandedIdentifier.Rule = iden | functionCall | memberCall; Statement.Rule = functionCall | memberCall | iden | variableDeclaration | ifBlock | caseBlock | functionCall | functionDefinition | io | assignment | result | loop | forLoop | type | newer | exitLoop; Program.Rule = Statement + Program | Empty; this.Root = Program; //4. Set operator precendence and associativity RegisterOperators(05, Associativity.Left, "not"); RegisterOperators(10, Associativity.Left, "=", "not="); RegisterOperators(30, Associativity.Left, "+", "-"); RegisterOperators(40, Associativity.Left, "*", "/", "div", "mod"); RegisterOperators(50, Associativity.Right, "**"); //5. Register Parenthesis as punctuation symbols so they will not appear in the syntax tree MarkPunctuation("(", ")", ","); RegisterBracePair("(", ")"); MarkTransient(Expr, BinOp, ParExpr); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public Gramatica() : base(caseSensitive: false) { #region ER //RegexBasedTerminal numero = new RegexBasedTerminal("int", "[0-9]+"); RegexBasedTerminal dec = new RegexBasedTerminal("double", "[0-9]+[.][0-9]+"); RegexBasedTerminal booleano = new RegexBasedTerminal("bool", "verdadero|falso|true|false"); NumberLiteral numero = TerminalFactory.CreateCSharpNumber("int"); IdentifierTerminal id = new IdentifierTerminal("id"); StringLiteral cadena = TerminalFactory.CreateCSharpString("string"); StringLiteral caracter = TerminalFactory.CreateCSharpChar("char"); CommentTerminal simple = new CommentTerminal("simple", ">>", "\n", "\r\n"); CommentTerminal multi = new CommentTerminal("multi", "<-", "->"); #endregion #region Terminales var mas = ToTerm("+"); var menos = ToTerm("-"); var div = ToTerm("/"); var por = ToTerm("*"); var para = ToTerm("("); var parc = ToTerm(")"); var elevar = ToTerm("^"); var aumento = ToTerm("++"); var decremento = ToTerm("--"); var igual = ToTerm("="); var not = ToTerm("!"); var diferente = ToTerm("!="); var equivalente = ToTerm("=="); var or = ToTerm("||"); var and = ToTerm("&&"); var menorque = ToTerm("<"); var mayorque = ToTerm(">"); var menorigual = ToTerm("<="); var mayorigual = ToTerm(">="); var puntocoma = ToTerm(";"); var coma = ToTerm(","); var punto = ToTerm("."); var dospuntos = ToTerm(":"); var llavea = ToTerm("{"); var llavec = ToTerm("}"); var corchetea = ToTerm("["); var corchetec = ToTerm("]"); var tint = ToTerm("int"); var tdouble = ToTerm("double"); var tstring = ToTerm("string"); var tchar = ToTerm("char"); var tbool = ToTerm("bool"); var array = ToTerm("array"); var clase = ToTerm("clase"); var importar = ToTerm("importar"); var publico = ToTerm("publico"); var privado = ToTerm("privado"); var tvoid = ToTerm("void"); var tnew = ToTerm("new"); var toverride = ToTerm("override"); var main = ToTerm("main"); var treturn = ToTerm("return"); var print = ToTerm("print"); var show = ToTerm("show"); var tif = ToTerm("if"); var telse = ToTerm("else"); var tfor = ToTerm("for"); var repeat = ToTerm("repeat"); var twhile = ToTerm("while"); var salir = ToTerm("salir"); var comprobar = ToTerm("comprobar"); var caso = ToTerm("caso"); var defecto = ToTerm("defecto"); var hacer = ToTerm("hacer"); var mientras = ToTerm("mientras"); var continuar = ToTerm("continuar"); var addfigure = ToTerm("addfigure"); var line = ToTerm("line"); var triangle = ToTerm("triangle"); var square = ToTerm("square"); var circle = ToTerm("circle"); var figure = ToTerm("figure"); #endregion #region No Terminales NonTerminal INICIO = new NonTerminal("INICIO"), LISTACLASES = new NonTerminal("LISTACLASES"), CLASE = new NonTerminal("CLASE"), OBJETO = new NonTerminal("OBJETO"), LISTAINSTRUCCIONES = new NonTerminal("LISTAINSTRUCCIONES"), LISTAMETODOS = new NonTerminal("LISTAMETODOS"), INSTRUCCION = new NonTerminal("INSTRUCCION"), METODO = new NonTerminal("METODO"), LISTAPARAM = new NonTerminal("LISTAPARAM"), LISTAENVIADA = new NonTerminal("LISTAENVIADA"), LISTAIDES = new NonTerminal("LISTAIDES"), DECLARACION = new NonTerminal("DECLARACION"), ASIGNACION = new NonTerminal("ASIGNACION"), VISIBILIDAD = new NonTerminal("VISIBILIDAD"), METODOVOID = new NonTerminal("METODOVOID"), METODORETURN = new NonTerminal("METODORETURN"), FUNCION = new NonTerminal("FUNCION"), RETURN = new NonTerminal("RETURN"), PRINT = new NonTerminal("PRINT"), IF = new NonTerminal("IF"), FOR = new NonTerminal("FOR"), REPEAT = new NonTerminal("REPEAT"), WHILE = new NonTerminal("WHILE"), COMPROBAR = new NonTerminal("COMPROBAR"), OPCION = new NonTerminal("OPCION"), DOWHILE = new NonTerminal("DOWHILE"), ADDFIGURA = new NonTerminal("ADDFIGURA"), FIGURA = new NonTerminal("FIGURA"), IFELSE = new NonTerminal("IF ELSE"), SHOW = new NonTerminal("SHOW"), LISTAIFELSE = new NonTerminal("LISTAIFELSE"), TIPO = new NonTerminal("TIPO"), LISTACASOS = new NonTerminal("LISTACASOS"), CONTINUAR = new NonTerminal("CONTINUAR"), CASO = new NonTerminal("CASO"), SALIR = new NonTerminal("SALIR"), PARAMETRO = new NonTerminal("PARAMETRO"), E = new NonTerminal("E"), MROBJECT = new NonTerminal("MROBJECT"), CALL = new NonTerminal("CALL"), AUMENTO = new NonTerminal("AUMENTO"), ACCESOVAR = new NonTerminal("ACCESOVAR"), DECREMENTO = new NonTerminal("DECREMENTO"), CAMBIO = new NonTerminal("CAMBIO"), DIMENSION = new NonTerminal("DIMENSION"), ASARREGLO = new NonTerminal("ASARREGLO"), AS1 = new NonTerminal("AS1"), AS2 = new NonTerminal("AS2"), AS3 = new NonTerminal("AS3"), RETURNARREGLO = new NonTerminal("RETURNARREGLO"), LISTAEXTRA = new NonTerminal("LISTAEXTRA"), EXTRA = new NonTerminal("EXTRA"), PRUEBA = new NonTerminal("PRUEBA"), LISTAPRUEBA = new NonTerminal("LISTAPRUEBA"), ASIGNACIONARRAY = new NonTerminal("ASIGNACIONARRAY"), TOARRAY = new NonTerminal("TOARRAY"), DARREGLO = new NonTerminal("DARREGLO"); #endregion #region Gramatica //precedencia this.RegisterOperators(0, Associativity.Left, or); this.RegisterOperators(1, Associativity.Left, and); this.RegisterOperators(2, Associativity.Left, not); this.RegisterOperators(3, Associativity.Left, equivalente, diferente, mayorigual, mayorque, menorque, menorigual); this.RegisterOperators(4, Associativity.Left, mas, menos); this.RegisterOperators(5, Associativity.Left, por, div); this.RegisterOperators(6, Associativity.Left, elevar); //marcar como puntuacion para que no aparezca en el arbol this.MarkPunctuation(para, array, treturn, hacer, mientras, punto, twhile, parc, puntocoma, coma, dospuntos, llavea, llavec, corchetea, corchetec, igual, clase, importar, tvoid, print, show, tif, telse, tfor, repeat); //no tomar para el analisis this.NonGrammarTerminals.Add(simple); this.NonGrammarTerminals.Add(multi); //hacer intrasendentes para optimizar el arbol this.MarkTransient(INSTRUCCION, TIPO, METODO, ASARREGLO, EXTRA, PRUEBA); //palabras reservadas para no confundir con ids this.MarkReservedWords("array", "clase", "importar", "publico", "privado", "void", "new", "override", "main", "return", "print", "show", "if", "else", "for", "repeat", "while", "salir", "comprobar", "caso", "defecto", "hacer", "mientras", "continuar", "addfigure", "circle", "triangle", "line", "square", "figure"); INICIO.Rule = LISTACLASES; //SOLO UN NODO ACTUANDO COMO LISTA LISTACLASES.Rule = MakePlusRule(LISTACLASES, CLASE); CLASE.Rule = clase + id + llavea + LISTAINSTRUCCIONES + LISTAMETODOS + llavec | clase + id + llavea + LISTAINSTRUCCIONES + llavec | clase + id + llavea + LISTAMETODOS + llavec | clase + id + llavea + llavec | clase + id + importar + LISTAIDES + llavea + LISTAINSTRUCCIONES + LISTAMETODOS + llavec | clase + id + importar + LISTAIDES + llavea + LISTAINSTRUCCIONES + llavec | clase + id + importar + LISTAIDES + llavea + LISTAMETODOS + llavec | clase + id + importar + LISTAIDES + llavea + llavec; LISTAIDES.Rule = MakePlusRule(LISTAIDES, coma, id); LISTAINSTRUCCIONES.Rule = MakePlusRule(LISTAINSTRUCCIONES, INSTRUCCION); LISTAMETODOS.Rule = MakePlusRule(LISTAMETODOS, METODO); INSTRUCCION.Rule = DECLARACION | ASIGNACION | FUNCION | PRINT | SHOW | IF | FOR | COMPROBAR | SALIR | CONTINUAR | WHILE | DOWHILE | REPEAT | RETURN | E | CAMBIO | OBJETO | MROBJECT | DARREGLO | ASIGNACIONARRAY ; DARREGLO.Rule = TIPO + array + LISTAIDES + DIMENSION + puntocoma | VISIBILIDAD + TIPO + array + LISTAIDES + DIMENSION + puntocoma | TIPO + array + LISTAIDES + DIMENSION + igual + ASARREGLO + puntocoma | VISIBILIDAD + TIPO + array + LISTAIDES + DIMENSION + igual + ASARREGLO + puntocoma ; ASARREGLO.Rule = AS1 | AS2 | AS3 | E; AS1.Rule = llavea + LISTAENVIADA + llavec; AS2.Rule = llavea + LISTAEXTRA + llavec; AS3.Rule = llavea + LISTAPRUEBA + llavec; LISTAPRUEBA.Rule = MakePlusRule(LISTAPRUEBA, coma, PRUEBA); PRUEBA.Rule = llavea + LISTAEXTRA + llavec; LISTAEXTRA.Rule = MakePlusRule(LISTAEXTRA, coma, EXTRA); EXTRA.Rule = llavea + LISTAENVIADA + llavec; DIMENSION.Rule = corchetea + E + corchetec | corchetea + E + corchetec + corchetea + E + corchetec | corchetea + E + corchetec + corchetea + E + corchetec + corchetea + E + corchetec; ASIGNACIONARRAY.Rule = id + igual + ASARREGLO + puntocoma; MROBJECT.Rule = id + id + igual + id + para + parc + puntocoma; OBJETO.Rule = id + id + puntocoma | id + id + igual + tnew + id + para + parc + puntocoma; CAMBIO.Rule = AUMENTO | DECREMENTO; AUMENTO.Rule = id + aumento + puntocoma; DECREMENTO.Rule = id + decremento + puntocoma; METODO.Rule = METODOVOID | METODORETURN; METODOVOID.Rule = main + para + parc + llavea + LISTAINSTRUCCIONES + llavec//MAIN | VISIBILIDAD + id + tvoid + toverride + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | id + tvoid + toverride + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + tvoid + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | id + tvoid + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + tvoid + toverride + para + parc + llavea + LISTAINSTRUCCIONES + llavec | id + tvoid + toverride + para + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + tvoid + para + parc + llavea + LISTAINSTRUCCIONES + llavec | id + tvoid + para + parc + llavea + LISTAINSTRUCCIONES + llavec ; METODORETURN.Rule = VISIBILIDAD + id + TIPO + toverride + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | id + TIPO + toverride + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + TIPO + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | id + TIPO + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + TIPO + toverride + para + parc + llavea + LISTAINSTRUCCIONES + llavec | id + TIPO + toverride + para + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + TIPO + para + parc + llavea + LISTAINSTRUCCIONES + llavec | id + TIPO + para + parc + llavea + LISTAINSTRUCCIONES + llavec | RETURNARREGLO; ; RETURNARREGLO.Rule = VISIBILIDAD + id + array + TIPO + DIMENSION + para + parc + llavea + LISTAINSTRUCCIONES + llavec | id + array + TIPO + DIMENSION + para + parc + llavea + LISTAINSTRUCCIONES + llavec | VISIBILIDAD + id + array + TIPO + DIMENSION + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec | id + array + TIPO + DIMENSION + para + LISTAPARAM + parc + llavea + LISTAINSTRUCCIONES + llavec; DECLARACION.Rule = VISIBILIDAD + TIPO + LISTAIDES + igual + E + puntocoma | TIPO + LISTAIDES + igual + E + puntocoma | TIPO + LISTAIDES + puntocoma | VISIBILIDAD + TIPO + LISTAIDES + puntocoma ; LISTAPARAM.Rule = MakePlusRule(LISTAPARAM, coma, PARAMETRO); PARAMETRO.Rule = TIPO + E | TIPO + TOARRAY; ASIGNACION.Rule = id + igual + E + puntocoma | TOARRAY + igual + E + puntocoma | id + punto + id + igual + E + puntocoma | id + punto + TOARRAY + igual + E + puntocoma; VISIBILIDAD.Rule = publico | privado; TIPO.Rule = tint | tdouble | tstring | tchar | tbool | id | TOARRAY; RETURN.Rule = treturn + E + puntocoma; FUNCION.Rule = id + para + LISTAENVIADA + parc + puntocoma | id + para + parc + puntocoma | id + punto + id + para + parc + puntocoma | id + punto + id + para + LISTAENVIADA + parc + puntocoma; LISTAENVIADA.Rule = MakePlusRule(LISTAENVIADA, coma, E); PRINT.Rule = print + para + E + parc + puntocoma; SHOW.Rule = show + para + E + coma + E + parc + puntocoma; IF.Rule = tif + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec | tif + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec + telse + llavea + LISTAINSTRUCCIONES + llavec | tif + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec + LISTAIFELSE + telse + llavea + LISTAINSTRUCCIONES + llavec ; LISTAIFELSE.Rule = MakePlusRule(LISTAIFELSE, IFELSE); IFELSE.Rule = telse + tif + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec; FOR.Rule = tfor + para + OPCION + E + puntocoma + E + parc + llavea + LISTAINSTRUCCIONES + llavec; OPCION.Rule = ASIGNACION | DECLARACION; REPEAT.Rule = repeat + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec; WHILE.Rule = twhile + para + E + parc + llavea + LISTAINSTRUCCIONES + llavec; COMPROBAR.Rule = comprobar + para + E + parc + llavea + LISTACASOS + llavec; LISTACASOS.Rule = MakePlusRule(LISTACASOS, CASO); CASO.Rule = caso + E + dospuntos + LISTAINSTRUCCIONES | defecto + dospuntos + LISTAINSTRUCCIONES; SALIR.Rule = salir + puntocoma; DOWHILE.Rule = hacer + llavea + LISTAINSTRUCCIONES + llavec + mientras + para + E + parc + puntocoma; CONTINUAR.Rule = continuar + puntocoma; E.Rule = E + mas + E | E + menos + E | E + por + E | E + div + E | E + elevar + E | E + equivalente + E | E + diferente + E | E + mayorque + E | E + mayorigual + E | E + menorigual + E | E + menorque + E | menos + E | E + aumento | E + decremento | E + or + E | E + and + E | not + E | para + E + parc | numero | dec | id | booleano | cadena | caracter | CALL | tnew + id + para + parc | ACCESOVAR | TOARRAY ; TOARRAY.Rule = id + DIMENSION; CALL.Rule = id + para + parc | id + para + LISTAENVIADA + parc | id + punto + id + para + parc | id + punto + id + para + LISTAENVIADA + parc; ACCESOVAR.Rule = id + punto + id; #endregion #region Raiz this.Root = INICIO; #endregion }