/// <summary> /// Initializes a new instance. /// </summary> public CSharpTypeNameGrammar() : base(true) { MarkPunctuation("<", ">", ".", ","); var identifier = TerminalFactory.CreateCSharpIdentifier(Terms.identifier); identifier.Flags |= TermFlags.NoAstNode; var qualified_identifier = new NonTerminal(Terms.qualified_identifier); var type_arg_list = new NonTerminal(Terms.type_arg_list); var type_arg_opt = new NonTerminal(Terms.type_arg_opt); type_arg_opt.Flags |= TermFlags.NoAstNode; var type_specifier = new NonTerminal(Terms.type_specifier); // symbols var DOT = ToTerm(".", Terms.DOT); var COMMA = ToTerm(",", Terms.COMMA); var LBRACKET = ToTerm("<", Terms.LBRACKET); var RBRACKET = ToTerm(">", Terms.RBRACKET); // rules qualified_identifier.Rule = MakePlusRule(qualified_identifier, DOT, identifier); type_arg_list.Rule = MakeStarRule(type_arg_list, COMMA, type_specifier); type_arg_opt.Rule = Empty | LBRACKET + type_arg_list + RBRACKET; type_specifier.Rule = qualified_identifier + type_arg_opt; // configure grammar Root = type_specifier; }
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 override void Init(AstContext context, ParseTreeNode treeNode) { base.Init(context, treeNode); var term = TerminalFactory.CreateCSharpIdentifier("text"); var tok = new Token(term, Location, "text", System.String.Join("_", treeNode.ChildNodes.Select(cn => cn.Term.Name))); treeNode.Token = tok; }
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 NumericalSchemeGrammar() { this.GrammarComments = ""; //Symbols var whitespace = new NonTerminal("WhiteSpace", Empty | " " | "\t"); // Comments var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var multiLineComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(multiLineComment); //Terminals var semicolon = ToTerm(";", "Semicolon"); var ofString = new StringLiteral("String", "\""); var ofNumber = new NumberLiteral("Number", NumberOptions.AllowSign); var ofIdentifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); var ofArrayTerm = new IdentifierTerminal("SchemeTerm", "(),|*.+-/%^~!&"); //Non-terminals var ofValue = new NonTerminal("Value"); var ofDictionary = new NonTerminal("Dictionary"); var ofDictionaryContent = new NonTerminal("DictionaryContent"); var ofDictionaryContentWrapper = new NonTerminal("DictionaryContentWrapper"); var ofDictEntry = new NonTerminal("DictEntry"); var ofArrayEntry = new NonTerminal("ArrayEntry"); var ofArray = new NonTerminal("Array"); var ofArrayWrapper = new NonTerminal("ArrayWrapper"); //BNF ofValue.Rule = ofIdentifier | ofArrayTerm | ofString | ofNumber; ofDictEntry.Rule = ofArrayWrapper | ofDictionary; ofDictionaryContent.Rule = MakeStarRule(ofDictionaryContent, whitespace, ofDictEntry); ofDictionaryContentWrapper.Rule = "{" + ofDictionaryContent + "}"; ofDictionary.Rule = ofIdentifier + whitespace + ofDictionaryContentWrapper; ofArrayEntry.Rule = ofValue; ofArray.Rule = MakeStarRule(ofArray, whitespace, ofArrayEntry); ofArrayWrapper.Rule = ofArray + semicolon; //Set grammar root this.Root = ofDictionaryContent; MarkPunctuation("{", "}"); MarkTransient(ofValue, ofDictionaryContentWrapper); }
public ASLGrammar() : base(true) { var stringLit = TerminalFactory.CreateCSharpString("string"); var number = TerminalFactory.CreateCSharpNumber("number"); var identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); var code = new CustomTerminal("code", MatchCodeTerminal); var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var delimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(delimitedComment); var state = new KeyTerm("state", "state"); var start = new KeyTerm("start", "start"); var split = new KeyTerm("split", "split"); var reset = new KeyTerm("reset", "reset"); var isLoading = new KeyTerm("isLoading", "isLoading"); var gameTime = new KeyTerm("gameTime", "gameTime"); var comma = ToTerm(",", "comma"); var semi = ToTerm(";", "semi"); var root = new NonTerminal("root"); var stateDef = new NonTerminal("stateDef"); var methodList = new NonTerminal("methodList"); var varList = new NonTerminal("varList"); var var = new NonTerminal("var"); var method = new NonTerminal("method"); var offsetList = new NonTerminal("offsetList"); var offset = new NonTerminal("offset"); var methodType = new NonTerminal("methodType"); root.Rule = stateDef + methodList; stateDef.Rule = state + "(" + stringLit + ")" + "{" + varList + "}"; methodList.Rule = MakeStarRule(methodList, method); varList.Rule = MakeStarRule(varList, semi, var); var.Rule = (identifier + identifier + ":" + stringLit + comma + offsetList) | Empty; method.Rule = (methodType + "{" + code + "}") | Empty; offsetList.Rule = MakePlusRule(offsetList, comma, offset); offset.Rule = number; methodType.Rule = start | split | isLoading | gameTime | reset; this.Root = root; MarkTransient(varList, methodList, offset, methodType); this.LanguageFlags = LanguageFlags.NewLineBeforeEOF; }
public void TestCSharpIdentifier() { SetTerminal(TerminalFactory.CreateCSharpIdentifier("Identifier")); TryMatch("x "); Assert.IsTrue(_token.Terminal.Name == "Identifier", "Failed to parse identifier"); Assert.IsTrue((string)_token.Value == "x", "Failed to parse identifier"); TryMatch("_a01 "); Assert.IsTrue(_token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)_token.Value == "_a01", "Failed to parse identifier starting with _"); TryMatch("0abc "); Assert.IsTrue(_token == null, "Erroneously recognized an identifier."); TryMatch(@"_\u0061bc "); Assert.IsTrue(_token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)_token.Value == "_abc", "Failed to parse identifier containing escape sequence \\u"); TryMatch(@"a\U00000062c_ "); Assert.IsTrue(_token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)_token.Value == "abc_", "Failed to parse identifier containing escape sequence \\U"); }//method
public void TestIdentifier_CSharp() { var parser = TestHelper.CreateParser(TerminalFactory.CreateCSharpIdentifier("Identifier")); var token = parser.ParseInput("x "); Assert.IsTrue(token.Terminal.Name == "Identifier", "Failed to parse identifier"); Assert.IsTrue((string)token.Value == "x", "Failed to parse identifier"); token = parser.ParseInput("_a01 "); Assert.IsTrue(token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)token.Value == "_a01", "Failed to parse identifier starting with _"); token = parser.ParseInput("0abc "); Assert.IsTrue(token.IsError, "Erroneously recognized an identifier."); token = parser.ParseInput(@"_\u0061bc "); Assert.IsTrue(token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)token.Value == "_abc", "Failed to parse identifier containing escape sequence \\u"); token = parser.ParseInput(@"a\U00000062c_ "); Assert.IsTrue(token.Terminal.Name == "Identifier", "Failed to parse identifier starting with _"); Assert.IsTrue((string)token.Value == "abc_", "Failed to parse identifier containing escape sequence \\U"); }
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 }
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 CicodeGrammar() : base(false) { var program = new NonTerminal("program"); var declaration = new NonTerminal("declaration"); var declarations = new NonTerminal("declarations"); var variableType = new NonTerminal("variable-type"); var parenParameters = new NonTerminal("paran-parameters"); var parameter = new NonTerminal("parameter"); var parameters = new NonTerminal("parameters"); var parameterInitializer = new NonTerminal("parameterInitializer"); var functionDeclaration = new NonTerminal("function-declaration"); var statements = new NonTerminal("statements"); var statement = new NonTerminal("statement"); var semiStatement = new NonTerminal("semi-statement"); var variableDeclaration = new NonTerminal("variable-declaration"); var block = new NonTerminal("block"); var variableInitializer = new NonTerminal("variableInitializer"); var variableInitializers = new NonTerminal("variableInitializers"); var blockContent = new NonTerminal("block-content"); var blockDeclarations = new NonTerminal("block-declarations"); var blockDeclaration = new NonTerminal("block-declaration"); var functionScope = new NonTerminal("function-scope"); var localVariableDeclaration = new NonTerminal("localVariableDeclaration"); var parameterType = new NonTerminal("parameterType"); var functionReturnType = new NonTerminal("function-returnType"); var returnStatement = new NonTerminal("return-statement"); var ifStatement = new NonTerminal("if-statement"); var optionalElseStatement = new NonTerminal("elseStatement"); var variableScope = new NonTerminal("variableScope"); var arrayIndexers = new NonTerminal("arrayIndexers"); var functionCall = new NonTerminal("functionCall"); var functionCallStatement = new NonTerminal("functionCallStatement"); var selectStatement = new NonTerminal("selectCaseStatement"); var caseStatement = new NonTerminal("caseStatement"); var caseStatements = new NonTerminal("caseStatements"); var caseExpression = new NonTerminal("caseExpression"); var caseExpressionList = new NonTerminal("caseExpressionList"); var caseElseStatement = new NonTerminal("caseElseStatement"); var whileDoStatement = new NonTerminal("whileDoStatement"); var forStatement = new NonTerminal("forStatement"); // Lexical Structure var stringLiteral = new StringLiteral("string", "\"", StringOptions.None); stringLiteral.EscapeChar = '^'; var numberLiteral = new NumberLiteral("number"); var identifier = TerminalFactory.CreateCSharpIdentifier("id"); var semi = ToTerm(";", "semi"); var colon = ToTerm(":", "colon"); var optionalSemi = new NonTerminal("semi?"); optionalSemi.Rule = Empty | semi; var dashLineComment = new CommentTerminal("comment", "//", "\n", "\r"); var bangLineComment = new CommentTerminal("comment", "!", "\n", "\r"); var blockComment = new CommentTerminal("BLOCK_COMMENT", "/*", "*/"); //comment must to be added to NonGrammarTerminals list; it is not used directly in grammar rules, // so we add it to this list to let Scanner know that it is also a valid terminal. base.NonGrammarTerminals.Add(dashLineComment); base.NonGrammarTerminals.Add(bangLineComment); base.NonGrammarTerminals.Add(blockComment); // Expressions var expression = new NonTerminal("expression"); var constantExpression = new NonTerminal("constantExpression"); var expressionList = new NonTerminal("expressionList"); var optionalExpression = new NonTerminal("optional-expression"); var literal = new NonTerminal("literal"); var term = new NonTerminal("term"); var arithmicExpression = new NonTerminal("arithmicExpression"); var parenthesizedExpression = new NonTerminal("ParExpr"); var unaryExpression = new NonTerminal("UnExpr"); var unaryOperator = new NonTerminal("UnOp"); var arithmicOperator = new NonTerminal("arithmicOperator", "operator"); var relationalOperator = new NonTerminal("relationalOperator", "operator"); var assignmentStatement = new NonTerminal("AssignmentStmt"); var assignmentOperator = new NonTerminal("assignmentOperator"); var variable = new NonTerminal("variable"); // 3. BNF rules expression.Rule = term | unaryExpression | arithmicExpression | functionCall; expressionList.Rule = expressionList + "," + expression | expression | Empty ; constantExpression.Rule = ToTerm("-") + numberLiteral | numberLiteral | stringLiteral ; optionalExpression.Rule = expression | Empty; term.Rule = literal | parenthesizedExpression | variable; parenthesizedExpression.Rule = "(" + expression + ")"; unaryExpression.Rule = unaryOperator + expression; unaryOperator.Rule = ToTerm("-") | "NOT"; arithmicExpression.Rule = expression + arithmicOperator + expression; relationalOperator.Rule = ToTerm(">") | "<" | ">=" | "<=" | "=" | "<>"; // strictly speaking not only arithmetic operators... should be refactored arithmicOperator.Rule = ToTerm("+") | "-" | "*" | "/" | "MOD" | "BITAND" | "BITOR" | "BITXOR" | relationalOperator | "AND" | "OR"; assignmentStatement.Rule = variable + assignmentOperator + expression + semi; assignmentOperator.Rule = ToTerm("="); // 4. Operators precedence RegisterOperators(2, "NOT"); RegisterOperators(3, "*", "/", "MOD"); //RegisterOperators(4, ":"); FOR FUTURE IMPL. What is this operator?? RegisterOperators(5, "+", "-"); RegisterOperators(6, ">", "<", "<=", ">="); RegisterOperators(7, "=", "<>"); RegisterOperators(8, "AND"); RegisterOperators(9, "OR"); RegisterOperators(10, "BITAND", "BITOR", "BITXOR"); // 5. Punctuation and transient terms MarkPunctuation("(", ")"); RegisterBracePair("(", ")"); MarkTransient(term, expression, arithmicOperator, unaryOperator, parenthesizedExpression); var arrayIdentifier = new NonTerminal("arrayIdentifier"); var arrayIndexer = new NonTerminal("arrayIndexer"); var arrayIndexDeclaration = new NonTerminal("arrayIndexDeclaration"); var arrayIndexDeclarations = new NonTerminal("arrayIndexDeclarations"); var arrayInitializers = new NonTerminal("arrayInitializers"); var arrayDeclaration = new NonTerminal("arrayDeclaration"); //////////////// literal.Rule = numberLiteral | stringLiteral; ifStatement.Rule = ToTerm("IF") + expression + ToTerm("THEN") + block + optionalElseStatement; optionalElseStatement.Rule = Empty | ToTerm("ELSE") + block; functionCall.Rule = identifier + "(" + expressionList + ")"; caseExpression.Rule = expression | expression + ToTerm("TO") + expression | ToTerm("IS") + relationalOperator + expression ; caseExpressionList.Rule = caseExpressionList + "," + caseExpression | caseExpression ; caseStatement.Rule = ToTerm("CASE") + caseExpressionList + statements ; caseElseStatement.Rule = ToTerm("CASE") + ToTerm("ELSE"); caseStatements.Rule = caseStatements + caseStatement | caseStatements + caseElseStatement | caseStatement; selectStatement.Rule = ToTerm("SELECT") + ToTerm("CASE") + expression + caseStatements + ToTerm("END") + ToTerm("SELECT"); whileDoStatement.Rule = ToTerm("WHILE") + expression + ToTerm("DO") + statements + ToTerm("END"); forStatement.Rule = ToTerm("FOR") + variable + ToTerm("=") + expression + ToTerm("TO") + expression + ToTerm("DO") + statements + ToTerm("END"); this.Root = program; program.Rule = declarations; declarations.Rule = MakeStarRule(declarations, declaration); variableInitializer.Rule = identifier + assignmentOperator + constantExpression; variableInitializers.Rule = variableInitializers + "," + variableInitializer | variableInitializer ; localVariableDeclaration.Rule = variableType + variableInitializers + ";" | variableType + identifier + ";" ; variableDeclaration.Rule = variableScope + variableType + variableInitializers + ";" | variableScope + variableType + identifier + ";" | arrayDeclaration + ";" ; arrayInitializers.Rule = arrayInitializers + "," + constantExpression | constantExpression ; arrayDeclaration.Rule = variableScope + variableType + identifier + arrayIndexDeclarations | variableScope + variableType + identifier + arrayIndexDeclarations + assignmentOperator + arrayInitializers; arrayIndexDeclarations.Rule = arrayIndexDeclarations + arrayIndexDeclaration | arrayIndexDeclaration ; arrayIndexers.Rule = arrayIndexers + arrayIndexer | arrayIndexer ; arrayIdentifier.Rule = identifier + arrayIndexers; arrayIndexer.Rule = "[" + expression + "]"; arrayIndexDeclaration.Rule = "[" + numberLiteral + "]"; variable.Rule = identifier | identifier + arrayIndexers ; variableType.Rule = ToTerm("INT") | ToTerm("STRING") | ToTerm("REAL") | ToTerm("OBJECT") | ToTerm("QUALITY") | ToTerm("TIMESTAMP") ; variableScope.Rule = Empty | ToTerm("GLOBAL") | ToTerm("MODULE") ; parameterInitializer.Rule = Empty | assignmentOperator + constantExpression; parameter.Rule = variableType + identifier + parameterInitializer; parameters.Rule = parameters + "," + parameter | parameter; parenParameters.Rule = ToTerm("(") + ")" | "(" + parameters + ")"; statements.Rule = MakeStarRule(statements, statement); statement.Rule = semiStatement | ifStatement | selectStatement | whileDoStatement | forStatement ; functionCallStatement.Rule = functionCall + semi; returnStatement.Rule = ToTerm("RETURN") + optionalExpression + semi; semiStatement.Rule = assignmentStatement | returnStatement | functionCallStatement ; block.Rule = blockContent + "END"; blockContent.Rule = blockDeclarations + statements ; blockDeclarations.Rule = MakeStarRule(blockDeclarations, blockDeclaration); blockDeclaration.Rule = localVariableDeclaration; functionScope.Rule = ToTerm("PUBLIC") | "PRIVATE" | Empty; // These reduce hints are needed to help determine the difference between // a function declaration and a variable declaration. functionScope.ReduceIf("FUNCTION"); variableScope.ReduceIf(semi); functionReturnType.Rule = variableType | Empty; declaration.Rule = functionDeclaration | variableDeclaration ; functionDeclaration.Rule = functionScope + functionReturnType + "FUNCTION" + identifier + parenParameters + block; MarkTransient(semiStatement, blockDeclaration); }
public OpenFoamGrammar() { this.GrammarComments = ""; ////Symbols var whitespace = new NonTerminal("WhiteSpace", Empty | " " | "\t"); // Comments var singleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); var multiLineComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(singleLineComment); NonGrammarTerminals.Add(multiLineComment); //Terminals var semicolon = ToTerm(";", "Semicolon"); var ofString = new StringLiteral("String", "\""); var ofNumber = new NumberLiteral("Number", NumberOptions.AllowSign); var ofIdentifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); var ofFvtUniform = ToTerm("uniform", "ofFvtUniform"); var ofFvtNonUniform = ToTerm("nonuniform", "ofFvtNonUniform"); //Nonterminals var ofValue = new NonTerminal("ofValue"); var ofArray = new NonTerminal("ofArray"); var ofArrayEntry = new NonTerminal("ofArrayEntry"); var ofArrayWrapper = new NonTerminal("ofArrayWrapper"); var ofDictionary = new NonTerminal("Dictionary"); var ofDictionaryContent = new NonTerminal("DictionaryContent"); var ofDictionaryContentWrapper = new NonTerminal("DictionaryContentWrapper"); var dictEntry = new NonTerminal("dictEntry"); var dictEntry_Basic = new NonTerminal("dictEntry_Basic"); var dictEntry_DimensionSet = new NonTerminal("dictEntry_DimensionSet"); var dictEntry_DimensionalScalar = new NonTerminal("dictEntry_DimensionalScalar"); var dictEntry_Array = new NonTerminal("dictEntry_Array"); var dictEntry_FieldValue = new NonTerminal("dictEntry_FieldValue"); //var dictEntry_FieldValueArray = new NonTerminal("dictEntry_FieldValueArray"); //Rules ofValue.Rule = ofIdentifier | ofString | ofNumber | "true" | "false" | "null"; dictEntry_Basic.Rule = ofIdentifier + whitespace + ofValue + semicolon; dictEntry_DimensionSet.Rule = ofIdentifier + whitespace + "[" + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + "]" + semicolon; dictEntry_DimensionalScalar.Rule = ofIdentifier + whitespace + ofIdentifier + "[" + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + ofNumber + "]" + ofNumber + semicolon; dictEntry_Array.Rule = ofIdentifier + whitespace + ofArrayWrapper + semicolon; dictEntry_FieldValue.Rule = ofIdentifier + (ofFvtUniform | ofFvtNonUniform) + (ofNumber | ofArray) + semicolon; dictEntry.Rule = dictEntry_Basic | dictEntry_DimensionSet | dictEntry_DimensionalScalar | dictEntry_Array | ofDictionary | dictEntry_FieldValue ; ofDictionaryContent.Rule = MakeStarRule(ofDictionaryContent, whitespace, dictEntry); ofDictionaryContentWrapper.Rule = "{" + ofDictionaryContent + "}"; ofDictionary.Rule = ofIdentifier + whitespace + ofDictionaryContentWrapper; ofArrayEntry.Rule = ofValue | ofArrayWrapper | ofDictionary; ofArray.Rule = MakeStarRule(ofArray, whitespace, ofArrayEntry); ofArrayWrapper.Rule = "(" + ofArray + ")"; //Set grammar root this.Root = ofDictionaryContent; MarkPunctuation("{", "}", "[", "]", ":", ","); MarkTransient(ofValue, ofDictionaryContentWrapper); //MarkReservedWords("FoamFile"); }
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 GramaticaPython() : base(caseSensitive: false) { #region expresiones regulares var identificador = TerminalFactory.CreateCSharpIdentifier("identificador"); var numero = TerminalFactory.CreateCSharpNumber("numero"); var val_false = Constantes.falso; var val_true = Constantes.verdadero; StringLiteral cadena = new StringLiteral("cadena", "\""); var caracter = TerminalFactory.CreateCSharpChar(Constantes.caracter); CommentTerminal COMENT_BLOQUE = new CommentTerminal("COMENTARIO BLOQUE", "/*", "*/"); CommentTerminal COMENT_LINEA = new CommentTerminal("COMENTARIO LINEA", "//", "\n", "\r\n"); NonGrammarTerminals.Add(COMENT_BLOQUE); NonGrammarTerminals.Add(COMENT_LINEA); #endregion NonTerminal EXPRESION = new NonTerminal(Constantes.expresion); NonTerminal DECIMAL = new NonTerminal(Constantes.tipoDecimal); NonTerminal ENTERO = new NonTerminal(Constantes.tipoEntero); NonTerminal CADENA = new NonTerminal(Constantes.tipoCadena); NonTerminal CHAR = new NonTerminal(Constantes.tipoChar); NonTerminal BOOLEANO = new NonTerminal(Constantes.tipoBool); NonTerminal SIMB_ARIT = new NonTerminal(Constantes.simb_arit); NonTerminal SIMB_REL = new NonTerminal(Constantes.simb_rel); NonTerminal UNARIO = new NonTerminal(Constantes.unario); NonTerminal ID = new NonTerminal(Constantes.id); NonTerminal NEGATIVO = new NonTerminal(Constantes.negativo); NonTerminal RELACIONAL = new NonTerminal(Constantes.relacional); NonTerminal ARITMETICA = new NonTerminal(Constantes.aritmetica); NonTerminal LOGICA = new NonTerminal(Constantes.logica); NonTerminal LLAMADA = new NonTerminal(Constantes.llamada); NonTerminal POSVECTOR = new NonTerminal(Constantes.posvector); NonTerminal LISTAPUNTOS = new NonTerminal(Constantes.listapuntos); NonTerminal SIMB_LOG = new NonTerminal(Constantes.simb_log); NonTerminal MAS_MAS = new NonTerminal(Constantes.masmas); NonTerminal MENOS_MENOS = new NonTerminal(Constantes.menosmenos); NonTerminal ASIG_ARRAY = new NonTerminal(Constantes.asig_array); NonTerminal termino = new NonTerminal(Constantes.termino); NonTerminal L_IDS = new NonTerminal(Constantes.listaIds); NonTerminal SUMA = new NonTerminal(Constantes.suma); NonTerminal RESTA = new NonTerminal(Constantes.resta); NonTerminal MULTIPLICACION = new NonTerminal(Constantes.multiplicacion); NonTerminal DIVISION = new NonTerminal(Constantes.division); NonTerminal POTENCIA = new NonTerminal(Constantes.potencia); NonTerminal MENOR = new NonTerminal(Constantes.menor); NonTerminal MENORIGUAL = new NonTerminal(Constantes.menorIgual); NonTerminal MAYOR = new NonTerminal(Constantes.mayor); NonTerminal MAYORIGUAL = new NonTerminal(Constantes.mayorIgual); NonTerminal IGUALIGUAL = new NonTerminal(Constantes.igualIgual); NonTerminal DISTINTOA = new NonTerminal(Constantes.distintoA); NonTerminal XOR = new NonTerminal(Constantes.xorJava); NonTerminal AND = new NonTerminal(Constantes.andJava); NonTerminal NOT = new NonTerminal(Constantes.notJavaPython); NonTerminal OR = new NonTerminal(Constantes.orJava); NonTerminal INSTANCIA = new NonTerminal(Constantes.instancia); NonTerminal POSICION = new NonTerminal(Constantes.posicion); NonTerminal FILA = new NonTerminal(Constantes.fila); NonTerminal LPOSICIONES = new NonTerminal(Constantes.lposiciones); NonTerminal LEXPRESIONES = new NonTerminal(Constantes.lexpresiones); NonTerminal LFILAS = new NonTerminal(Constantes.lfilas); #region expresion POSICION.Rule = ToTerm("[") + EXPRESION + "]"; LPOSICIONES.Rule = MakePlusRule(LPOSICIONES, POSICION); FILA.Rule = ToTerm("{") + LEXPRESIONES + "}"; LEXPRESIONES.Rule = MakePlusRule(LEXPRESIONES, ToTerm(","), EXPRESION); LFILAS.Rule = MakePlusRule(LFILAS, ToTerm(","), FILA); DECIMAL.Rule = numero; ENTERO.Rule = numero; CADENA.Rule = cadena; ID.Rule = identificador; CHAR.Rule = caracter; BOOLEANO.Rule = ToTerm(val_false) | ToTerm(val_true); ARITMETICA.Rule = SUMA | RESTA | MULTIPLICACION | DIVISION | POTENCIA; RELACIONAL.Rule = MENOR | MAYOR | MENORIGUAL | MAYORIGUAL | DISTINTOA | IGUALIGUAL; LOGICA.Rule = XOR | OR | AND | NOT; SUMA.Rule = EXPRESION + ToTerm(Constantes.suma) + EXPRESION; RESTA.Rule = EXPRESION + ToTerm(Constantes.resta) + EXPRESION; MULTIPLICACION.Rule = EXPRESION + ToTerm(Constantes.multiplicacion) + EXPRESION; DIVISION.Rule = EXPRESION + ToTerm(Constantes.division) + EXPRESION; POTENCIA.Rule = EXPRESION + ToTerm(Constantes.potencia) + EXPRESION; MENOR.Rule = EXPRESION + ToTerm(Constantes.menor) + EXPRESION; MENORIGUAL.Rule = EXPRESION + ToTerm(Constantes.menorIgual) + EXPRESION; MAYOR.Rule = EXPRESION + ToTerm(Constantes.mayor) + EXPRESION; MAYORIGUAL.Rule = EXPRESION + ToTerm(Constantes.mayorIgual) + EXPRESION; IGUALIGUAL.Rule = EXPRESION + ToTerm(Constantes.igualIgual) + EXPRESION; DISTINTOA.Rule = EXPRESION + ToTerm(Constantes.distintoA) + EXPRESION; XOR.Rule = EXPRESION + ToTerm(Constantes.xorJava) + EXPRESION; AND.Rule = EXPRESION + ToTerm(Constantes.andJava) + EXPRESION; NOT.Rule = ToTerm(Constantes.notJavaPython) + EXPRESION; OR.Rule = EXPRESION + ToTerm(Constantes.orJava) + EXPRESION; INSTANCIA.Rule = Constantes.nuevo + identificador + "(" + LEXPRESIONES + ")" | Constantes.nuevo + identificador + "(" + ")"; UNARIO.Rule = MAS_MAS | MENOS_MENOS; MAS_MAS.Rule = identificador + ToTerm(Constantes.masmas); MENOS_MENOS.Rule = identificador + ToTerm(Constantes.menosmenos); NEGATIVO.Rule = ToTerm("-") + EXPRESION; termino.Rule = //ARITMETICA //| RELACIONAL // | LOGICA DECIMAL | ENTERO | ID | CADENA | BOOLEANO | CHAR; //| LLAMADA //| POSVECTOR //| UNARIO //| ToTerm("(") + EXPRESION + ")" //| NEGATIVO //| "{" + LFILAS + "}" //| INSTANCIA; LLAMADA.Rule = identificador + ToTerm("(") + LEXPRESIONES + ")" | identificador + ToTerm("(") + ")"; POSVECTOR.Rule = identificador + LPOSICIONES; L_IDS.Rule = MakePlusRule(L_IDS, ToTerm(","), identificador); EXPRESION.Rule = MakePlusRule(EXPRESION, ToTerm("."), termino); NonTerminal n = new NonTerminal("fdsfd"); n.Rule = EXPRESION; #endregion Root = n; }
public AnalizadorTree() : base(caseSensitive: false) { //Comentarios CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "##", "\n", "\r\n"); CommentTerminal COMENTARIO_MULT = new CommentTerminal("comentario_mult", "{--", "--}"); NonGrammarTerminals.Add(COMENTARIO_SIMPLE); NonGrammarTerminals.Add(COMENTARIO_MULT); //Palabras Reservadas MarkReservedWords("importar"); MarkReservedWords("__constructor"); MarkReservedWords("super"); MarkReservedWords("self"); MarkReservedWords("publico"); MarkReservedWords("privado"); MarkReservedWords("protegido"); MarkReservedWords("/**Sobreescribir**/"); MarkReservedWords("metodo"); MarkReservedWords("funcion"); MarkReservedWords("clase"); MarkReservedWords("si"); MarkReservedWords("si_no_si"); MarkReservedWords("si_no"); MarkReservedWords("elegir"); MarkReservedWords("caso"); MarkReservedWords("defecto"); MarkReservedWords("para"); MarkReservedWords("hacer"); MarkReservedWords("mientras"); MarkReservedWords("repetir"); MarkReservedWords("hasta"); MarkReservedWords("loop"); MarkReservedWords("nuevo"); MarkReservedWords("return"); MarkReservedWords("salir"); MarkReservedWords("continuar"); MarkReservedWords("true"); MarkReservedWords("false"); MarkReservedWords("void"); MarkReservedWords("entero"); MarkReservedWords("decimal"); MarkReservedWords("caracter"); MarkReservedWords("cadena"); MarkReservedWords("booleano"); MarkReservedWords("out_String"); MarkReservedWords("parseInt"); MarkReservedWords("parseDouble"); MarkReservedWords("intToStr"); MarkReservedWords("doubleToStr"); MarkReservedWords("doubleToInt"); MarkReservedWords("imprimir"); //Palabras reservadas var importar = ToTerm("importar"); var constructor = ToTerm("__constructor"); var super = ToTerm("super"); var self = ToTerm("self"); var publico = ToTerm("publico"); var privado = ToTerm("privado"); var protegido = ToTerm("protegido"); var sobreescribir = ToTerm("/**Sobreescribir**/"); var metodo = ToTerm("metodo"); var funcion = ToTerm("funcion"); var clase = ToTerm("clase"); var si = ToTerm("si"); var sinosi = ToTerm("si_no_si"); var sino = ToTerm("si_no"); var selector = ToTerm("elegir"); var caso = ToTerm("caso"); var defecto = ToTerm("defecto"); var para = ToTerm("para"); var hacer = ToTerm("hacer"); var mientras = ToTerm("mientras"); var repetir = ToTerm("repetir"); var hasta = ToTerm("hasta"); var loop = ToTerm("loop"); var nuevo = ToTerm("nuevo"); var retornar = ToTerm("return"); var quiebre = ToTerm("salir"); var continuar = ToTerm("continuar"); var verdadero = ToTerm("true"); var falso = ToTerm("false"); var vacio = ToTerm("void"); var num = ToTerm("entero"); var dec = ToTerm("decimal"); var caracter = ToTerm("caracter"); var str = ToTerm("cadena"); var boolean = ToTerm("booleano"); var outStr = ToTerm("out_String"); var parseInt = ToTerm("parseInt"); var parseDouble = ToTerm("parseDouble"); var intToStr = ToTerm("intToStr"); var doubleToStr = ToTerm("doubleToStr"); var doubleToInt = ToTerm("doubleToInt"); var mostrar = ToTerm("imprimir"); //Signos var asignar = ToTerm("=>"); var apar = ToTerm("("); var cpar = ToTerm(")"); var acor = ToTerm("["); var ccor = ToTerm("]"); var coma = ToTerm(","); var punto = ToTerm("."); var dosp = ToTerm(":"); //No Terminales var INICIO = new NonTerminal("INICIO"); var IMPORTACIONES = new NonTerminal("IMPORTACIONES"); var IMPORTAR = new NonTerminal("IMPORTAR"); var LISTA_ARCHIVOS = new NonTerminal("LISTA_ARCHIVOS"); var ARCHIVO = new NonTerminal("ARCHIVO"); var CLASES = new NonTerminal("CLASES"); var CLASE = new NonTerminal("CLASE"); var BCUERPO = new NonTerminal("BCUERPO"); var CUERPO = new NonTerminal("CUERPO"); var METODO = new NonTerminal("METODO"); var VISIBILIDAD = new NonTerminal("VISIBILIDAD"); var DECLARACIONES = new NonTerminal("DECLARACIONES"); var LISTA_IDS = new NonTerminal("IDS"); var BLOQUE = new NonTerminal("BLOQUE"); var LISTA_SENTENCIAS = new NonTerminal("SENTENCIAS"); var SENTENCIA = new NonTerminal("SENTENCIA"); var DECLARAR = new NonTerminal("DECLARAR"); var asignarR = new NonTerminal("asignarR"); var CONTROL = new NonTerminal("CONTROL"); var IF1 = new NonTerminal("IF1"); var IF2 = new NonTerminal("IF2"); var IF3 = new NonTerminal("IF3"); var IF4 = new NonTerminal("IF4"); var IF5 = new NonTerminal("IF5"); var SWITCH = new NonTerminal("SWITCH"); var CASOS = new NonTerminal("CASOS"); var BCASO = new NonTerminal("BCASO"); var CASO = new NonTerminal("CASO"); var ECASO = new NonTerminal("ECASO"); var DEFECTO = new NonTerminal("DEFECTO"); var WHILE = new NonTerminal("WHILE"); var DO_WHILE = new NonTerminal("DO_WHILE"); var FOR = new NonTerminal("FOR"); var LOOP = new NonTerminal("LOOP"); var REPEAT = new NonTerminal("REPEAT"); var BANDERA = new NonTerminal("BANDERA"); var EXP = new NonTerminal("EXP"); var EXPS = new NonTerminal("EXPS"); var ACCESO = new NonTerminal("ACCESO"); var TACCESO = new NonTerminal("TACCESO"); var TIPO = new NonTerminal("TIPO"); var LLAMADA = new NonTerminal("LLAMADA"); var TPROC = new NonTerminal("TPROC"); var CUERPOS = new NonTerminal("CUERPOS"); var VARIABLES = new NonTerminal("VARIABLES"); var RETORNO = new NonTerminal("RETORNO"); var INTERRUMPIR = new NonTerminal("INTERRUMPIR"); var CONTINUAR = new NonTerminal("CONTINUAR"); var LISTA_PARAMETROS = new NonTerminal("LISTA_PARAMETROS"); var PARAMETRO = new NonTerminal("PARAMETRO"); var PARAM = new NonTerminal("PARAM"); var DECLARACION = new NonTerminal("DECLARACION"); var ASIGNACION = new NonTerminal("ASIGNACION"); var DIMENSION = new NonTerminal("DIMENSION"); var NATIVAS = new NonTerminal("NATIVAS"); var CADENA = new NonTerminal("CADENA"); var IMPRIMIR = new NonTerminal("IMPRIMIR"); var EXCEPTION = new NonTerminal("EXCEPTION"); var Fasignar = new NonTerminal("Fasignar"); var DIM = new NonTerminal("DIM"); var DIM2 = new NonTerminal("DIM"); var INDICES = new NonTerminal("INDICES"); var AID = new NonTerminal("AID"); var Tasignar = new NonTerminal("EXP"); var CRECE = new NonTerminal("CRECE"); var ARR = new NonTerminal("ARR"); var A = new NonTerminal("A"); var NARREGLO = new NonTerminal("NARREGLO"); var DARREGLO = new NonTerminal("NARREGLO"); var NUMEROS = new NonTerminal("INDICES"); var NUEVO = new NonTerminal("NUEVO"); var SUPER = new NonTerminal("SUPER"); var ESTE = new NonTerminal("ESTE"); //Terminales Expresiones Regulares RegexBasedTerminal archivo = new RegexBasedTerminal("archivo", "[a-zA-Z][0-9a-zA-Z]*.(tree|olc)"); RegexBasedTerminal ruta = new RegexBasedTerminal("ruta", "C://([a-zA-Z][0-9a-zA-Z]*/)*[a-zA-Z][0-9a-zA-Z]*.(tree|olc)"); RegexBasedTerminal url = new RegexBasedTerminal("url", "http://([a-zA-Z][0-9a-zA-Z]*/)*[a-zA-Z][0-9a-zA-Z]*.(tree|olc)"); NumberLiteral numero = TerminalFactory.CreateCSharpNumber("numero"); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); var tstring = new StringLiteral("cadena", "\"", StringOptions.AllowsDoubledQuote); var tchar = new StringLiteral("caracter", "'", StringOptions.AllowsDoubledQuote); //No Terminal Inicial this.Root = INICIO; //Producciones INICIO.Rule = IMPORTACIONES + CLASES | CLASES; IMPORTACIONES.Rule = MakeStarRule(IMPORTACIONES, IMPORTAR); IMPORTAR.Rule = importar + LISTA_ARCHIVOS + Eos; LISTA_ARCHIVOS.Rule = MakeStarRule(LISTA_ARCHIVOS, coma, ARCHIVO); ARCHIVO.Rule = ruta | archivo | url; CLASES.Rule = MakeStarRule(CLASES, CLASE); CLASE.Rule = clase + id + acor + id + ccor + dosp + Eos + BCUERPO | clase + id + acor + ccor + dosp + Eos + BCUERPO; BCUERPO.Rule = Indent + CUERPOS + Dedent; CUERPOS.Rule = MakeStarRule(CUERPOS, CUERPO); CUERPO.Rule = VISIBILIDAD + DECLARACION + Eos | METODO | constructor + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE | DECLARACION + Eos | ASIGNACION + Eos; METODO.Rule = sobreescribir + Eos + VISIBILIDAD + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE | VISIBILIDAD + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE | sobreescribir + Eos + TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE | TPROC + id + acor + LISTA_PARAMETROS + ccor + dosp + Eos + BLOQUE; VISIBILIDAD.Rule = publico | privado | protegido; LISTA_PARAMETROS.Rule = MakeStarRule(LISTA_PARAMETROS, coma, PARAMETRO); PARAMETRO.Rule = TIPO + id + ARR; ARR.Rule = MakeStarRule(ARR, A); A.Rule = acor + ccor; DECLARACION.Rule = TIPO + LISTA_IDS + asignarR | TIPO + LISTA_IDS | TIPO + DARREGLO; DARREGLO.Rule = id + NUMEROS; NUMEROS.Rule = MakeStarRule(NUMEROS, DIM2); DIM2.Rule = acor + numero + ccor; asignarR.Rule = asignar + EXP; ASIGNACION.Rule = ACCESO + asignar + EXP; INDICES.Rule = MakeStarRule(INDICES, DIM); LISTA_IDS.Rule = LISTA_IDS + coma + id | id; BLOQUE.Rule = Indent + LISTA_SENTENCIAS + Dedent; LISTA_SENTENCIAS.Rule = MakeStarRule(LISTA_SENTENCIAS, SENTENCIA); SENTENCIA.Rule = DECLARACION + Eos | self + punto + ASIGNACION + Eos | ASIGNACION + Eos | CONTROL | ACCESO + Eos | INTERRUMPIR + Eos | CONTINUAR + Eos | RETORNO + Eos | NATIVAS + Eos | IMPRIMIR + Eos | SUPER + Eos; SUPER.Rule = super + punto + ASIGNACION | super + punto + ACCESO | super + acor + EXPS + ccor; IMPRIMIR.Rule = mostrar + acor + EXP + ccor | outStr + acor + EXP + ccor; NATIVAS.Rule = parseInt + acor + EXP + ccor | parseDouble + acor + EXP + ccor | intToStr + acor + EXP + ccor | doubleToStr + acor + EXP + ccor | doubleToInt + acor + EXP + ccor; INTERRUMPIR.Rule = quiebre; CONTINUAR.Rule = continuar; RETORNO.Rule = retornar + EXP; LLAMADA.Rule = id + acor + EXPS + ccor; CONTROL.Rule = IF1 | IF2 | IF3 | IF5 | SWITCH | WHILE | DO_WHILE | FOR | LOOP | REPEAT; IF1.Rule = si + EXP + dosp + Eos + BLOQUE; IF2.Rule = si + EXP + dosp + Eos + BLOQUE + sino + dosp + Eos + BLOQUE; IF3.Rule = si + EXP + dosp + Eos + BLOQUE + IF4; IF5.Rule = si + EXP + dosp + Eos + BLOQUE + IF4 + sino + dosp + Eos + BLOQUE; IF4.Rule = IF4 + sinosi + EXP + dosp + Eos + BLOQUE | sinosi + EXP + dosp + Eos + BLOQUE; SWITCH.Rule = selector + caso + EXP + dosp + Eos + BCASO; BCASO.Rule = Indent + CASOS + DEFECTO + Dedent | Indent + CASOS + Dedent; CASOS.Rule = MakeStarRule(CASOS, CASO); CASO.Rule = EXP + dosp + Eos + BLOQUE; DEFECTO.Rule = defecto + dosp + Eos + BLOQUE; WHILE.Rule = mientras + EXP + dosp + Eos + BLOQUE; DO_WHILE.Rule = hacer + dosp + Eos + BLOQUE + mientras + EXP + Eos; REPEAT.Rule = repetir + dosp + Eos + BLOQUE + hasta + EXP + Eos; Fasignar.Rule = DECLARACION | ASIGNACION; FOR.Rule = para + acor + Fasignar + dosp + EXP + dosp + EXP + ccor + dosp + Eos + BLOQUE; LOOP.Rule = loop + dosp + Eos + BLOQUE; TPROC.Rule = funcion + TIPO + ARR | metodo; TIPO.Rule = vacio | num | dec | caracter | str | boolean | id; NARREGLO.Rule = id + INDICES; EXP.Rule = EXP + EXP + ToTerm("or") | EXP + EXP + ToTerm("and") | EXP + EXP + ToTerm("xor") | EXP + EXP + ToTerm("==") | EXP + EXP + ToTerm("!=") | EXP + EXP + ToTerm(">") | EXP + EXP + ToTerm("<") | EXP + EXP + ToTerm(">=") | EXP + EXP + ToTerm("<=") | EXP + EXP + ToTerm("+") | EXP + EXP + ToTerm("-") | EXP + EXP + ToTerm("*") | EXP + EXP + ToTerm("/") | EXP + EXP + ToTerm("pow") | apar + EXP + cpar | acor + EXP + ccor | EXP + ToTerm("-") | EXP + ToTerm("not") | CRECE | NUEVO | LLAMADA | NATIVAS | super + punto + ACCESO | self + punto + ACCESO | ACCESO | numero | tstring | tchar | BANDERA; BANDERA.Rule = falso | verdadero; NUEVO.Rule = nuevo + id + acor + EXPS + ccor; ACCESO.Rule = MakeStarRule(ACCESO, punto, TACCESO); TACCESO.Rule = LLAMADA | id | NARREGLO; DIM.Rule = acor + EXP + ccor; EXPS.Rule = MakeStarRule(EXPS, coma, EXP); CRECE.Rule = EXP + ToTerm("++") | EXP + ToTerm("--"); //Definir Asociatividad RegisterOperators(1, Associativity.Left, "or"); //OR,NOR RegisterOperators(2, Associativity.Left, "and"); //AND,NAND RegisterOperators(3, Associativity.Left, "xor"); //XOR RegisterOperators(4, Associativity.Right, "not"); //NOT RegisterOperators(5, Associativity.Left, "==", "!=", ">", "<", ">=", "<="); //MAYORQUES,MENORQUES,IGUAL,DIFERENTE RegisterOperators(6, Associativity.Left, "+", "-"); //MAS,MENOS RegisterOperators(7, Associativity.Left, "*", "/"); //POR,DIVIDIR,MOD RegisterOperators(8, Associativity.Right, "-"); //UNARIO RegisterOperators(9, Associativity.Left, "pow"); //POTENCIA RegisterOperators(10, Associativity.Left, "++", "--"); //Manejo de Errores Lexicos y Sintacticos SENTENCIA.ErrorRule = SyntaxError + SENTENCIA; CUERPO.ErrorRule = SyntaxError + CUERPO; CASOS.ErrorRule = SyntaxError + CASO; //Eliminacion de caracters, no terminales que son estorbos this.MarkPunctuation("(", ")", ":", "=>", ",", ".", "[", "]", "://", "/"); this.MarkPunctuation("clase", "si", "si_no_si", "si_no", "elegir", "caso", "defecto", "hacer", "mientras", "loop", "repetir", "para", "return", "continuar", "salir"); this.MarkTransient(AID, asignarR, IMPORTACIONES, IMPORTAR, ARCHIVO, TACCESO, SENTENCIA, DIM, DIM2, CONTROL, TIPO, DEFECTO); }
public Gramatica() : base(caseSensitive: true) { //---------------------> Comentarios CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "//", "\n", "\r\n"); CommentTerminal COMENTARIO_MULT = new CommentTerminal("comentario_mult", "/*", "*/"); NonGrammarTerminals.Add(COMENTARIO_SIMPLE); NonGrammarTerminals.Add(COMENTARIO_MULT); //---------------------> Definir Palabras Reservadas MarkReservedWords("Int"); MarkReservedWords("Double"); MarkReservedWords("String"); MarkReservedWords("Char"); MarkReservedWords("Bool"); MarkReservedWords("Void"); MarkReservedWords("True"); MarkReservedWords("False"); MarkReservedWords("Import"); MarkReservedWords("Return"); MarkReservedWords("If"); MarkReservedWords("Else"); MarkReservedWords("Switch"); MarkReservedWords("Case"); MarkReservedWords("Break"); MarkReservedWords("Default"); MarkReservedWords("For"); MarkReservedWords("Do"); MarkReservedWords("While"); MarkReservedWords("Print"); MarkReservedWords("CompareTo"); MarkReservedWords("GetUser()"); //---------------------> (Opcional)Definir variables para palabras reservadas var entero = ToTerm("Int"); var doubl = ToTerm("Double"); var strin = ToTerm("String"); var caracter = ToTerm("Char"); var booleano = ToTerm("Bool"); var voi = ToTerm("Void"); var verdadero = ToTerm("True"); var falso = ToTerm("False"); var importacion = ToTerm("Import"); var retornar = ToTerm("Return"); var si = ToTerm("If"); var sino = ToTerm("Else"); var switc = ToTerm("Switch"); var caso = ToTerm("Case"); var brea = ToTerm("Break"); var defaul = ToTerm("Default"); var para = ToTerm("For"); var hacer = ToTerm("Do"); var mientras = ToTerm("While"); var imprime = ToTerm("Print"); var comparador = ToTerm("CompareTo"); var nombreUsuario = ToTerm("GetUser()"); //---------------------> (Opcional)Definir variables para signos y mas var coma = ToTerm(","); var pto = ToTerm("."); var pyc = ToTerm(";"); var dospts = ToTerm(":"); var apar = ToTerm("("); var cpar = ToTerm(")"); var alla = ToTerm("{"); var clla = ToTerm("}"); var acor = ToTerm("["); var ccor = ToTerm("]"); //------------------------> Operadores var mas = ToTerm("+"); var menos = ToTerm("-"); var multiplicacion = ToTerm("*"); var division = ToTerm("/"); var porcentaje = ToTerm("%"); var potencia = ToTerm("^"); var mayor = ToTerm(">"); var menor = ToTerm("<"); var menorigual = ToTerm("<="); var mayorigual = ToTerm(">="); var comparacion = ToTerm("=="); var diferente = ToTerm("!="); var or = ToTerm("||"); var and = ToTerm("&&"); var xor = ToTerm("|&"); var not = ToTerm("!"); var suma = ToTerm("+="); var resta = ToTerm("-="); var asignar = ToTerm("="); var disminuir = ToTerm("--"); var aumentar = ToTerm("++"); //---------------------> No Terminales var INICIO = new NonTerminal("INICIO"); var METODO = new NonTerminal("METODO"); var SENTENCIAS = new NonTerminal("SENTENCIAS"); var DECLARA = new NonTerminal("DECLARA"); var ASIGNACIONVAR = new NonTerminal("ASIGNACIONVAR"); var PARAMETROS = new NonTerminal("PARAMETROS"); var PARA = new NonTerminal("PARA"); var DECLARACIONES = new NonTerminal("DECLARACIONES"); var IF = new NonTerminal("IF"); var IFE = new NonTerminal("IFE"); var VARIOS = new NonTerminal("VARIOS"); var LLAMADA = new NonTerminal("LLAMADA"); var VALORES = new NonTerminal("VALORES"); var IMPRIMIR = new NonTerminal("IMPRIMIR"); var WHILE = new NonTerminal("WHILE"); var DOWHILE = new NonTerminal("DOWHILE"); var TIPO = new NonTerminal("TIPO"); var S = new NonTerminal("S"); var EXPRE = new NonTerminal("EXPRE"); var INCREMENTA = new NonTerminal("INCREMENTA"); var DECREMENTA = new NonTerminal("DECREMENTA"); var ASIGNACIONES = new NonTerminal("ASIGNACIONES"); var IMPORTACIONES = new NonTerminal("IMPORTACIONES"); var IMPORTACION = new NonTerminal("IMPORTACION"); var VAR = new NonTerminal("VAR"); var RETOR = new NonTerminal("RETOR"); var CLASES = new NonTerminal("CLASES"); var ARREGLOS = new NonTerminal("ARREGLOS"); var SWITCH = new NonTerminal("SWITCH"); var FOR = new NonTerminal("FOR"); var CASOS = new NonTerminal("CASOS"); var CASO = new NonTerminal("CASO"); var COMPARTO = new NonTerminal("COMPARTO"); //---------------------> Terminales NumberLiteral num = new NumberLiteral("num"); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); var tstring = new StringLiteral("tstring", "\"", StringOptions.AllowsDoubledQuote); var tchar = new StringLiteral("tchar", "'", StringOptions.AllowsDoubledQuote); //----------------------------------------------PRODUCCIONES----------------------------------------------------------- S.Rule = IMPORTACIONES + CLASES; IMPORTACIONES.Rule = MakeStarRule(IMPORTACIONES, IMPORTACION); IMPORTACION.Rule = importacion + tstring + pyc; CLASES.Rule = MakeStarRule(CLASES, INICIO); INICIO.Rule = DECLARA + dospts + TIPO + METODO; /* --------------------------------------------------------------------------------------- * * CREACION DE METODOS * * --------------------------------------------------------------------------------------- */ METODO.Rule = ASIGNACIONES + pyc | apar + PARAMETROS + cpar + alla + VARIOS + clla; /* --------------------------------------------------------------------------------------- * * DECLARACION DE VARIABLES * * --------------------------------------------------------------------------------------- */ TIPO.Rule = entero | caracter | booleano | doubl | strin | voi; ARREGLOS.Rule = id + acor + EXPRE + ccor; DECLARACIONES.Rule = DECLARA + dospts + TIPO + ASIGNACIONES; ASIGNACIONES.Rule = asignar + EXPRE | acor + EXPRE + ccor + asignar + alla + VALORES + clla | acor + EXPRE + ccor | acor + EXPRE + ccor + asignar + EXPRE | Empty; DECLARA.Rule = DECLARA + coma + id | id; ASIGNACIONVAR.Rule = id + asignar + EXPRE | id + asignar + alla + VALORES + clla | id + acor + EXPRE + ccor + asignar + EXPRE; PARAMETROS.Rule = PARAMETROS + coma + PARA | PARA | Empty; PARA.Rule = id + dospts + TIPO; /* --------------------------------------------------------------------------------------- * * SENTENCIAS * * --------------------------------------------------------------------------------------- */ IMPRIMIR.Rule = imprime + apar + EXPRE + cpar + pyc; VARIOS.Rule = MakeStarRule(VARIOS, SENTENCIAS); SENTENCIAS.Rule = DECLARACIONES + pyc | retornar + RETOR + pyc | IF | IFE | WHILE | DOWHILE | IMPRIMIR | INCREMENTA + pyc | DECREMENTA + pyc | LLAMADA + pyc | ASIGNACIONVAR + pyc | ARREGLOS | brea + pyc | SWITCH | FOR; LLAMADA.Rule = id + apar + VALORES + cpar; RETOR.Rule = EXPRE | Empty; VALORES.Rule = VALORES + coma + EXPRE | EXPRE | Empty; IF.Rule = si + apar + EXPRE + cpar + alla + VARIOS + clla; IFE.Rule = si + apar + EXPRE + cpar + alla + VARIOS + clla + sino + alla + VARIOS + clla; WHILE.Rule = mientras + apar + EXPRE + cpar + alla + VARIOS + clla; DOWHILE.Rule = hacer + alla + VARIOS + clla + mientras + apar + EXPRE + cpar; INCREMENTA.Rule = EXPRE + mas + mas; DECREMENTA.Rule = EXPRE + menos + menos; SWITCH.Rule = switc + apar + EXPRE + cpar + alla + CASOS + clla; CASOS.Rule = MakePlusRule(CASOS, CASO); CASO.Rule = caso + EXPRE + dospts + VARIOS + brea + pyc | defaul + dospts + VARIOS; FOR.Rule = para + apar + DECLARACIONES + pyc + EXPRE + pyc + EXPRE + cpar + alla + VARIOS + clla; COMPARTO.Rule = id + pto + comparador + apar + EXPRE + cpar; /* --------------------------------------------------------------------------------------- * * OPERACIONES ARITMETICAS Y RELACIONALES * * --------------------------------------------------------------------------------------- */ EXPRE.Rule = EXPRE + or + EXPRE | EXPRE + and + EXPRE | EXPRE + comparacion + EXPRE | EXPRE + diferente + EXPRE | EXPRE + mayor + EXPRE | EXPRE + mayorigual + EXPRE | EXPRE + menor + EXPRE | EXPRE + menorigual + EXPRE | EXPRE + mas + EXPRE | EXPRE + menos + EXPRE | EXPRE + multiplicacion + EXPRE | EXPRE + division + EXPRE | EXPRE + porcentaje + EXPRE | apar + EXPRE + cpar | num | menos + num | id | verdadero | falso | tstring | LLAMADA | INCREMENTA | DECREMENTA | tchar | ARREGLOS | COMPARTO | nombreUsuario; //---------------------> No Terminal Inicial this.Root = S; //---------------------> Definir Asociatividad RegisterOperators(1, Associativity.Left, or); //OR RegisterOperators(2, Associativity.Left, and); //AND RegisterOperators(3, Associativity.Left, comparacion, diferente); //IGUAL, DIFERENTE RegisterOperators(4, Associativity.Left, mayor, menor, mayorigual, menorigual); //MAYORQUES, MENORQUES RegisterOperators(5, Associativity.Left, mas, menos); //MAS, MENOS RegisterOperators(6, Associativity.Left, multiplicacion, division); //POR, DIVIDIR RegisterOperators(2, Associativity.Left, porcentaje); //POTENCIA RegisterOperators(7, Associativity.Right, "!"); //NOT //---------------------> Manejo de Errores /* SENTENCIAS.ErrorRule = SyntaxError + clla; * METODO.ErrorRule = SyntaxError + clla;*/ //CASOS.ErrorRule = SyntaxError + CASO;*/ //---------------------> Eliminacion de caracters, no terminales this.MarkPunctuation(apar, cpar, pyc, alla, clla, asignar, coma, dospts, acor, ccor, pto); // this.MarkPunctuation("print", "if", "else", "do", "while"); // this.MarkTransient(SENTENCIA); //this.MarkTransient(CASO); }
public AssemblyGrammar() { #region Declare Terminals Here CommentTerminal blockComment = new CommentTerminal("block-comment", "/*", "*/"); CommentTerminal lineComment = new CommentTerminal("line-comment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); //CommentTerminal sharpComment = new CommentTerminal("sharp-comment","#","\r","\n","\u2085","\u2028","\u2029"); NonGrammarTerminals.Add(blockComment); NonGrammarTerminals.Add(lineComment); //NonGrammarTerminals.Add(sharpComment); StringLiteral stringLiteral = new StringLiteral("string-literal", "\""); StringLiteral charLiteral = new StringLiteral("char-literal", "\'", StringOptions.IsChar); NumberLiteral number = new NumberLiteral("number", NumberOptions.AllowSign | NumberOptions.IntOnly); number.AddPrefix("0x", NumberOptions.Hex); number.AddPrefix("0b", NumberOptions.Binary); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("identifier"); #endregion #region Declare NonTerminals Here; NonTerminal fileroot = new NonTerminal("fileroot"); NonTerminal rootdefs = new NonTerminal("root-defines"); NonTerminal rootdef = new NonTerminal("root-define"); NonTerminal usingDesc = new NonTerminal("using-description"); NonTerminal memorySizeDesc = new NonTerminal("memorysize-description"); NonTerminal targetISADesc = new NonTerminal("targetisa-description"); NonTerminal label = new NonTerminal("label"); NonTerminal operandReg = new NonTerminal("operand-register"); NonTerminal operandRef = new NonTerminal("operand-reference"); NonTerminal operandImm = new NonTerminal("operand-immediate"); NonTerminal valueInt = new NonTerminal("value-integer"); NonTerminal valueChar = new NonTerminal("value-character"); NonTerminal valueRefAddr = new NonTerminal("value-referaddress"); NonTerminal labeledStatement = new NonTerminal("labeled-statement"); NonTerminal statement = new NonTerminal("statement"); NonTerminal instr = new NonTerminal("instruction"); NonTerminal instrLabels = new NonTerminal("instruction-labels"); NonTerminal instrNemonic = new NonTerminal("instruction-nemonic"); NonTerminal instrOperands = new NonTerminal("instruction-operands"); NonTerminal instrOperand = new NonTerminal("instruction-operand"); NonTerminal labeledInstrOperand = new NonTerminal("labeled-instruction-operand"); NonTerminal instrJump = new NonTerminal("instruction-jump"); NonTerminal instrJumpNemonic = new NonTerminal("instruction-jump-nemonic"); NonTerminal instrJumpTarget = new NonTerminal("instruction-jump-target"); NonTerminal macrocall = new NonTerminal("macrocall"); NonTerminal macrocallLabels = new NonTerminal("macrocall-labels"); NonTerminal macrocallName = new NonTerminal("macrocall-name"); NonTerminal macrocallOperands = new NonTerminal("macrocall-operands"); NonTerminal macrocallOperand = new NonTerminal("macrocall-operand"); NonTerminal symboldef = new NonTerminal("symboldef"); NonTerminal symboldefName = new NonTerminal("symboldef-name"); NonTerminal symboldefContent = new NonTerminal("symboldef-content"); NonTerminal variabledef = new NonTerminal("variabledef"); NonTerminal variabledefName = new NonTerminal("variabledef-name"); NonTerminal variabledefContents = new NonTerminal("variabledef-contents"); NonTerminal variabledefContent = new NonTerminal("variabledef-content"); NonTerminal variabledefPositionHint = new NonTerminal("variabledef-poshint"); NonTerminal constantdef = new NonTerminal("constantdef"); NonTerminal constantdefName = new NonTerminal("constantdef-name"); NonTerminal constantdefContents = new NonTerminal("constantdef-content"); NonTerminal constantdefContent = new NonTerminal("constantdef-content"); NonTerminal macrodef = new NonTerminal("macrodef"); NonTerminal macrodefArguments = new NonTerminal("macrodef-arguments"); NonTerminal macrodefArgument = new NonTerminal("macrodef-arguments"); NonTerminal macrodefContents = new NonTerminal("macrodef-contents"); NonTerminal macrodefContent = new NonTerminal("macrodef-content"); NonTerminal sectiondef = new NonTerminal("sectiondef"); NonTerminal sectiondefAttributes = new NonTerminal("sectiondef-attributes"); NonTerminal sectiondefAttribute = new NonTerminal("sectiondef-attribute"); NonTerminal sectiondefContents = new NonTerminal("sectiondef-contents"); NonTerminal sectiondefContent = new NonTerminal("sectiondef-content"); NonTerminal blockdef = new NonTerminal("blockdef"); NonTerminal blockdefContents = new NonTerminal("blockdef-contents"); NonTerminal blockdefContent = new NonTerminal("blockdef-content"); NonTerminal debugprint = new NonTerminal("debugprint"); #endregion #region Place Rules Here this.Root = fileroot; fileroot.Rule = rootdefs; rootdefs.Rule = MakeStarRule(rootdefs, rootdef); rootdef.Rule = sectiondef | usingDesc | memorySizeDesc | targetISADesc; usingDesc.Rule = ToTerm("#include") + stringLiteral + ToTerm(";"); memorySizeDesc.Rule = ToTerm("#memorysize") + number + ToTerm(";"); targetISADesc.Rule = ToTerm("#targetisa") + stringLiteral + ToTerm(";"); //Commons operandImm.Rule = valueInt | valueChar | valueRefAddr; valueInt.Rule = number; valueChar.Rule = charLiteral; valueRefAddr.Rule = ToTerm("&") + identifier | ToTerm("&") + identifier + ToTerm("[") + number + ToTerm("]"); operandRef.Rule = identifier; operandReg.Rule = ToTerm("$") + number | ToTerm("$") + identifier; //Variable variabledef.Rule = ToTerm(".variable") + variabledefName + ToTerm(";") //With no initial value (these will be grouped into one variable by optimization.) | ToTerm(".variable") + variabledefName + ToTerm("=") + variabledefContent + ToTerm(";") //With initial value (these will be not grouped.) | ToTerm(".variable") + variabledefName + ToTerm("[") + number + ToTerm("]") + ToTerm("=") + ToTerm("{") + variabledefContents + ToTerm("}") + ToTerm(";") | ToTerm(".variable") + variabledefName + variabledefPositionHint + ToTerm(";") //With no initial value (these will be grouped into one variable by optimization.) | ToTerm(".variable") + variabledefName + variabledefPositionHint + ToTerm("=") + variabledefContent + ToTerm(";") //With initial value (these will be not grouped.) | ToTerm(".variable") + variabledefName + ToTerm("[") + number + ToTerm("]") + variabledefPositionHint + ToTerm("=") + ToTerm("{") + variabledefContents + ToTerm("}") + ToTerm(";");; variabledefPositionHint.Rule = ToTerm("(") + ToTerm("@") + number + ToTerm(")"); variabledefName.Rule = identifier; variabledefContents.Rule = MakeStarRule(variabledefContents, ToTerm(","), variabledefContent); variabledefContent.Rule = valueInt | valueChar | valueRefAddr; //Constant constantdef.Rule = ToTerm(".constant") + constantdefName + ToTerm("=") + constantdefContent + ToTerm(";") | ToTerm(".constant") + constantdefName + ToTerm("[") + number + ToTerm("]") + ToTerm("=") + ToTerm("{") + constantdefContents + ToTerm("}") + ToTerm(";"); constantdefName.Rule = identifier; constantdefContents.Rule = MakeStarRule(constantdefContents, ToTerm(","), constantdefContent); constantdefContent.Rule = valueInt | valueChar | valueRefAddr; //Statement instr | callmacro debugprint.Rule = ToTerm(">>>>") + stringLiteral; label.Rule = identifier + ToTerm(":"); labeledStatement.Rule = label + labeledStatement | statement; statement.Rule = instr | macrocall; //Instruction instr.Rule = instrNemonic + instrOperands + ToTerm(";") | instrNemonic + instrOperands + ToTerm(";") + debugprint | instrNemonic + instrOperands + instrJump + ToTerm(";") | instrNemonic + instrOperands + instrJump + ToTerm(";") + debugprint; instrNemonic.Rule = identifier; instrLabels.Rule = MakeStarRule(instrLabels, label); instrOperands.Rule = MakeStarRule(instrOperands, ToTerm(","), labeledInstrOperand); labeledInstrOperand.Rule = label + labeledInstrOperand | instrOperand; instrOperand.Rule = operandRef | operandImm | operandReg; //Instruction Jump instrJump.Rule = ToTerm("-<") + instrJumpNemonic + instrJumpTarget; instrJumpNemonic.Rule = identifier; instrJumpTarget.Rule = operandRef | operandImm | operandReg; //Macrocall macrocall.Rule = ToTerm("~") + macrocallName + ToTerm("(") + macrocallOperands + ToTerm(")") + ToTerm(";") | ToTerm("~") + macrocallName + ToTerm("(") + macrocallOperands + ToTerm(")") + ToTerm(";") + debugprint; macrocallName.Rule = identifier; macrocallOperands.Rule = MakeStarRule(macrocallOperands, ToTerm(","), macrocallOperand); macrocallOperand.Rule = operandRef | operandImm | operandReg; //Macrodefinition macrodef.Rule = ToTerm("macro") + identifier + ToTerm("(") + macrodefArguments + ToTerm(")") + ToTerm("{") + macrodefContents + ToTerm("}"); macrodefArguments.Rule = MakeStarRule(macrodefArguments, ToTerm(","), macrodefArgument); macrodefArgument.Rule = identifier; macrodefContents.Rule = MakeStarRule(macrodefContents, macrodefContent); macrodefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | macrodef; //Symboldefinition symboldef.Rule = ToTerm(".symbol") + symboldefName + ToTerm("=") + symboldefContent + ToTerm(";") | ToTerm(".symbol") + symboldefName + ToTerm(":=") + symboldefContent + ToTerm(";"); symboldefName.Rule = identifier; symboldefContent.Rule = operandReg | ToTerm("@") + number | valueInt | valueChar | valueRefAddr; //Section 属性を設定可能 sectiondef.Rule = ToTerm("section") + identifier + ToTerm("{") + sectiondefAttributes + sectiondefContents + ToTerm("}"); sectiondefAttributes.Rule = MakeStarRule(sectiondefAttributes, sectiondefAttribute); sectiondefAttribute.Rule = ToTerm(".startup"); sectiondefContents.Rule = MakeStarRule(sectiondefContents, sectiondefContent); sectiondefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | symboldef | macrodef; //Block ただのスコープ blockdef.Rule = ToTerm("{") + blockdefContents + ToTerm("}") | identifier + ToTerm("{") + blockdefContents + ToTerm("}"); blockdefContents.Rule = MakeStarRule(blockdefContents, blockdefContent); blockdefContent.Rule = blockdef | labeledStatement | variabledef | constantdef | symboldef | macrodef; //セクションで定義された変数や定数・命令は最適化されて好き勝手な場所に配置される. //デバッグ情報からその変数がどこのセクションで定義され,どこに配置されているかが確認できる //セクションはその親のセクションを持っている //ラベルを参照する際にはそのラベルが使用されたセクションから順に上をたどって参照先を検索する //マクロが展開されるとその中身は新しいブロックの中に展開される //.startup //.variable NAME = //.constant NAME = 0x23a1s,65409 //'srl: rd,rs,rt //{ // //} // //@ROM //{ // //} #endregion #region Define Keywords this.MarkReservedWords("break", "continue", "else", "extern", "for", "if", "int", "return", "static", "void", "while"); #endregion }
public 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 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 Gramatica() : base(caseSensitive: true) { CommentTerminal blockComment = new CommentTerminal("block-comment", "/*", "*/"); CommentTerminal lineComment = new CommentTerminal("line-comment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); NonGrammarTerminals.Add(blockComment); NonGrammarTerminals.Add(lineComment); /* Reserved Words */ KeyTerm var_ = ToTerm("var"), goto_ = ToTerm("goto"), if_ = ToTerm("if"), ifFalse_ = ToTerm("ifFalse"), proc_ = ToTerm("proc"), begin_ = ToTerm("begin"), end_ = ToTerm("end"), call_ = ToTerm("call"), print_ = ToTerm("print"), c_ = ToTerm("c"), i_ = ToTerm("i"), f_ = ToTerm("f"); MarkReservedWords("var", "goto", "if", "ifFalse", "proc", "begin", "end", "call", "print", "c", "i", "f"); /* Arithmetic Operators*/ KeyTerm mas = ToTerm("+"), menos = ToTerm("-"), por = ToTerm("*"), division = ToTerm("/"), modulo = ToTerm("%"); /* Relational operators */ KeyTerm menorigual = ToTerm("<="), mayorigual = ToTerm(">="), menorque = ToTerm("<"), mayorque = ToTerm(">"), igual = ToTerm("=="), diferente = ToTerm("!="); /* Symbols*/ KeyTerm equal = ToTerm("="), semicolon = ToTerm(";"), colon = ToTerm(":"), comma = ToTerm(","), leftPar = ToTerm("("), rightPar = ToTerm(")"), leftCor = ToTerm("["), rightCor = ToTerm("]"), quotes = ToTerm("\""); MarkPunctuation(equal, semicolon, colon, comma, leftPar, rightPar, quotes); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); RegexBasedTerminal label = new RegexBasedTerminal("label", "L[0-9]+"); NumberLiteral num = new NumberLiteral("num"); NonTerminal START = new NonTerminal("START"), INSTRUCTIONS = new NonTerminal("INSTRUCTIONS"), INSTRUCTION = new NonTerminal("INSTRUCTION"), DECLARATION = new NonTerminal("DECLARATION"), ASSIGNMENT = new NonTerminal("ASSIGNMENT"), LABEL = new NonTerminal("LABEL"), GOTO = new NonTerminal("GOTO"), IF = new NonTerminal("IF"), METHOD = new NonTerminal("METHOD"), CALL = new NonTerminal("CALL"), PRINT = new NonTerminal("PRINT"), CHART = new NonTerminal("CHART"), IDENTIFIER_LIST = new NonTerminal("IDENTIFIER_LIST"), BLOCKS = new NonTerminal("BLOCKS"), BLOCK = new NonTerminal("BLOCK"), E = new NonTerminal("E"), E_ARITHMETIC = new NonTerminal("E_ARITHMETIC"), E_RELATIONAL = new NonTerminal("E_RELATIONAL"), E_PRIMITIVE = new NonTerminal("E_PRIMITIVE"); this.RegisterOperators(1, Associativity.Left, igual, diferente); this.RegisterOperators(2, Associativity.Left, mayorigual, menorigual, mayorque, menorque); this.RegisterOperators(3, Associativity.Left, mas, menos); this.RegisterOperators(4, Associativity.Left, por, division); this.RegisterOperators(5, Associativity.Right, modulo); this.Root = START; START.Rule = INSTRUCTIONS; INSTRUCTIONS.Rule = MakePlusRule(INSTRUCTIONS, INSTRUCTION); INSTRUCTION.Rule = DECLARATION + semicolon | ASSIGNMENT + semicolon | LABEL | GOTO + semicolon | IF + semicolon | METHOD | CALL + semicolon | PRINT + semicolon; LABEL.Rule = label + colon; GOTO.Rule = goto_ + label; IF.Rule = if_ + leftPar + E + rightPar + goto_ + label | ifFalse_ + leftPar + E + rightPar + goto_ + label; METHOD.Rule = proc_ + id + leftPar + rightPar + begin_ + BLOCKS + end_; CALL.Rule = call_ + id; PRINT.Rule = print_ + leftPar + quotes + modulo + CHART + quotes + comma + id + rightPar; CHART.Rule = c_ | i_ | f_; DECLARATION.Rule = var_ + IDENTIFIER_LIST | var_ + id + equal + E | var_ + id + leftCor + rightCor; IDENTIFIER_LIST.Rule = MakeStarRule(IDENTIFIER_LIST, comma, id); ASSIGNMENT.Rule = id + equal + E | id + leftCor + E + rightCor + equal + E; BLOCKS.Rule = MakeStarRule(BLOCKS, BLOCK); BLOCK.Rule = DECLARATION + semicolon | ASSIGNMENT + semicolon | LABEL | GOTO + semicolon | IF + semicolon | CALL + semicolon | PRINT + semicolon; E.Rule = E_ARITHMETIC | E_RELATIONAL | E_PRIMITIVE | leftPar + E + rightPar; E_ARITHMETIC.Rule = E + mas + E | E + menos + E | E + por + E | E + division + E | E + modulo + E; E_RELATIONAL.Rule = E + menorigual + E | E + mayorigual + E | E + menorque + E | E + mayorque + E | E + igual + E | E + diferente + E; E_PRIMITIVE.Rule = num | id | id + leftCor + E + rightCor; }
//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("]") }); }
public GrammarP1() : base(caseSensitive: true) { /*************** Comentarios ***************/ //No hay :D /*************** Reservados ***************/ MarkReservedWords("CONJ"); MarkReservedWords("RESERV"); MarkReservedWords("retorno"); MarkReservedWords("yytext"); MarkReservedWords("yyline"); MarkReservedWords("yyrow"); MarkReservedWords("error"); MarkReservedWords("int"); MarkReservedWords("float"); MarkReservedWords("string"); MarkReservedWords("char"); MarkReservedWords("bool"); var conj = ToTerm("CONJ"); var reserv = ToTerm("RESERV"); var retorno = ToTerm("retorno"); var yytext = ToTerm("yytext"); var yyline = ToTerm("yyline"); var yyrow = ToTerm("yyrow"); var rerror = ToTerm("error"); var rint = ToTerm("int"); var rfloat = ToTerm("float"); var rstring = ToTerm("string"); var rchar = ToTerm("char"); var rbool = ToTerm("bool"); var flecha = ToTerm("->"); var fin = ToTerm(";"); var dosp = ToTerm(":"); var coma = ToTerm(","); var apar = ToTerm("("); var cpar = ToTerm(")"); var acor = ToTerm("["); var ccor = ToTerm("]"); var and = ToTerm("."); var or = ToTerm("|"); var muchos = ToTerm("+"); var nada_muchos = ToTerm("*"); var nada = ToTerm("?"); //var barra = ToTerm("\\"); var salto = ToTerm("\\n"); var retorno_carro = ToTerm("\\r"); var tab = ToTerm("\\t"); var comillas_s = ToTerm("\\'"); var comillas_d = ToTerm("\\\""); var blanco = ToTerm("[:blanco:]"); var todo = ToTerm("[:todo:]"); /*************** No Terminales ***************/ var INICIO = new NonTerminal("INICIO", typeof(AstNode)); var CUERPO = new NonTerminal("CUERPO", typeof(AstNode)); var CODIGO = new NonTerminal("CODIGO", typeof(AstNode)); var SENTENCIA = new NonTerminal("SENTENCIA", typeof(AstNode)); var CONJUNTO = new NonTerminal("CONJUNTO", typeof(AstNode)); var SERIE = new NonTerminal("SERIE", typeof(AstNode)); var SERIE2 = new NonTerminal("SERIE2", typeof(AstNode)); var LISTA = new NonTerminal("LISTA", typeof(AstNode)); var SIMBOLO = new NonTerminal("SIMBOLO", typeof(AstNode)); var REGLA = new NonTerminal("REGLA", typeof(AstNode)); var METODO = new NonTerminal("METODO", typeof(AstNode)); var ER = new NonTerminal("ER", typeof(AstNode)); var ESCAPE = new NonTerminal("ESCAPE", typeof(AstNode)); var M1 = new NonTerminal("M1", typeof(AstNode)); var M2 = new NonTerminal("M2", typeof(AstNode)); var TIPO = new NonTerminal("TIPO", typeof(AstNode)); var RERROR = new NonTerminal("ERROR", typeof(AstNode)); var RESERVAR = new NonTerminal("RESERVAR", typeof(AstNode)); var RESERVADAS = new NonTerminal("RESERVADAS", typeof(AstNode)); var RESERVADA = new NonTerminal("RESERVADA", typeof(AstNode)); /*************** Terminales ***************/ NumberLiteral numero = TerminalFactory.CreateCSharpNumber("numero"); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); var tstring = new StringLiteral("tstring", "\"", StringOptions.AllowsDoubledQuote); var tchar = new StringLiteral("tchar", "'", StringOptions.AllowsDoubledQuote); RegexBasedTerminal ascii = new RegexBasedTerminal("ascii", "[^\008\009\010\011\013\020\024\032\034\039\092\096\0239\0249]"); //AstNode numero.AstConfig.NodeType = typeof(AstNode); id.AstConfig.NodeType = typeof(AstNode); tstring.AstConfig.NodeType = typeof(AstNode); tchar.AstConfig.NodeType = typeof(AstNode); ascii.AstConfig.NodeType = typeof(AstNode); /*************** Gramatica ***************/ this.Root = INICIO; INICIO.Rule = CUERPO; CUERPO.Rule = ToTerm("%%") + CODIGO + ToTerm("%%"); CODIGO.Rule = MakeStarRule(CODIGO, SENTENCIA); SENTENCIA.Rule = CONJUNTO | REGLA | RERROR; CONJUNTO.Rule = conj + dosp + id + flecha + SERIE + fin | conj + dosp + id + flecha + LISTA + fin; //SERIE.Rule = SIMBOLO + ToTerm("~") + SIMBOLO; //SERIE.Rule = SERIE2; SERIE.Rule = SIMBOLO + ToTerm("~") + SIMBOLO; LISTA.Rule = MakeStarRule(LISTA, coma, SIMBOLO); SIMBOLO.Rule = SERIE | ESCAPE | numero | tstring | tchar | id | ascii; REGLA.Rule = id + flecha + ER + flecha + METODO + fin | id + flecha + ER + flecha + METODO + flecha + RESERVAR + fin | id + flecha + ER + flecha + METODO + fin + flecha + RESERVAR + fin; ER.Rule = ER + ER + and | ER + ER + or | ER + muchos | ER + nada_muchos | ER + nada | ESCAPE | tstring | tchar | numero | id; ESCAPE.Rule = salto | retorno_carro | tab | comillas_s | comillas_d | blanco | todo; /*ESCAPE.Rule = barra+ToTerm("n") | barra + ToTerm("r") | barra + ToTerm("t") | barra + ToTerm("'") | barra + ToTerm("\"") | blanco | todo;*/ METODO.Rule = M1 | M2; RESERVAR.Rule = reserv + acor + RESERVADAS + ccor; RESERVADAS.Rule = MakeStarRule(RESERVADAS, RESERVADA); RESERVADA.Rule = tstring + flecha + retorno + apar + id + coma + yyline + coma + yyrow + cpar + fin | id + flecha + retorno + apar + id + coma + yyline + coma + yyrow + cpar + fin; M1.Rule = retorno + apar + id + coma + yyline + coma + yyrow + cpar; M2.Rule = retorno + apar + id + coma + yytext + coma + TIPO + coma + yyline + coma + yyrow + cpar; TIPO.Rule = rint | rfloat | rstring | rchar | rbool; RERROR.Rule = rerror + flecha + ER + flecha + rerror + apar + yyline + coma + yyrow + coma + yytext + cpar + fin | id + flecha + ER + flecha + rerror + apar + yyline + coma + yyrow + coma + yytext + cpar + fin; /*************** Precedencia y Asociatividad ***************/ //RegisterOperators(1, or, and); //RegisterOperators(2, muchos, nada_muchos, nada); /*************** Errores ***************/ CODIGO.ErrorRule = SyntaxError + CODIGO; LISTA.ErrorRule = SyntaxError + LISTA; RESERVADAS.ErrorRule = SyntaxError + RESERVADAS; /*************** Eliminación ***************/ this.MarkPunctuation("%%", "->", ":", ";", ",", "~", "(", ")", "[", "]", "CONJ", "RESERV", "retorno"); this.MarkTransient(CUERPO, SENTENCIA, SIMBOLO, RESERVAR, METODO, TIPO); LanguageFlags = LanguageFlags.CreateAst; }
public Grammar() : base(caseSensitive: false) { #region Lexical structure //COMENTARIOS CommentTerminal LINE_COMMENT = new CommentTerminal("LINE_COMMENT", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); CommentTerminal MULTI_LINE_COMMENT = new CommentTerminal("MULTI_LINE_COMMENT", "(*", "*)"); CommentTerminal MULTI_LINE_COMMENT_LLAVE = new CommentTerminal("MULTI_LINE_COMMENT_LLAVE", "{", "}"); NonGrammarTerminals.Add(LINE_COMMENT); NonGrammarTerminals.Add(MULTI_LINE_COMMENT); NonGrammarTerminals.Add(MULTI_LINE_COMMENT_LLAVE); #endregion #region ER var REAL = new RegexBasedTerminal("REAL", "[0-9]+[.][0-9]+"); var NUMERO = new NumberLiteral("NUMERO"); //var IDENTIFIER = new IdentifierTerminal("IDENTIFIER", "[_a-zA-Z][_a-zA-Z0-9]"); var IDENTIFIER = TerminalFactory.CreateCSharpIdentifier("IDENTIFIER"); var IDENTIFIER_ARRAY_TYPE = TerminalFactory.CreateCSharpIdentifier("IDENTIFIER_ARRAY_TYPE"); var CADENA = new StringLiteral("CADENA", "\'"); #endregion #region Terminales var PUNTO_COMA = ToTerm(";", "TK_PUNTO_COMA"); var PUNTO = ToTerm(".", "TK_PUNTO"); var COMA = ToTerm(",", "TK_COMA"); var DOS_PUNTOS = ToTerm(":", "TK_DOS_PUNTOS"); var PAR_IZQ = ToTerm("(", "TK_PAR_IZQ"); var PAR_DER = ToTerm(")", "TK_PAR_DER"); var COR_IZQ = ToTerm("[", "TK_COR_IZQ"); var COR_DER = ToTerm("]", "TK_COR_DER"); //Aritmethic var PLUS = ToTerm("+", "TK_PLUS"); var MIN = ToTerm("-", "TK_MIN"); var POR = ToTerm("*", "TK_POR"); var DIVI = ToTerm("/", "TK_DIVI"); var MODULE = ToTerm("%", "TK_MODULE"); //Logic var AND = ToTerm("and", "TK_AND"); var OR = ToTerm("or", "TK_OR"); var NOT = ToTerm("not", "TK_NOT"); //Relational var HIGHER = ToTerm(">", "TK_HIGHER"); var LESS = ToTerm("<", "TK_LESS"); var HIGHER_EQUAL = ToTerm(">=", "TK_HIGHER_EQUAL"); var LESS_EQUAL = ToTerm("<=", "TK_LESS_EQUAL"); var EQUALS = ToTerm("=", "TK_EQUALS"); var DISCTINCT = ToTerm("<>", "TK_DISCTINCT"); //Reservadas var RESERV_INT = ToTerm("integer", "RESERV_INT"); var RESERV_STR = ToTerm("string", "RESERV_STR"); var RESERV_REAL = ToTerm("real", "RESERV_REAL"); var RESERV_BOL = ToTerm("boolean", "RESERV_BOL"); var RESERV_OBJ = ToTerm("object", "RESERV_OBJ"); var RESERV_PROGRAM = ToTerm("program", "RESERV_PROGRAM"); var RESERV_VAR = ToTerm("var", "RESERV_VAR"); var RESERV_BEGIN = ToTerm("begin", "RESERV_BEGIN"); var RESERV_END = ToTerm("end", "RESERV_END"); var RESERV_CONST = ToTerm("const", "RESERV_CONST"); var RESERV_TRUE = ToTerm("true", "RESERV_TRUE"); var RESERV_FALSE = ToTerm("false", "RESERV_FALSE"); #region ARRAYS Y TYPES TERMINALES var RESERV_TYPE = ToTerm("type", "RESERV_TYPE"); var RESERV_ARRAY = ToTerm("array", "RESERV_ARRAY"); var RESERV_OF = ToTerm("of", "RESERV_OF"); #endregion #region IF TERMINALES var RESERV_IF = ToTerm("if", "RESERV_IF"); var RESERV_THEN = ToTerm("then", "RESERV_THEN"); var RESERV_ELSE = ToTerm("else", "RESERV_ELSE"); #endregion #region CASE TERMINALES var RESERV_CASE = ToTerm("case", "RESERV_CASE"); #endregion #region WHILE TERMINALES var RESERV_WHILE = ToTerm("while", "RESERV_WHILE"); var RESERV_DO = ToTerm("do", "RESERV_DO"); #endregion #region REPEAT TERMINALES var RESERV_REPEAT = ToTerm("repeat", "RESERV_REPEAT"); var RESERV_UNTIL = ToTerm("until", "RESERV_UNTIL"); #endregion #region FOR TERMINALES var RESERV_FOR = ToTerm("for", "RESERV_FOR"); var RESERV_TO = ToTerm("to", "RESERV_TO"); var RESERV_DOWN = ToTerm("downto", "RESERV_DOWN"); var RESERV_BREAK = ToTerm("break", "RESERV_BREAK"); var RESERV_CONTINUE = ToTerm("continue", "RESERV_CONTINUE"); #endregion #region FUNCTION Y PROCEDURE TERMINALES var RESERV_FUNCTION = ToTerm("function", "RESERV_FUNCTION"); var RESERV_PROCEDURE = ToTerm("procedure", "RESERV_PROCEDURE"); #endregion #region FUNCIONES NATIVAS TERMINALES var RESERV_WRITE = ToTerm("write", "RESERV_WRITE"); var RESERV_WRITEN = ToTerm("writeln", "RESERV_WRITEN"); var RESERV_EXIT = ToTerm("exit", "RESERV_EXIT"); #endregion RegisterOperators(1, Associativity.Left, PLUS, MIN); RegisterOperators(2, Associativity.Left, POR, DIVI); RegisterOperators(3, Associativity.Left, MODULE); RegisterOperators(4, Associativity.Left, HIGHER_EQUAL, LESS_EQUAL, LESS, HIGHER); RegisterOperators(5, Associativity.Left, EQUALS, DISCTINCT); RegisterOperators(6, Associativity.Left, AND, OR, NOT); RegisterOperators(7, Associativity.Left, PAR_IZQ, PAR_DER); #endregion #region No Terminales NonTerminal init = new NonTerminal("init"); NonTerminal INSTRUCTION = new NonTerminal("INSTRUCTION"); NonTerminal INSTRUCTIONS = new NonTerminal("INSTRUCTIONS"); NonTerminal INSTRUCTIONS_BODY = new NonTerminal("INSTRUCTIONS_BODY"); NonTerminal PROGRAM_BODY = new NonTerminal("PROGRAM_BODY", "PROGRAM_BODY"); NonTerminal start = new NonTerminal("start"); #region EXPLOGICA NonTerminal EXPRESION = new NonTerminal("EXPRESION", "EXPRESION"); NonTerminal EXPRESION_PRIMA = new NonTerminal("EXPRESION_PRIMA", "EXPRESION_PRIMA"); NonTerminal EXPLOGICA = new NonTerminal("EXPLOGICA", "EXPLOGICA"); NonTerminal EXPLOGICA_PRIMA = new NonTerminal("EXPLOGICA_PRIMA", "EXPLOGICA_PRIMA"); NonTerminal EXPRELACIONAL = new NonTerminal("EXPRELACIONAL", "EXPRELACIONAL"); NonTerminal EXPRELACIONAL_PRIMA = new NonTerminal("EXPRELACIONAL_PRIMA", "EXPRELACIONAL_PRIMA"); NonTerminal TERMINO = new NonTerminal("TERMINO", "TERMINO"); NonTerminal TERMINO_PRIMA = new NonTerminal("TERMINO_PRIMA ", "TERMINO_PRIMA"); NonTerminal FACTOR = new NonTerminal("FACTOR", "FACTOR"); NonTerminal DATA_TYPE = new NonTerminal("DATA_TYPE", "DATA_TYPE"); NonTerminal ID_TIPE = new NonTerminal("ID_TIPE", "ID_TIPE"); #endregion #region VAR Y CONST NonTerminal DECLARATION_LIST = new NonTerminal("DECLARATION_LIST", "DECLARATION_LIST"); NonTerminal VAR_DECLARATION = new NonTerminal("VAR_DECLARATION", "VAR_DECLARATION"); NonTerminal CONST_DECLARATION = new NonTerminal("CONST_DECLARATION", "CONST_DECLARATION"); NonTerminal DECLARATION_BODY = new NonTerminal("DECLARATION_BODY", "DECLARATION_BODY"); NonTerminal MORE_ID = new NonTerminal("MORE_ID", "MORE_ID"); NonTerminal ASSIGNATION = new NonTerminal("ASSIGNATION", "ASSIGNATION"); NonTerminal VAR_ASSIGNATE = new NonTerminal("VAR_ASSIGNATE", "VAR_ASSIGNATE"); NonTerminal VAR_ASSIGNATE_EXP = new NonTerminal("VAR_ASSIGNATE_EXP", "VAR_ASSIGNATE_EXP"); #endregion #region ARRAY Y TYPES NO TERMINALES NonTerminal TYPE_LIST = new NonTerminal("TYPE_LIST", "TYPE_LIST"); NonTerminal TYPE = new NonTerminal("TYPE", "TYPE"); NonTerminal TYPE_P = new NonTerminal("TYPE_P", "TYPE_P"); NonTerminal ARRAY = new NonTerminal("ARRAY", "ARRAY"); NonTerminal OBJECT = new NonTerminal("OBJECT", "OBJECT"); NonTerminal MORE_ARRAY = new NonTerminal("MORE_ARRAY", "MORE_ARRAY"); NonTerminal MORE_ACCES = new NonTerminal("MORE_ACCES", "MORE_ACCES"); #endregion #region IF-THEN NO TERMINALES NonTerminal IFTHEN = new NonTerminal("IF-THEN", "IF-THEN"); NonTerminal IF_SENTENCE = new NonTerminal("IF_SENTENCE", "IF_SENTENCE"); NonTerminal ELIF = new NonTerminal("ELIF", "ELIF"); #endregion #region CASE NO TERMINALES NonTerminal SENTENCE_CASE = new NonTerminal("SENTENCE_CASE", "SENTENCE_CASE"); NonTerminal CASE_ELSE = new NonTerminal("CASE_ELSE", "CASE_ELSE"); NonTerminal CASES = new NonTerminal("CASES", "CASES"); NonTerminal CASE = new NonTerminal("CASE", "CASE"); #endregion #region WHILE DO NonTerminal WHILE = new NonTerminal("WHILE", "WHILE"); #endregion #region REPEAT UNTIL NonTerminal REPEAT_UNTIL = new NonTerminal("REPEAT_UNTIL", "REPEAT_UNTIL"); NonTerminal CONTINUE = new NonTerminal("CONTINUE", "CONTINUE"); #endregion #region FOR NonTerminal FOR = new NonTerminal("FOR", "FOR"); NonTerminal TODOWN = new NonTerminal("TODOWN", "TODOWN"); NonTerminal BREAK = new NonTerminal("BREAK", "BREAK"); #endregion #region FUNCIONES NATIVAS NO TERMINALES NonTerminal WRITE = new NonTerminal("WRITE", "WRITE"); NonTerminal WRHITE_PARAMETER = new NonTerminal("WRHITE_PARAMETER", "WRHITE_PARAMETER"); NonTerminal MORE_WRHITE_PARAMETER = new NonTerminal("WRHITE_PARAMETER", "WRHITE_PARAMETER"); NonTerminal EXIT = new NonTerminal("EXIT", "EXIT"); NonTerminal EXIT_EXP = new NonTerminal("EXIT_EXP", "EXIT_EXP"); #endregion #region FUNCIONS NO TERMINALES NonTerminal FUNCTION_LIST = new NonTerminal("FUNCTION_LIST", "FUNCTION_LIST"); NonTerminal FUNCTION = new NonTerminal("FUNCTION", "FUNCTION"); NonTerminal PARAMETER = new NonTerminal("PARAMETER", "PARAMETER"); NonTerminal PARAMETER_BODY = new NonTerminal("PARAMETER_BODY", "PARAMETER_BODY"); NonTerminal PARAMETER_END = new NonTerminal("PARAMETER_END", "PARAMETER_END"); NonTerminal CALL = new NonTerminal("CALL", "CALL"); NonTerminal CALL_FUNCTION_PROCEDURE = new NonTerminal("CALL_FUNCTION_PROCEDURE", "CALL_FUNCTION_PROCEDURE"); NonTerminal CALL_PARAMETERS = new NonTerminal("CALL_PARAMETERS", "CALL_PARAMETERS"); NonTerminal DECLARATION_LIST_HIJA = new NonTerminal("DECLARATION_LIST", "DECLARATION_LIST"); //NonTerminal ARGUMENTS = new NonTerminal("ARGUMENTS", "ARGUMENTS"); //NonTerminal REFERENCIA_VALOR = new NonTerminal("REFERENCIA_VALOR", "REFERENCIA_VALOR"); #endregion #endregion #region Gramatica init.Rule = start; start.Rule = RESERV_PROGRAM + IDENTIFIER + PUNTO_COMA + PROGRAM_BODY; PROGRAM_BODY.Rule = TYPE_LIST + DECLARATION_LIST + FUNCTION_LIST + INSTRUCTIONS_BODY + PUNTO; INSTRUCTIONS_BODY.Rule = RESERV_BEGIN + INSTRUCTIONS + RESERV_END ; INSTRUCTIONS.Rule = MakePlusRule(INSTRUCTIONS, INSTRUCTION); INSTRUCTION.Rule = VAR_ASSIGNATE | IFTHEN | SENTENCE_CASE | WHILE | REPEAT_UNTIL | FOR | BREAK | CONTINUE | WRITE | CALL | EXIT | TYPE ; INSTRUCTION.ErrorRule = SyntaxError + PUNTO_COMA | SyntaxError + RESERV_END ; #region DECLARACION & ASIGNACION DECLARATION_LIST.Rule = RESERV_VAR + IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION + DECLARATION_LIST | RESERV_CONST + IDENTIFIER + EQUALS + EXPLOGICA + PUNTO_COMA + CONST_DECLARATION + DECLARATION_LIST | Empty ; DECLARATION_LIST.ErrorRule = SyntaxError + PUNTO_COMA; VAR_DECLARATION.Rule = IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION | Empty ; CONST_DECLARATION.Rule = IDENTIFIER + EQUALS + EXPLOGICA + PUNTO_COMA + CONST_DECLARATION | Empty ; DECLARATION_BODY.Rule = DOS_PUNTOS + DATA_TYPE + ASSIGNATION + PUNTO_COMA | COMA + IDENTIFIER + MORE_ID + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA ; ASSIGNATION.Rule = EQUALS + EXPLOGICA | Empty; ; MORE_ID.Rule = COMA + IDENTIFIER + MORE_ID | Empty ; VAR_ASSIGNATE.Rule = IDENTIFIER + VAR_ASSIGNATE_EXP ; VAR_ASSIGNATE_EXP.Rule = DOS_PUNTOS + EQUALS + EXPLOGICA + PUNTO_COMA | COR_IZQ + EXPLOGICA + COR_DER + MORE_ACCES + DOS_PUNTOS + EQUALS + EXPLOGICA + PUNTO_COMA ; MORE_ACCES.Rule = COR_IZQ + EXPLOGICA + COR_DER + MORE_ACCES | Empty ; DATA_TYPE.Rule = RESERV_REAL | RESERV_STR | IDENTIFIER_ARRAY_TYPE | RESERV_INT | RESERV_BOL | IDENTIFIER ; #endregion #region TYPES Y ARRAY TYPE_LIST.Rule = TYPE + TYPE_LIST | Empty ; TYPE.Rule = RESERV_TYPE + IDENTIFIER_ARRAY_TYPE + EQUALS + TYPE_P; TYPE_P.Rule = OBJECT | ARRAY ; ARRAY.Rule = RESERV_ARRAY + COR_IZQ + EXPLOGICA + PUNTO + PUNTO + EXPLOGICA + COR_DER + RESERV_OF + MORE_ARRAY + PUNTO_COMA; ; MORE_ARRAY.Rule = DATA_TYPE | RESERV_ARRAY + COR_IZQ + EXPLOGICA + PUNTO + PUNTO + EXPLOGICA + COR_DER + RESERV_OF + MORE_ARRAY; ; OBJECT.Rule = RESERV_OBJ + DECLARATION_LIST + RESERV_END + PUNTO_COMA; #endregion #region EXPRESION EXPLOGICA.Rule = EXPRELACIONAL + EXPLOGICA_PRIMA | NOT + EXPRELACIONAL + EXPLOGICA_PRIMA; EXPLOGICA_PRIMA.Rule = AND + EXPRELACIONAL + EXPLOGICA_PRIMA | OR + EXPRELACIONAL + EXPLOGICA_PRIMA | Empty ; EXPRELACIONAL.Rule = EXPRESION + EXPRELACIONAL_PRIMA; EXPRELACIONAL_PRIMA.Rule = LESS + EXPRESION + EXPRELACIONAL_PRIMA | HIGHER + EXPRESION + EXPRELACIONAL_PRIMA | LESS_EQUAL + EXPRESION + EXPRELACIONAL_PRIMA | HIGHER_EQUAL + EXPRESION + EXPRELACIONAL_PRIMA | EQUALS + EXPRESION + EXPRELACIONAL_PRIMA | DISCTINCT + EXPRESION + EXPRELACIONAL_PRIMA | Empty ; EXPRESION.Rule = TERMINO + EXPRESION_PRIMA; EXPRESION_PRIMA.Rule = PLUS + TERMINO + EXPRESION_PRIMA | MIN + TERMINO + EXPRESION_PRIMA | Empty ; TERMINO.Rule = FACTOR + TERMINO_PRIMA; TERMINO_PRIMA.Rule = POR + FACTOR + TERMINO_PRIMA | DIVI + FACTOR + TERMINO_PRIMA | MODULE + FACTOR + TERMINO_PRIMA | Empty ; FACTOR.Rule = PAR_IZQ + EXPLOGICA + PAR_DER | REAL | CADENA | NUMERO | IDENTIFIER + ID_TIPE | RESERV_TRUE | RESERV_FALSE | CALL_FUNCTION_PROCEDURE | MIN + FACTOR ; ID_TIPE.Rule = COR_IZQ + EXPLOGICA + COR_DER + MORE_ACCES | Empty; /*EXPRESION.Rule * = EXPRESION + PLUS + EXPRESION | EXPRESION + MIN + EXPRESION | EXPRESION + POR + EXPRESION | EXPRESION + DIVI + EXPRESION | EXPRESION + MODULE + EXPRESION | EXPRESION + LESS + EXPRESION | EXPRESION + HIGHER + EXPRESION | EXPRESION + LESS_EQUAL + EXPRESION | EXPRESION + HIGHER_EQUAL + EXPRESION | EXPRESION + EQUALS + EXPRESION | EXPRESION + DISCTINCT + EXPRESION | EXPRESION + AND + EXPRESION | EXPRESION + OR + EXPRESION | NOT + EXPRESION | CALL_FUNCTION_PROCEDURE | IDENTIFIER | NUMERO | CADENA | REAL | RESERV_TRUE | RESERV_FALSE | PAR_IZQ + EXPRESION + PAR_DER | ;*/ #endregion #endregion #region SENTENCIAS DE CONTROL #region IF-THEN IFTHEN.Rule = RESERV_IF + EXPLOGICA + RESERV_THEN + IF_SENTENCE + ELIF; IF_SENTENCE.Rule = INSTRUCTIONS_BODY | Empty ; ELIF.Rule = RESERV_ELSE + IF_SENTENCE + PUNTO_COMA | RESERV_ELSE + IFTHEN | Empty ; #endregion #region CASE SENTENCE_CASE.Rule = RESERV_CASE + EXPLOGICA + RESERV_OF + CASES + CASE_ELSE + RESERV_END + PUNTO_COMA; CASES.Rule = CASE + CASES | Empty ; CASE.Rule = EXPLOGICA + DOS_PUNTOS + INSTRUCTIONS; CASE_ELSE.Rule = RESERV_ELSE + INSTRUCTIONS | Empty ; #endregion #region WHILE DO WHILE.Rule = RESERV_WHILE + EXPLOGICA + RESERV_DO + INSTRUCTIONS_BODY + PUNTO_COMA; #endregion #region REPEAT UNTIL REPEAT_UNTIL.Rule = RESERV_REPEAT + INSTRUCTIONS + RESERV_UNTIL + EXPLOGICA + PUNTO_COMA; #endregion #region FOR FOR.Rule = RESERV_FOR + IDENTIFIER + DOS_PUNTOS + EQUALS + EXPLOGICA + TODOWN + EXPLOGICA + RESERV_DO + INSTRUCTIONS_BODY + PUNTO_COMA ; TODOWN.Rule = RESERV_TO | RESERV_DOWN ; #endregion #endregion #region SENTENCIAS DE TRANSFERENCIA CONTINUE.Rule = RESERV_CONTINUE + PUNTO_COMA ; BREAK.Rule = RESERV_BREAK + PUNTO_COMA ; #endregion #region FUNCIONES Y PROCEDIMIENTOS FUNCTION_LIST.Rule = RESERV_FUNCTION + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + DOS_PUNTOS + DATA_TYPE + PUNTO_COMA + DECLARATION_LIST_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCTION_LIST | RESERV_PROCEDURE + IDENTIFIER + PAR_IZQ + PARAMETER + PAR_DER + PUNTO_COMA + DECLARATION_LIST_HIJA + INSTRUCTIONS_BODY + PUNTO_COMA + FUNCTION_LIST | Empty ; FUNCTION_LIST.ErrorRule = SyntaxError + PUNTO_COMA; PARAMETER.Rule = RESERV_VAR + IDENTIFIER + PARAMETER_BODY + DOS_PUNTOS + DATA_TYPE + PARAMETER_END | IDENTIFIER + PARAMETER_BODY + DOS_PUNTOS + DATA_TYPE + PARAMETER_END | Empty; PARAMETER_BODY.Rule = COMA + IDENTIFIER + PARAMETER_BODY | Empty ; PARAMETER_END.Rule = PUNTO_COMA + PARAMETER | Empty ; CALL.Rule = IDENTIFIER + PAR_IZQ + CALL_PARAMETERS + PAR_DER + PUNTO_COMA; CALL_PARAMETERS.Rule = EXPLOGICA + CALL_PARAMETERS | COMA + EXPLOGICA + CALL_PARAMETERS | Empty ; CALL_FUNCTION_PROCEDURE.Rule = IDENTIFIER + PAR_IZQ + CALL_PARAMETERS + PAR_DER; DECLARATION_LIST_HIJA.Rule = RESERV_VAR + IDENTIFIER + DECLARATION_BODY + VAR_DECLARATION + DECLARATION_LIST_HIJA | RESERV_CONST + IDENTIFIER + EQUALS + EXPLOGICA + PUNTO_COMA + CONST_DECLARATION + DECLARATION_LIST_HIJA | Empty ; #endregion #region FUNCIONES NATIVAS WRITE.Rule = RESERV_WRITE + PAR_IZQ + WRHITE_PARAMETER + PAR_DER + PUNTO_COMA | RESERV_WRITEN + PAR_IZQ + WRHITE_PARAMETER + PAR_DER + PUNTO_COMA ; WRHITE_PARAMETER.Rule = EXPLOGICA + MORE_WRHITE_PARAMETER | Empty ; MORE_WRHITE_PARAMETER.Rule = COMA + EXPLOGICA + MORE_WRHITE_PARAMETER | Empty ; EXIT.Rule = RESERV_EXIT + PAR_IZQ + EXIT_EXP + PAR_DER + PUNTO_COMA; EXIT_EXP.Rule = EXPLOGICA | Empty ; #endregion #region Preferencias this.Root = init; #endregion }
public Gramatica() : base(caseSensitive: true) { //---------------------> Comentarios CommentTerminal COMENTARIO_SIMPLE = new CommentTerminal("comentario_simple", "!!", "\n", "\r\n"); CommentTerminal COMENTARIO_MULT = new CommentTerminal("comentario_mult", "<<", ">>"); NonGrammarTerminals.Add(COMENTARIO_SIMPLE); NonGrammarTerminals.Add(COMENTARIO_MULT); /*--------------------Definir Palabras Reservadas ----------------*/ MarkReservedWords("Importar"); MarkReservedWords("Definir"); MarkReservedWords("Double"); MarkReservedWords("String"); MarkReservedWords("Bool"); MarkReservedWords("Int"); MarkReservedWords("Char"); MarkReservedWords("Retorno"); MarkReservedWords("Vacio"); MarkReservedWords("Principal"); MarkReservedWords("Si"); MarkReservedWords("Sino"); MarkReservedWords("Selecciona"); MarkReservedWords("Defecto"); MarkReservedWords("Para"); MarkReservedWords("Hasta"); MarkReservedWords("Mientras"); MarkReservedWords("Detener"); MarkReservedWords("Continuar"); MarkReservedWords("Mostrar"); MarkReservedWords("DibujarAST"); MarkReservedWords("DibujarEXP"); MarkReservedWords("DibujarTS"); /*--------------------- (Opcional)Definir variables para palabras reservadas--*/ var mas = ToTerm("+"); var punto = ToTerm("."); var menos = ToTerm("-"); var por = ToTerm("*"); var division = ToTerm("/"); var potencia = ToTerm("^"); var igual = ToTerm("="); var porc = ToTerm("%"); var allave = ToTerm("{"); var cllave = ToTerm("}"); var apar = ToTerm("("); var cpar = ToTerm(")"); var coma = ToTerm(","); var dospuntos = ToTerm(":"); var puntocoma = ToTerm(";"); var llavea = ToTerm("{"); var llavec = ToTerm("}"); var trues = ToTerm("true"); var falses = ToTerm("false"); /*-------------relacionales------------------*/ var igualigual = ToTerm("=="); var diferente = ToTerm("!="); var mayor = ToTerm(">"); var menor = ToTerm("<"); var mayorigual = ToTerm(">="); var menorigual = ToTerm("<="); var incerteza = ToTerm("~"); var masmas = ToTerm("++"); var menosmenos = ToTerm("--"); /*--------------------expresiones logicas---------*/ var or = ToTerm("||"); var and = ToTerm("&&"); var not = ToTerm("!"); var xor = ToTerm("|&"); /*----------------------palabras-------*/ var importar = ToTerm("Importar"); var definir = ToTerm("Definir"); var vadouble = ToTerm("Double"); var vastring = ToTerm("String"); var varint = ToTerm("Int"); var vabool = ToTerm("Bool"); var vachar = ToTerm("Char"); var retorno = ToTerm("Retorno"); var vacio = ToTerm("Vacio"); var principal = ToTerm("Principal"); var si = ToTerm("Si"); var sino = ToTerm("Sino"); var selecciona = ToTerm("Selecciona"); var defecto = ToTerm("Defecto"); var para = ToTerm("Para"); var hasta = ToTerm("Hasta"); var mientras = ToTerm("Mientras"); var detener = ToTerm("Detener"); var continuar = ToTerm("Continuar"); var mostrar = ToTerm("Mostrar"); var dibast = ToTerm("DibujarAST"); var dibexp = ToTerm("DibujarEXP"); var dibts = ToTerm("DibujarTS"); /*--------------------- No Terminales --------*/ var INICIO = new NonTerminal("INICIO"); var LISTA = new NonTerminal("LISTA"); var ESTRUC = new NonTerminal("ESTRUC"); var DECLARACION = new NonTerminal("DECLARACION"); var DECLARACION2 = new NonTerminal("DECLARACION2"); var EXPRESION = new NonTerminal("EXPRESION"); var EXPRESION2 = new NonTerminal("EXPRESION2"); var CTIPO = new NonTerminal("CTIPO"); var VARIOS = new NonTerminal("VARIOS"); var ESTRUCTURA = new NonTerminal("ESTRUCTURA"); var ENCABEZADO = new NonTerminal("ENCABEZADO"); var TIPO = new NonTerminal("TIPO"); var CUERPO = new NonTerminal("CUERPO"); var ASIGNACION = new NonTerminal("ASIGNACION"); var ASIGNACION2 = new NonTerminal("ASIGNACION2"); var FUN = new NonTerminal("FUN"); var METOD = new NonTerminal("METOD"); var LISTA2 = new NonTerminal("LISTA2"); var DECLAPARA = new NonTerminal("DECLAPARA"); var PARAMETROS = new NonTerminal("PARAMETROS"); var ESTRUC2 = new NonTerminal("ESTRUC2"); var FUNPRIN = new NonTerminal("FUNPRIN"); var LISTA3 = new NonTerminal("LISTA3"); var ESTRUC3 = new NonTerminal("ESTRUC3"); var LLAMADAS = new NonTerminal("LLAMADAS"); var RETORN = new NonTerminal("RETORN"); var SENTSI = new NonTerminal("SENTSI"); var SENTSINO = new NonTerminal("SENTSINO"); var SENTHASTA = new NonTerminal("SENTHASTA"); var SENTMIENTRAS = new NonTerminal("SENTMIENTRAS"); var SENTPARA = new NonTerminal("SENTPARA"); var SENTSELECCIONA = new NonTerminal("SENTSELECCIONA"); var CASO = new NonTerminal("CASO"); var DEFECT = new NonTerminal("DEFECT"); var PRINT = new NonTerminal("PRINT"); var DIBAST = new NonTerminal("DIBAST"); var DIBEXP = new NonTerminal("DIBEXP"); var DIBTS = new NonTerminal("DIBTS"); var LLAMAR = new NonTerminal("LLAMAR"); var VARIOS2 = new NonTerminal("VARIOS2"); //---------------------> Terminales var tString = new StringLiteral("tString", "\"", StringOptions.AllowsDoubledQuote); var tchar = new StringLiteral("tchar", "\'", StringOptions.AllowsDoubledQuote); NumberLiteral numero = TerminalFactory.CreateCSharpNumber("numero"); IdentifierTerminal id = TerminalFactory.CreateCSharpIdentifier("id"); //---------------------> No Terminal Inicial this.Root = INICIO; //---------------------> Producciones ------------------------------------------ INICIO.Rule = ENCABEZADO + LISTA; ENCABEZADO.Rule = importar + id + punto + id + puntocoma + ENCABEZADO | definir + CTIPO + puntocoma + ENCABEZADO | Empty; LISTA.Rule = MakeStarRule(LISTA, ESTRUC); /*----------------------lo que puede llevar todo el programa-----------------*/ ESTRUC.Rule = DECLARACION | ASIGNACION | FUN | METOD | FUNPRIN ; /*---------------------------lo que llevan las funciones y metodos----------------------*/ LISTA2.Rule = MakeStarRule(LISTA2, ESTRUC2); ESTRUC2.Rule = DECLARACION2 | ASIGNACION2 | LLAMADAS | RETORN | SENTSI | SENTPARA | SENTMIENTRAS | SENTHASTA | SENTSELECCIONA | DIBEXP | DIBAST | DIBTS | PRINT; /*----------------------------puede llevar funcion principal y otros ---------*/ LISTA3.Rule = MakeStarRule(LISTA3, ESTRUC3); ESTRUC3.Rule = DECLARACION2 | ASIGNACION2 | LLAMADAS | detener + puntocoma | continuar + puntocoma | SENTSI | SENTPARA | SENTMIENTRAS | SENTHASTA | SENTSELECCIONA | DIBEXP | DIBAST | DIBTS | PRINT | RETORN; /*------------------------------DECLArACION y asignacion---------------------------*/ DECLARACION.Rule = TIPO + VARIOS + igual + EXPRESION + puntocoma | TIPO + VARIOS + puntocoma; ASIGNACION.Rule = id + igual + EXPRESION + puntocoma; DECLARACION2.Rule = TIPO + VARIOS + igual + EXPRESION + puntocoma | TIPO + VARIOS + puntocoma; ASIGNACION2.Rule = id + igual + EXPRESION + puntocoma; VARIOS.Rule = CTIPO + coma + VARIOS | CTIPO; VARIOS2.Rule = coma + EXPRESION + VARIOS2 | Empty; CTIPO.Rule = tString | tchar | numero | id; TIPO.Rule = vabool | vachar | vadouble | varint | vastring; /*---------------------metodos funciones----------------------*/ FUN.Rule = TIPO + id + apar + DECLAPARA + cpar + allave + LISTA2 + cllave; METOD.Rule = vacio + id + apar + DECLAPARA + cpar + allave + LISTA2 + cllave; PARAMETROS.Rule = EXPRESION | EXPRESION + coma + PARAMETROS | Empty; DECLAPARA.Rule = TIPO + id + coma + DECLAPARA | TIPO + id | Empty; LLAMAR.Rule = id + apar + PARAMETROS + cpar; /*-------------------funcion principal----------------------*/ FUNPRIN.Rule = vacio + principal + apar + cpar + allave + LISTA3 + cllave; /*--------------llamdas a funciones ----------*/ LLAMADAS.Rule = id + apar + PARAMETROS + cpar + puntocoma; /*----------------retornar-------------*/ RETORN.Rule = retorno + EXPRESION + puntocoma | retorno + puntocoma; /*----------------------sentencia si---------------*/ SENTSI.Rule = si + apar + EXPRESION + cpar + allave + LISTA3 + cllave + SENTSINO; SENTSINO.Rule = sino + allave + LISTA3 + cllave | Empty; /*-----------------sentencia selecciona-------------*/ SENTSELECCIONA.Rule = selecciona + apar + EXPRESION + cpar + llavea + CASO + DEFECT + cllave; CASO.Rule = EXPRESION + dospuntos + LISTA3 + CASO | Empty; DEFECT.Rule = defecto + dospuntos + LISTA3 | Empty; /*----------------------sentencia para-------------------*/ SENTPARA.Rule = para + apar + vadouble + id + igual + EXPRESION + puntocoma + EXPRESION + puntocoma + masmas + cpar + allave + LISTA3 + cllave | para + apar + vadouble + id + igual + EXPRESION + puntocoma + EXPRESION + puntocoma + menosmenos + cpar + allave + LISTA3 + cllave; /*-------------------------sentencia hasta ------------*/ SENTHASTA.Rule = hasta + apar + EXPRESION + cpar + allave + LISTA3 + cllave; /*------------sentencias mientras ---------------*/ SENTMIENTRAS.Rule = mientras + apar + EXPRESION + cpar + allave + LISTA3 + cllave; /*------------------------mostrar----*/ PRINT.Rule = mostrar + apar + tString + VARIOS2 + cpar + puntocoma; /*----------------funcion dibujar ast-----------*/ DIBAST.Rule = dibast + apar + id + cpar + puntocoma; /*--------------------funcion dibujar exp------*/ DIBEXP.Rule = dibexp + apar + EXPRESION2 + cpar + puntocoma; /*------------------------------------------dibujar ts-------------------*/ DIBTS.Rule = dibts + apar + cpar + puntocoma; EXPRESION.Rule = EXPRESION + or + EXPRESION | EXPRESION + and + EXPRESION | not + EXPRESION | EXPRESION + xor + EXPRESION | EXPRESION + igualigual + EXPRESION | EXPRESION + diferente + EXPRESION | EXPRESION + mayor + EXPRESION | EXPRESION + menor + EXPRESION | EXPRESION + mayorigual + EXPRESION | EXPRESION + menorigual + EXPRESION | EXPRESION + mas + EXPRESION | EXPRESION + menos + EXPRESION | EXPRESION + por + EXPRESION | EXPRESION + potencia + EXPRESION | EXPRESION + division + EXPRESION | EXPRESION + incerteza + EXPRESION | apar + EXPRESION + cpar | EXPRESION + porc + EXPRESION | id | LLAMAR | numero | tString | tchar | trues | falses | menos + EXPRESION; // | distinto + EXPRESION /*-----------------para dibujar expresion-----------------*/ EXPRESION2.Rule = EXPRESION2 + or + EXPRESION2 | EXPRESION2 + and + EXPRESION2 | not + EXPRESION2 | EXPRESION2 + xor + EXPRESION2 | EXPRESION2 + diferente + EXPRESION2 | EXPRESION2 + mayor + EXPRESION2 | EXPRESION2 + menor + EXPRESION2 | EXPRESION2 + mayorigual + EXPRESION2 | EXPRESION2 + menorigual + EXPRESION2 | EXPRESION2 + mas + EXPRESION2 | EXPRESION2 + menos + EXPRESION2 | EXPRESION2 + por + EXPRESION2 | EXPRESION2 + potencia + EXPRESION2 | EXPRESION2 + division + EXPRESION2 | EXPRESION2 + incerteza + EXPRESION2 | apar + EXPRESION2 + cpar | EXPRESION2 + igualigual + EXPRESION2 | EXPRESION2 + porc + EXPRESION2 | id | LLAMAR | numero | tString | tchar | trues | falses | menos + EXPRESION; // | distinto + EXPRESION //---------------------> Definir Asociatividad RegisterOperators(1, Associativity.Left, "||"); //OR RegisterOperators(2, Associativity.Left, "&&"); //AND RegisterOperators(7, Associativity.Left, "!"); //NOT RegisterOperators(7, Associativity.Left, "|&"); //NOT RegisterOperators(5, Associativity.Left, "+", "-"); //MAS, MENOS RegisterOperators(6, Associativity.Left, "*", "/", "%"); //POR, DIVIDIR RegisterOperators(6, Associativity.Right, "^"); //POTENCIA ESTRUC.ErrorRule = SyntaxError + ESTRUC; ESTRUC2.ErrorRule = SyntaxError + ESTRUC2; ESTRUC3.ErrorRule = SyntaxError + ESTRUC3; }
internal BnfTerms(TerminalFactoryS TerminalFactoryS, CultureInfo cultureInfo) { if (cultureInfo.Name == "hu") { this.PROGRAM = TerminalFactoryS.CreateKeyTerm("program"); this.NAMESPACE = TerminalFactoryS.CreateKeyTerm("névtér"); this.BEGIN = TerminalFactoryS.CreateKeyTerm("eleje"); this.END = TerminalFactoryS.CreateKeyTerm("vége"); this.FUNCTION = TerminalFactoryS.CreateKeyTerm("függvény"); this.WHILE = TerminalFactoryS.CreateKeyTerm("amíg"); this.FOR = TerminalFactoryS.CreateKeyTerm("ciklus"); this.IF = TerminalFactoryS.CreateKeyTerm("ha"); this.THEN = TerminalFactoryS.CreateKeyTerm("akkor"); this.ELSE = TerminalFactoryS.CreateKeyTerm("egyébként"); this.DO = TerminalFactoryS.CreateKeyTerm("csináld"); this.RETURN = TerminalFactoryS.CreateKeyTerm("visszatér"); this.WRITE = TerminalFactoryS.CreateKeyTerm("Kiír"); this.WRITELN = TerminalFactoryS.CreateKeyTerm("KiírSor"); this.VAR = TerminalFactoryS.CreateKeyTerm("változó"); this.ASYNC = TerminalFactoryS.CreateKeyTerm("aszink", true); this.AND_OP = TerminalFactoryS.CreateKeyTerm("és", DE.BinaryOperator.And); this.OR_OP = TerminalFactoryS.CreateKeyTerm("vagy", DE.BinaryOperator.Or); this.NOT_OP = TerminalFactoryS.CreateKeyTerm("nem", DE.UnaryOperator.Not); this.INTEGER_TYPE = TerminalFactoryS.CreateKeyTerm("egész", D.Type.Integer); this.REAL_TYPE = TerminalFactoryS.CreateKeyTerm("valós", D.Type.Real); this.STRING_TYPE = TerminalFactoryS.CreateKeyTerm("karakterlánc", D.Type.String); this.CHAR_TYPE = TerminalFactoryS.CreateKeyTerm("karakter", D.Type.Char); this.BOOL_TYPE = TerminalFactoryS.CreateKeyTerm("logikai", D.Type.Bool); this.COLOR_TYPE = TerminalFactoryS.CreateKeyTerm("szín", D.Type.Color); this.DATE_TYPE = TerminalFactoryS.CreateKeyTerm("dátum", D.Type.Date); this.BOOL_CONSTANT = new BnfiTermConstant <bool>() { { "igaz", true }, { "hamis", false } }; this.COLOR_CONSTANT = new BnfiTermConstant <D.Color>() { { "szín_fekete", D.Color.Black }, { "szín_kék", D.Color.Blue }, { "szín_barna", D.Color.Brown }, { "szín_szürke", D.Color.Gray }, { "szín_zöld", D.Color.Green }, { "szín_narancs", D.Color.Orange }, { "szín_piros", D.Color.Red }, { "szín_fehér", D.Color.White }, { "szín_sárga", D.Color.Yellow } }; } else if (cultureInfo.Name == "de") { this.PROGRAM = TerminalFactoryS.CreateKeyTerm("Programm"); this.NAMESPACE = TerminalFactoryS.CreateKeyTerm("NameRaum"); this.BEGIN = TerminalFactoryS.CreateKeyTerm("Beginn"); this.END = TerminalFactoryS.CreateKeyTerm("Ende"); this.FUNCTION = TerminalFactoryS.CreateKeyTerm("Funktion"); this.WHILE = TerminalFactoryS.CreateKeyTerm("während"); this.FOR = TerminalFactoryS.CreateKeyTerm("Zyklus"); this.IF = TerminalFactoryS.CreateKeyTerm("wenn"); this.THEN = TerminalFactoryS.CreateKeyTerm("dann"); this.ELSE = TerminalFactoryS.CreateKeyTerm("sonst"); this.DO = TerminalFactoryS.CreateKeyTerm("tun"); this.RETURN = TerminalFactoryS.CreateKeyTerm("zurückholen"); this.WRITE = TerminalFactoryS.CreateKeyTerm("Schreiben"); this.WRITELN = TerminalFactoryS.CreateKeyTerm("SchreibenLeine"); this.VAR = TerminalFactoryS.CreateKeyTerm("Variable"); this.ASYNC = TerminalFactoryS.CreateKeyTerm("async", true); this.AND_OP = TerminalFactoryS.CreateKeyTerm("und", DE.BinaryOperator.And); this.OR_OP = TerminalFactoryS.CreateKeyTerm("oder", DE.BinaryOperator.Or); this.NOT_OP = TerminalFactoryS.CreateKeyTerm("nicht", DE.UnaryOperator.Not); this.INTEGER_TYPE = TerminalFactoryS.CreateKeyTerm("Ganzzahl", D.Type.Integer); this.REAL_TYPE = TerminalFactoryS.CreateKeyTerm("ReeleZahl", D.Type.Real); this.STRING_TYPE = TerminalFactoryS.CreateKeyTerm("Schnur", D.Type.String); this.CHAR_TYPE = TerminalFactoryS.CreateKeyTerm("Charakter", D.Type.Char); this.BOOL_TYPE = TerminalFactoryS.CreateKeyTerm("Boolsche", D.Type.Bool); this.COLOR_TYPE = TerminalFactoryS.CreateKeyTerm("Farbe", D.Type.Color); this.DATE_TYPE = TerminalFactoryS.CreateKeyTerm("Datum", D.Type.Date); this.BOOL_CONSTANT = new BnfiTermConstant <bool>() { { "richtig", true }, { "falsch", false } }; this.COLOR_CONSTANT = new BnfiTermConstant <D.Color>() { { "Farbe_schwarz", D.Color.Black }, { "Farbe_blau", D.Color.Blue }, { "Farbe_braun", D.Color.Brown }, { "Farbe_grau", D.Color.Gray }, { "Farbe_grün", D.Color.Green }, { "Farbe_orange", D.Color.Orange }, { "Farbe_rot", D.Color.Red }, { "Farbe_weiss", D.Color.White }, { "Farbe_gelb", D.Color.Yellow } }; } else { this.PROGRAM = TerminalFactoryS.CreateKeyTerm("program"); this.NAMESPACE = TerminalFactoryS.CreateKeyTerm("namespace"); this.BEGIN = TerminalFactoryS.CreateKeyTerm("begin"); this.END = TerminalFactoryS.CreateKeyTerm("end"); this.FUNCTION = TerminalFactoryS.CreateKeyTerm("function"); this.WHILE = TerminalFactoryS.CreateKeyTerm("while"); this.FOR = TerminalFactoryS.CreateKeyTerm("for"); this.IF = TerminalFactoryS.CreateKeyTerm("if"); this.THEN = TerminalFactoryS.CreateKeyTerm("then"); this.ELSE = TerminalFactoryS.CreateKeyTerm("else"); this.DO = TerminalFactoryS.CreateKeyTerm("do"); this.RETURN = TerminalFactoryS.CreateKeyTerm("return"); this.WRITE = TerminalFactoryS.CreateKeyTerm("Write"); this.WRITELN = TerminalFactoryS.CreateKeyTerm("WriteLn"); this.VAR = TerminalFactoryS.CreateKeyTerm("var"); this.ASYNC = TerminalFactoryS.CreateKeyTerm("async", true); this.AND_OP = TerminalFactoryS.CreateKeyTerm("and", DE.BinaryOperator.And); this.OR_OP = TerminalFactoryS.CreateKeyTerm("or", DE.BinaryOperator.Or); this.NOT_OP = TerminalFactoryS.CreateKeyTerm("not", DE.UnaryOperator.Not); this.INTEGER_TYPE = TerminalFactoryS.CreateKeyTerm("integer", D.Type.Integer); this.REAL_TYPE = TerminalFactoryS.CreateKeyTerm("real", D.Type.Real); this.STRING_TYPE = TerminalFactoryS.CreateKeyTerm("string", D.Type.String); this.CHAR_TYPE = TerminalFactoryS.CreateKeyTerm("char", D.Type.Char); this.BOOL_TYPE = TerminalFactoryS.CreateKeyTerm("boolean", D.Type.Bool); this.COLOR_TYPE = TerminalFactoryS.CreateKeyTerm("color", D.Type.Color); this.DATE_TYPE = TerminalFactoryS.CreateKeyTerm("date", D.Type.Date); this.BOOL_CONSTANT = new BnfiTermConstant <bool>() { { "True", true }, { "False", false } }; this.COLOR_CONSTANT = new BnfiTermConstant <D.Color>() { { "Color_Black", D.Color.Black }, { "Color_Blue", D.Color.Blue }, { "Color_Brown", D.Color.Brown }, { "Color_Gray", D.Color.Gray }, { "Color_Green", D.Color.Green }, { "Color_Orange", D.Color.Orange }, { "Color_Red", D.Color.Red }, { "Color_White", D.Color.White }, { "Color_Yellow", D.Color.Yellow } }; } this.DOT = TerminalFactoryS.CreateKeyTerm("."); this.LET = TerminalFactoryS.CreateKeyTerm(":="); this.SEMICOLON = TerminalFactoryS.CreateKeyTerm(";"); this.COLON = TerminalFactoryS.CreateKeyTerm(":"); this.COMMA = TerminalFactoryS.CreateKeyTerm(","); this.LEFT_PAREN = TerminalFactoryS.CreateKeyTerm("("); this.RIGHT_PAREN = TerminalFactoryS.CreateKeyTerm(")"); this.QUESTION_MARK = TerminalFactoryS.CreateKeyTerm("?"); this.ADD_OP = TerminalFactoryS.CreateKeyTerm("+", DE.BinaryOperator.Add); this.SUB_OP = TerminalFactoryS.CreateKeyTerm("-", DE.BinaryOperator.Sub); this.MUL_OP = TerminalFactoryS.CreateKeyTerm("*", DE.BinaryOperator.Mul); this.DIV_OP = TerminalFactoryS.CreateKeyTerm("/", DE.BinaryOperator.Div); this.POW_OP = TerminalFactoryS.CreateKeyTerm("^", DE.BinaryOperator.Pow); this.MOD_OP = TerminalFactoryS.CreateKeyTerm("%", DE.BinaryOperator.Mod); this.POS_OP = TerminalFactoryS.CreateKeyTerm("+", DE.UnaryOperator.Pos); this.NEG_OP = TerminalFactoryS.CreateKeyTerm("-", DE.UnaryOperator.Neg); this.EQ_OP = TerminalFactoryS.CreateKeyTerm("=", DE.BinaryOperator.Eq); this.NEQ_OP = TerminalFactoryS.CreateKeyTerm("<>", DE.BinaryOperator.Neq); this.LT_OP = TerminalFactoryS.CreateKeyTerm("<", DE.BinaryOperator.Lt); this.LTE_OP = TerminalFactoryS.CreateKeyTerm("<=", DE.BinaryOperator.Lte); this.GT_OP = TerminalFactoryS.CreateKeyTerm(">", DE.BinaryOperator.Gt); this.GTE_OP = TerminalFactoryS.CreateKeyTerm(">=", DE.BinaryOperator.Gte); // NOTE: to parse keyterms with international characters properly we need to allow international characters in identifiers as well: // CreateCSharpIdentifier creates an identifier terminal that allows internation characters // this.IDENTIFIER = TerminalFactoryS.CreateIdentifier(); this.IDENTIFIER = TerminalFactory.CreateCSharpIdentifier("identifier").IntroIdentifier(); }
public CustomDslGrammar() : base(false) { #region Terminals var Number = new NumberLiteral("number", NumberOptions.AllowSign, typeof(NumberNode)) { DefaultFloatType = TypeCode.Decimal }; var StringLiteral = new StringLiteral("string", "'", StringOptions.AllowsDoubledQuote, typeof(StringNode)); var Comma = ToTerm(","); var Not = ToTerm("NOT"); var LParen = ToTerm("("); var RParen = ToTerm(")"); var UnaryOperator = ToTerm("+") | "-" | Not; var BinaryOperator = ToTerm("+") | "-" | "*" | "/" | "%" //arithmetic | "&" | "|" | "^" //bit | "=" | ">" | "<" | ">=" | "<=" | "<>" | "AND" | "OR"; #endregion #region Non-terminals var date = new NonTerminal("date", typeof(DateNode)); var boolean = new NonTerminal("boolean", typeof(BooleanNode)); var nil = new NonTerminal("null", typeof(NilNode)); var expression = new NonTerminal("expression"); var unaryExpression = new NonTerminal("unaryExpression", typeof(UnaryExpressionNode)); var binaryExpression = new NonTerminal("binaryExpression", typeof(BinaryExpressionNode)); var functionCall = new NonTerminal("functionCall", typeof(FunctionNode)); var terminal = new NonTerminal("term"); var tuple = new NonTerminal("tuple", typeof(TupleNode)); var logicFunction = new NonTerminal("logicFunction", typeof(FunctionNode)); var mathFunction = new NonTerminal("mathFunction", typeof(FunctionNode)); var stringFunction = new NonTerminal("stringFunction", typeof(FunctionNode)); var iifFunction = new NonTerminal("iif", typeof(IifFunctionNode)); var icaseFunction = new NonTerminal("icase", typeof(IcaseFunctionNode)); var caseCondition = new NonTerminal("case", typeof(CaseConditionNode)); var caseConditionList = new NonTerminal("caselist", typeof(CaseConditionListNode)); var powerFunction = new NonTerminal("power", typeof(FunctionNode)); var minFunction = new NonTerminal("min", typeof(MinFunctionNode)); var maxFunction = new NonTerminal("max", typeof(MaxFunctionNode)); var substringFunction = new NonTerminal("substring", typeof(FunctionNode)); var concatFunction = new NonTerminal("concat", typeof(ConcatFunctionNode)); var leftFunction = new NonTerminal("left", typeof(FunctionNode)); var rightFunction = new NonTerminal("right", typeof(FunctionNode)); var fieldName = new NonTerminal("fieldName"); var expressionList = new NonTerminal("expressionList", typeof(ExpressionListNode)); var today = new NonTerminal("today", typeof(TodayNode)); var objectProperty = new NonTerminal("objectProperty", typeof(ObjectPropertyNode)); #endregion #region Expression expression.Rule = terminal | unaryExpression | binaryExpression; expressionList.Rule = MakePlusRule(expressionList, Comma, expression); #endregion #region Literals date.Rule = ToTerm("Date") + LParen + StringLiteral + RParen; boolean.Rule = ToTerm("true") | ToTerm("false") ; nil.Rule = ToTerm("null"); #endregion #region Terminals and Expressions terminal.Rule = StringLiteral | Number | date | boolean | nil | functionCall | tuple | today | objectProperty ; tuple.Rule = LParen + expression + RParen; unaryExpression.Rule = UnaryOperator + expression; binaryExpression.Rule = expression + BinaryOperator + expression; #endregion #region Functions functionCall.Rule = logicFunction | mathFunction | stringFunction ; logicFunction.Rule = iifFunction | icaseFunction ; mathFunction.Rule = powerFunction | minFunction | maxFunction ; stringFunction.Rule = substringFunction | concatFunction | leftFunction | rightFunction ; #endregion #region Logic Functions iifFunction.Rule = ToTerm("IIF") + LParen + expression + Comma + expression + Comma + expression + RParen; icaseFunction.Rule = ToTerm("ICASE") + LParen + caseConditionList + (Comma + expression).Q() + RParen; caseCondition.Rule = expression + Comma + expression; caseConditionList.Rule = MakePlusRule(caseConditionList, Comma, caseCondition); #endregion #region Math Functions powerFunction.Rule = ToTerm("POWER") + LParen + expression + Comma + expression + RParen; minFunction.Rule = ToTerm("MIN") + LParen + expression + Comma + expression + RParen; maxFunction.Rule = ToTerm("MAX") + LParen + expression + Comma + expression + RParen; #endregion #region String Functions substringFunction.Rule = ToTerm("SUBSTRING") + LParen + expression + Comma + expression + Comma + expression + RParen; concatFunction.Rule = ToTerm("CONCAT") + LParen + expression + Comma + expression + RParen; leftFunction.Rule = ToTerm("LEFT") + LParen + expression + Comma + expression + RParen; rightFunction.Rule = ToTerm("RIGHT") + LParen + expression + Comma + expression + RParen; #endregion #region Special Functions today.Rule = ToTerm("#{TODAY}"); fieldName.Rule = TerminalFactory.CreateCSharpIdentifier("id"); objectProperty.Rule = ToTerm("$") + fieldName; #endregion #region Grammar Metadata LanguageFlags = LanguageFlags.CreateAst; RegisterOperators(10, "*", "/", "%"); RegisterOperators(9, "+", "-"); RegisterOperators(8, "=", ">", "<", ">=", "<=", "<>", "!=", "!<", "!>"); RegisterOperators(7, "^", "&", "|"); RegisterOperators(6, "NOT"); RegisterOperators(5, "AND"); RegisterOperators(4, "OR", "LIKE", "IN"); MarkPunctuation(",", "(", ")", "}", "{", "${", ".", "?", "#{"); MarkTransient(terminal, expression, functionCall, logicFunction, mathFunction, stringFunction); #endregion Root = expression; }
///-------------------------------------------------------------------------------- /// <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 ObjectGrammar() : base(false) { //var identifier = new RegexBasedTerminal("identifier", "[a-zA-Z][a-zA-Z0-9_]*", "list"); IdentifierTerminal identifier = TerminalFactory.CreateCSharpIdentifier("Identifier"); //var identifier = new RegexBasedTerminal("identifier", @"\b((?!list)[a-zA-Z0-9_])+\b"); var value = new RegexBasedTerminal("name", @"\b[a-zA-Z0-9_\.]+\b"); var str = new QuotedValueLiteral("value", "\"", TypeCode.String); var external = new NonTerminal("external"); var line = new NonTerminal("line"); var @object = new NonTerminal("object"); var objectList = new NonTerminal("objectList"); var properties = new NonTerminal("properties"); var property = new NonTerminal("property"); var attributeList_opt = new NonTerminal("attributeList_opt"); var attributeList = new NonTerminal("attributeList"); var attributes = new NonTerminal("attributes"); var attribute = new NonTerminal("attribute"); var attribute_kv = new NonTerminal("attribute_kv"); var attribute_value = new NonTerminal("attribute_value"); var attribute_flag = new NonTerminal("attribute_flag"); var optional_flag = new NonTerminal("optional_flag"); var optional_flag_opt = new NonTerminal("optional_flag_opt"); var default_value = new NonTerminal("default_value"); var default_value_opt = new NonTerminal("default_value_opt"); var type = new NonTerminal("type"); var list = new NonTerminal("list"); var comma = ToTerm(",", "comma"); CommentTerminal SingleLineComment = new CommentTerminal("SingleLineComment", "//", "\r", "\n", "\u2085", "\u2028", "\u2029"); //CommentTerminal DelimitedComment = new CommentTerminal("DelimitedComment", "/*", "*/"); NonGrammarTerminals.Add(SingleLineComment); //NonGrammarTerminals.Add(DelimitedComment); external.Rule = ToTerm("external") + identifier + attributeList_opt; line.Rule = external | @object; attribute_value.Rule = value | str; attribute_kv.Rule = identifier + "=" + attribute_value; attribute_flag.Rule = identifier; attribute.Rule = attribute_kv | attribute_flag; attributes.Rule = MakePlusRule(attributes, comma, attribute); attributeList.Rule = "[" + attributes + "]"; attributeList_opt.Rule = Empty | attributeList; list.Rule = "List" + identifier; type.Rule = identifier | list; default_value.Rule = ToTerm("=") + attribute_value; default_value_opt.Rule = Empty | default_value; optional_flag.Rule = "?"; optional_flag_opt.Rule = Empty | optional_flag; property.Rule = optional_flag_opt + identifier + ":" + type + default_value_opt + attributeList_opt; properties.Rule = MakePlusRule(properties, property); @object.Rule = ToTerm("object") + identifier + attributeList_opt + "{" + properties + "}"; objectList.Rule = MakePlusRule(objectList, line); Root = objectList; MarkPunctuation("=", "[", "]", ":", "{", "}", ";", "list", "object", "external"); }
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 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); }