Created
February 6, 2019 17:22
-
-
Save Generickle/3c4eefaae52bf035424a9186d8cc5ae7 to your computer and use it in GitHub Desktop.
Tutorial Flex y Cup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*-----------------------PAQUETE-----------------------*/ | |
package olc2.np.lenguaje1.parser; | |
/*--------------------IMPORTACIONES--------------------*/ | |
import java_cup.runtime.Symbol; | |
import olc2.np.lenguaje1.convenciones.ManejadorDeErrores; | |
/*-----------------------INICIO------------------------*/ | |
%% | |
/*---------------CÓDIGO AUXILIAR %{---}%---------------*/ | |
%{ | |
ManejadorDeErrores manejadorDeErrores = ManejadorDeErrores.getInstance(); | |
//String string = "";//Variable para formar una cadena por estados | |
public String archivo = ""; | |
%} | |
/*-------------------CONFIGURACIONES-------------------*/ | |
%cupsym Lenguaje1Sym | |
%class Lenguaje1AL | |
%cup | |
%public | |
%char | |
%column | |
%full | |
%line | |
%unicode | |
%ignorecase | |
%init{ | |
yyline = 1; | |
yychar = 1; | |
%init} | |
/*------------------DEFINICION DE ESTADOS---------------*/ | |
//%state ESTADO_AUXILIAR_1 | |
//%state ESTADO_AUXILIAR_2 | |
//%state CADENA//Estado para formar una cadena | |
/*------------------EXPRESIONES REGULARES---------------*/ | |
digito = [0-9] //E.R. que reconoce el intervalo de digitos del 0 al 9. | |
erEntero = {digito}+//E.R. que reconoce numeros enteros. | |
erDecimal = {digito}+("."{digito}+)//E.R. que reconoce numeros decimales. | |
erIfNot = "if"{espacioEnBlanco}*"not" | |
//erNumero = {digito}+("."{digito}+)?//E.R. que reconoce tanto decimales como enteros. | |
letra = [a-zA-Z] //E.R. que reconoce el intervalo de letras de la a hasta z minusculas y mayusculas. | |
erId = ({letra}|"_")+({letra}|{digito}|"_")*//E.R. para reconocer identificadores | |
erCaracter = "\'"[^\']?"\'" | |
erCadena = "\""[^\"]*"\"" | |
finDeLinea = \r|\n|\r\n | |
simboloValido = [^\r\n] | |
espacioEnBlanco = {finDeLinea} | [ \t\f] | |
comentarioMultiple = "$*" [^*] ~"*$" | "$*" "*"+ "$" | |
//Comentario can be the last line of the file, without line terminator. | |
comentarioSimple = "$$" {simboloValido}* {finDeLinea}? | |
contenidoDeComentario = ( [^*] | \*+ [^$*] )* | |
comentarioDocumentado = "$**" {contenidoDeComentario} "*"+ "$" | |
//Coments | |
comentario = {comentarioMultiple} | {comentarioSimple} | {comentarioDocumentado} | |
%% | |
/*--------------------------FIN-------------------------*/ | |
/*---------------ESPECIFICACIONES DE ESTADOS------------*/ | |
//Estado inicial | |
<YYINITIAL> { | |
//Signos de Agrupacion | |
"{" { /*System.out.println("llqa "+ yytext());*/ return new Symbol(Lenguaje1Sym.LLQA, yycolumn, yyline, yytext()); } | |
"}" { /*System.out.println("llqc "+ yytext());*/ return new Symbol(Lenguaje1Sym.LLQC, yycolumn, yyline, yytext()); } | |
"[" { /*System.out.println("cqa "+ yytext());*/ return new Symbol(Lenguaje1Sym.CQA, yycolumn, yyline, yytext()); } | |
"]" { /*System.out.println("cqc "+ yytext());*/ return new Symbol(Lenguaje1Sym.CQC, yycolumn, yyline, yytext()); } | |
"(" { /*System.out.println("pqa "+ yytext());*/ return new Symbol(Lenguaje1Sym.PQA, yycolumn, yyline, yytext()); } | |
")" { /*System.out.println("pqc "+ yytext());*/ return new Symbol(Lenguaje1Sym.PQC, yycolumn, yyline, yytext()); } | |
//Signos de Puntuacion | |
"," {/*System.out.println("coma "+ yytext());*/return new Symbol(Lenguaje1Sym.COMA, yycolumn, yyline, yytext());} | |
"." {/*System.out.println("punto "+ yytext());*/return new Symbol(Lenguaje1Sym.PUNTO, yycolumn, yyline, yytext());} | |
";" {/*System.out.println("pyc "+ yytext());*/ return new Symbol(Lenguaje1Sym.PYC, yycolumn, yyline, yytext());} | |
"=" {/*System.out.println("igual "+ yytext());*/return new Symbol(Lenguaje1Sym.IGUAL, yycolumn, yyline, yytext());} | |
//Signos Aritmeticos | |
"+" {/*System.out.println("mas "+ yytext());*/return new Symbol(Lenguaje1Sym.MAS, yycolumn, yyline, yytext());} | |
"-" {/*System.out.println("menos "+ yytext());*/return new Symbol(Lenguaje1Sym.MENOS, yycolumn, yyline, yytext());} | |
"*" {/*System.out.println("por "+ yytext());*/return new Symbol(Lenguaje1Sym.POR, yycolumn, yyline, yytext());} | |
"/" {/*System.out.println("dividido "+ yytext());*/return new Symbol(Lenguaje1Sym.DIVIDIDO, yycolumn, yyline, yytext());} | |
"^" {/*System.out.println("elevado "+ yytext());*/return new Symbol(Lenguaje1Sym.ELEVADO, yycolumn, yyline, yytext());} | |
"%" {/*System.out.println("modulo "+ yytext());*/return new Symbol(Lenguaje1Sym.MODULO, yycolumn, yyline, yytext());} | |
"++" {/*System.out.println("incremento "+ yytext());*/return new Symbol(Lenguaje1Sym.INCREMENTO, yycolumn, yyline, yytext());} | |
"--" {/*System.out.println("decremento "+ yytext());*/return new Symbol(Lenguaje1Sym.DECREMENTO, yycolumn, yyline, yytext());} | |
//Signos relacionales | |
"<" {/*System.out.println("menor "+ yytext());*/return new Symbol(Lenguaje1Sym.MENOR, yycolumn, yyline, yytext());} | |
">" {/*System.out.println("mayor "+ yytext());*/return new Symbol(Lenguaje1Sym.MAYOR, yycolumn, yyline, yytext());} | |
"<=" {/*System.out.println("menorIgual "+ yytext());*/return new Symbol(Lenguaje1Sym.MENOR_IGUAL, yycolumn, yyline, yytext());} | |
">=" {/*System.out.println("mayorIgual "+ yytext());*/return new Symbol(Lenguaje1Sym.MAYOR_IGUAL, yycolumn, yyline, yytext());} | |
"==" {/*System.out.println("equivalente "+ yytext());*/return new Symbol(Lenguaje1Sym.EQUIVALENTE, yycolumn, yyline, yytext());} | |
"!=" {/*System.out.println("diferente "+ yytext());*/return new Symbol(Lenguaje1Sym.DIFERENTE, yycolumn, yyline, yytext());} | |
//Signos logicos | |
"&&" {/*System.out.println("and "+ yytext());*/return new Symbol(Lenguaje1Sym.AND, yycolumn, yyline, yytext());} | |
"||" {/*System.out.println("or "+ yytext());*/return new Symbol(Lenguaje1Sym.OR, yycolumn, yyline, yytext());} | |
"!" {/*System.out.println("not "+ yytext());*/return new Symbol(Lenguaje1Sym.NOT, yycolumn, yyline, yytext());} | |
//En algunas herrameintas es necesario colocar los signos simples antes de los compuestos, es decir colocar el not "!" antes del diferente "!=" | |
//porque sino no se reconoceria el signo not "!" solo el signo diferente "!=" | |
//Palabras Reservadas | |
"clase" {/*System.out.println("KeyWord: "+ yytext());*/return new Symbol(Lenguaje1Sym.K_CLASE, yycolumn, yyline, yytext());} | |
"imprimir" {/*System.out.println("KeyWord: " + yytext());*/return new Symbol(Lenguaje1Sym.K_IMPRIMIR, yycolumn, yyline, yytext());} | |
"si" {/*System.out.println("KeyWord: " + yytext());*/return new Symbol(Lenguaje1Sym.K_SI, yycolumn, yyline, yytext());} | |
"sino" {/*System.out.println("KeyWord: " + yytext());*/return new Symbol(Lenguaje1Sym.K_SINO, yycolumn, yyline, yytext());} | |
"mientras" {/*System.out.println("KeyWord: " + yytext());*/return new Symbol(Lenguaje1Sym.K_MIENTRAS, yycolumn, yyline, yytext());} | |
"verdadero" {/*System.out.println("KeyWord: "+ yytext());*/return new Symbol(Lenguaje1Sym.K_VERDADERO, yycolumn, yyline, yytext());} | |
"falso" {/*System.out.println("KeyWord: "+ yytext());*/return new Symbol(Lenguaje1Sym.K_FALSO, yycolumn, yyline, yytext());} | |
"nulo" {/*System.out.println("KeyWord: "+ yytext());*/return new Symbol(Lenguaje1Sym.K_NULO, yycolumn, yyline, yytext());} | |
//Expresiones Regulares | |
{erEntero} {/*System.out.println("erEntero: "+ yytext());*/ return new Symbol(Lenguaje1Sym.ER_ENTERO, yycolumn, yyline, yytext());} | |
{erDecimal} {/*System.out.println("erDecimal: "+ yytext());*/ return new Symbol(Lenguaje1Sym.ER_DECIMAL, yycolumn, yyline, yytext());} | |
{erId} {/*System.out.println("erId: "+ yytext());*/return new Symbol(Lenguaje1Sym.ER_ID, yycolumn, yyline, yytext());} | |
{erCaracter} {/*System.out.println("erCaracter: "+ yytext());*/return new Symbol(Lenguaje1Sym.ER_CARACTER, yycolumn, yyline, yytext().substring(1, yytext().length()-1));} | |
{erCadena} {/*System.out.println("erCadena: "+ yytext());*/return new Symbol(Lenguaje1Sym.ER_CADENA, yycolumn, yyline, yytext().substring(1, yytext().length()-1));} | |
{espacioEnBlanco} {/*System.out.println("Espacio en blanco");*/} | |
{comentario} {/*System.out.println("comentario");*/} | |
} | |
//Definicion del estado para formar una cadena | |
/* | |
<CADENA> { | |
\" { | |
yybegin(YYINITIAL); | |
return Symbol(sym.STRING_LITERAL, string.toString()); | |
} | |
[^\n\r\"\\]+ { string.append( yytext() ); } | |
\\t { string.append('\t'); } | |
\\n { string.append('\n'); } | |
\\r { string.append('\r'); } | |
\\\" { string.append('\"'); } | |
\\ { string.append('\\'); } | |
} | |
*/ | |
//Tokens no permitidos (Error) | |
[^] { | |
manejadorDeErrores.insertarError(archivo, "Error Lexico",yyline, yycolumn, "El lexema \"" + yytext() + "\" no pertenece al lenguaje"); | |
return new Symbol(Lenguaje1Sym.error, yycolumn, yyline, yytext()); | |
} | |
/* | |
Si el analisis lexico mediante expresiones regulares de JFlex es muy complicado, se puede definir la expresion regular con estados. | |
<ESTADO_AUXILIAR_1>{ ... } | |
<ESTADO_AUXILIAR_2>{ ... } | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*-----------------------PAQUETE-----------------------*/ | |
package olc2.np.lenguaje1.parser; | |
/*--------------------IMPORTACIONES--------------------*/ | |
import java.util.LinkedList; | |
import java_cup.runtime.Symbol; | |
import olc2.np.lenguaje1.convenciones.ManejadorDeErrores; | |
import olc2.np.lenguaje1.interpretacion.Expresion; | |
import olc2.np.lenguaje1.interpretacion.Instruccion; | |
/*-------------------CODIGO PUBLICO--------------------*/ | |
parser code | |
{: | |
ManejadorDeErrores manejadorDeErrores = ManejadorDeErrores.getInstance(); | |
public String archivo = ""; | |
//Metodo que se llama en el momento en encontrar un error recuperable | |
public void syntax_error(Symbol s) | |
{ | |
String lexema = s.value.toString(); | |
int columna = s.left+1; | |
int linea = s.right; | |
manejadorDeErrores.insertarError(archivo, "Error Sintactico", linea, columna, "No se esperaba el caracter: " + lexema); | |
} | |
//Metodo que se llama en el momento en que ya no es posible una recuperacion de errores | |
public void unrecovered_syntax_error(Symbol s) throws java.lang.Exception | |
{ | |
String lexema = s.value.toString(); | |
int columna = s.left+1; | |
int linea = s.right; | |
manejadorDeErrores.insertarError(archivo, "Error Sintactico", linea, columna, "No se esperaba el caracter: " + lexema); | |
} | |
//Metodo que se llama en el momento en encontrar un error semantico (Hay que probarlo) | |
public void semantic(Symbol s, String str) | |
{ | |
String lexema = s.value.toString(); | |
int columna = s.left+1; | |
int linea = s.right; | |
manejadorDeErrores.insertarError(archivo, "Error Semantico", linea, columna, "No se esperaba el caracter: " + lexema + ". Mensaje: " + str); | |
} | |
:} | |
/*-------------------CODIGO PRIVADO--------------------*/ | |
action code | |
{: | |
//public String cadena = "Analisis Sintactico del lenguaje 1"; | |
:} | |
//tokens terminales; | |
terminal String IGUAL, PUNTO, COMA, PYC, | |
MAS, MENOS, POR, DIVIDIDO, ELEVADO, MODULO, INCREMENTO, DECREMENTO, | |
MENOR, MAYOR, MENOR_IGUAL, MAYOR_IGUAL, EQUIVALENTE, DIFERENTE, | |
AND, OR, NOT, | |
PQA, PQC, CQA, CQC, LLQA, LLQC, | |
K_CLASE, K_SI, K_SINO, K_MIENTRAS, K_VERDADERO, K_FALSO, K_NULO, | |
K_IMPRIMIR, | |
ER_ID, ER_ENTERO, ER_DECIMAL, ER_CARACTER, ER_CADENA; | |
//tokens no terminales | |
non terminal LinkedList<Instruccion> inicio, clase, listaDeSentenciasGlobales, listaDeSentenciasLocales, listaDeDeclaraciones, listaDeSinoSi, listaDeExpresiones; | |
non terminal Instruccion sentenciaGlobal, sentenciaLocal, declaracion, expresion, asignacion, imprimir, sdcIf, si, sino, sinoSi, mientras; | |
precedence left AND; | |
precedence left OR; | |
precedence right NOT; | |
precedence left EQUIVALENTE, DIFERENTE, MENOR, MAYOR, MENOR_IGUAL, MAYOR_IGUAL; | |
precedence left MAS, MENOS; | |
precedence left POR, DIVIDIDO, MODULO; | |
precedence right ELEVADO; | |
precedence left INCREMENTO, DECREMENTO; | |
start with inicio; | |
inicio ::= expresion:exp {: System.out.println("Analisis Finalizado"); RESULT = new LinkedList<>(); RESULT.add(exp); :} | |
; | |
expresion ::= expresion:exp1 MAS:signo expresion:exp2 {: RESULT = new Expresion(exp1, exp2, Expresion.TipoDeOperacion.SUMA, exp1right, exp1left); :} | |
| expresion:exp1 POR expresion:exp2 {: RESULT = new Expresion(exp1, exp2, Expresion.TipoDeOperacion.MULTIPLICACION, exp1right, exp1left); :} | |
| PQA expresion:exp PQC {: RESULT = exp; :} | |
| ER_ID:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.IDENTIFICADOR, expright, expleft); :} | |
| ER_CADENA:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.CADENA, expright, expleft); :} | |
| ER_CARACTER:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.CARACTER, expright, expleft); :} | |
| ER_ENTERO:exp {: RESULT = new Expresion(new Integer(exp), Expresion.TipoDeOperacion.ENTERO, expright, expleft); :} | |
| ER_DECIMAL:exp {: RESULT = new Expresion(new Double(exp), Expresion.TipoDeOperacion.DECIMAL, expright, expleft); :} | |
| K_VERDADERO:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.TRUE, expright, expleft); :} | |
| K_FALSO:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.FALSE, expright, expleft); :} | |
| K_NULO:exp {: RESULT = new Expresion(exp, Expresion.TipoDeOperacion.NULO, expright, expleft); :} | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment