options { IGNORE_CASE = true; FORCE_LA_CHECK = true; STATIC = false; } PARSER_BEGIN(PascalToJavaParser) import java.io.FileWriter; import java.io.BufferedWriter; import java.io.FileInputStream; import java.util.Vector; import java.util.Hashtable; class PascalToJavaParser { public static BufferedWriter file; public static String temp, aux; public static Token global; public static Vector tabelaDeSimbolos = new Vector(); public static int nivelEscopo = -1; public static int escopoMax = -1; public static void main (String args[]) throws ParseException, TokenMgrError, NumberFormatException { if (args.length != 1) { System.out.println("Usage: "); System.exit(1); } PascalToJavaParser parser = null; try { //file = new BufferedWriter(new FileWriter(args[1])); parser = new PascalToJavaParser(new FileInputStream(args[0])); } catch (Exception e) { System.err.println("Falha ao abrir arquivo"); e.printStackTrace(); System.exit(1); } parser.parseFile(); try { file.close(); } catch (Exception e) { System.err.println("Sem arquivo"); e.printStackTrace(); System.exit(1); } } public static void write(String some) { try { file.write(some); System.out.print(some); } catch (Exception e) { System.err.println("Erro na escrita de saida"); e.printStackTrace(); System.exit(1); } } } class Variaveis { public Vector variaveis; public String tipo; public Variaveis(){ variaveis = new Vector(); } public void addVariavel(String var) { variaveis.addElement(var); } public boolean exist(String var) { return variaveis.contains(var); } public void setTipo(String tipo_) { tipo = tipo_; } public boolean isTipo(String tipo_) { return tipo.equals(tipo_); } } PARSER_END(PascalToJavaParser) // ******************************** Espacos ************************************ SKIP : { " " | "\t" | "\n" | "\r" | "\f" } // ****************************** Comentarios ********************************** MORE : { "{" : COMENTARIO } SPECIAL_TOKEN : { "}" : DEFAULT } MORE : { < ~[] > } // ************************* Palavras Reservadas ******************************* TOKEN : { < REAL: "real" > | < INTEGER: "integer" > | < CHAR: "char" > | < IF: "if" > | < THEN: "then" > | < ELSE: "else" > | < BEGIN: "begin" > | < END: "end" > | < PROGRAM: "program" > | < TRUE: "true" > | < FALSE: "false" > | < PROCEDURE: "procedure" > | < FUNCTION: "function" > | < RETURN: "return" > | < VAR: "var" > | < CONST: "const" > | < ARRAY: "array" > | < OF: "of" > | < WHILE: "while" > | < DO: "do" > | < TO: "to" > | < BREAK: "break" > | < CONTINUE: "continue" > | < FOR: "for" > | < USES: "uses" > | < REPEAT: "repeat" > | < UNTIL: "until" > | < CASE: "case" > | < BYTE: "byte" > | < STRING: "string" > | < NOT: "not" > | < NIL: "nil" > | < LONGINT: "longint" > | < BOOLEAN: "boolean" > } // ********************** Separadores ************************************** TOKEN: { < LBRACKET: "[" > | < RBRACKET: "]" > | < OPEN_PAR: "(" > | < CLOSE_PAR: ")" > | < SEMICOLON: ";" > | < COMMA: "," > | < DOT: "." > | < TWODOTS: ":" > } // ******************************* Operadores ********************************** TOKEN : { < OPADI: ( "+" | "-" ) > | < IGUAL: "=" > | < OPMULT: ( "/" | "*" | "div" | "mod" | "and" | "in" ) > | < OPREL: ( "<" | "<=" | "<>" | "=>" | ">" | "or" | "and" ) > | < ATRIB : ":=" > } // ******************************** Literais *********************************** TOKEN : { < NUM_INT: (["0"-"9"])+ > } TOKEN : { < NUM_REAL: (["0"-"9"])+ "." (["0"-"9"])+ > } TOKEN : { < LITERAL: "\'" (~["\'"])* "\'" > } // ************************ FUNCOES ********************************** TOKEN: { < FUNC_WRITE: "write" > | < FUNC_WRITELN: "writeln" > | < FUNC_READ: "read" > | < FUNC_READLN: "readln" > | < FUNC_LENGTH: "length" > } // ************************ Identificador ************************************* TOKEN : { < ID: ("_"|) ("_"||)* > | < #LETTER: ["a"-"z", "A"-"Z" ] > | < #DIGIT: ["0"-"9"] > } void parseFile() : {} { Programa() } // ************************************ Gramatica ***************************** /* O programa i composto das seguintes partes. Utilizar bibliotecas i opcional. */ void Programa() : {} { { String name = getToken(0).image; try { file = new BufferedWriter(new FileWriter(name+".java")); } catch (Exception e) { System.err.println("Falha ao criar arquivo!!"); e.printStackTrace(); System.exit(1); } write("import java.io.*;\npublic class "+name+" {\n"); write("\tpublic static void main (String args[]) {\n\t\t"+name+" programa = new "+name+"();\n\t\tprograma.begin();\n\t}\n"); } [Uses()] [Constantes()] Corpo() { write("\n}\n"); } } /* O corpo i composto por declaragues de variaveis (que sco opcionais), rotinas (tambim opcionais) e as sentengas que entco entre um 'begin' e 'end' (pode ser nulo). */ void Corpo() : { String comandos; } { Declara() Rotinas() { escopoMax=nivelEscopo; nivelEscopo=0; } {write("\tpublic void begin() {\n");} comandos = Sentencas() { write(comandos); } {write("\t}\n");} } void Constantes() : {} { (global = {temp=global.image.toLowerCase()+" = ";} {write("\tpublic final ");} (([ {temp += getToken(0).image;}] (global= { write("int "); aux = global.image; } |global= { write("float "); aux = global.image; })) | global= { write("String "); aux = "\""+global.image.substring(1,global.image.length()-1)+"\"";} | global= { write("boolean "); aux = global.image; } | global= { write("boolean "); aux = global.image; }) { write(temp+aux+";\n");} )+ } //** Refere-se as bibliotecas utilizadas. As bibliotecas podem estar separadas por ',' e depois do zltimo nome temos um ';' void Uses() : {} { ( )* {write("/* Uso de bibliotecas ainda não suportado!!!\nBibliotecas sendo omitidas. */\n");} } //** Declaragco das variaveis void Declara() : {} { [ { nivelEscopo++; tabelaDeSimbolos.addElement(new Hashtable()); } ( UmaDeclaracaoVar() {write("\n");} )+ // 1 ou mais vezes ] } //** Declara as variaveis e seu tipo void UmaDeclaracaoVar() : { String tipo; String variaveis; Variaveis var; } { { var = new Variaveis(); } variaveis = ListaVariaveis(var) tipo = TipoPadrao() { var.setTipo(tipo); variaveis += ";"; write("\t"+tipo+" "+variaveis); Hashtable tmp = (Hashtable)tabelaDeSimbolos.elementAt(nivelEscopo); for (int i=0; i<= var.variaveis.size()-1; i++) { tmp.put(var.variaveis.elementAt(i),var.tipo); } } } //** composicao das variaveis, identificador seguido de mais identificadores String ListaVariaveis(Variaveis var) : { Token tok; String variaveis; String auxi=""; } { tok = { variaveis = tok.image.toLowerCase(); var.addVariavel(variaveis);} [ {variaveis+=", ";} auxi = ListaVariaveis(var) ] { return variaveis+auxi; } } //tipo primitivo String TipoPadrao() : {} { {return "int";} | { return "float";} | { return "char";} | { return "byte";} | [] {return "String";} | {return "int";} | {return "boolean";} } void Rotinas() : {} { ( Procedimento() | Funcao() )* { write("/* Procedimentos e Funções não suportados */\n"); } } void Procedimento() : { String parametros; } { //{ write("\tpublic void "+getToken(0).image.toLowerCase()); } parametros = Parametros() //{ if (!teste) write("() "); } //{ write("{\n"); } CorpoSimples() //{ write("\t}\n"); } } void Funcao() : { String nome = "", parametros, tipo; } { //{ nome = getToken(0).image.toLowerCase(); } parametros=Parametros() tipo=TipoPadrao() //{ write ("\tpublic "+tipo+" "+nome+parametros+" {\n"); } CorpoSimples() } String Parametros() : { String parametros="()"; } { [ ListaParametros() {return parametros;} ] {return parametros;} } void ListaParametros() : {} { ListaDeIdentificadores() (TipoPadrao()) CountListaPar() } void CountListaPar() : {} { [ ListaParametros() ] } void ListaDeIdentificadores() : {} { CountListaId() } void CountListaId() : {} { [ ListaDeIdentificadores() ] } String CorpoSimples() : { String corpo; } { Declara() corpo = Sentencas() {corpo+="}\n";} {return corpo;} } String Sentencas() : { String cmd, saux=""; } { cmd = Comando() { if (cmd!="") cmd+="\n"; } [ saux = Sentencas() ] { return cmd+saux; } } String Sentenca() : { String cmd; } { cmd = Comando() { return cmd+"\n"; } } String Comando() : { String cmd="", vread="", id=""; Token aux; } { ( ((aux=|aux=) [ cmd = VarRead() {return cmd;}] ) { if (aux.image.toLowerCase().equals("readln")) { cmd = "try {\nSystem.in.read();\n} catch (Exception e) {\n"; cmd+= "System.err.println(\"Falha ao ler do teclado!\");\n"; cmd+= "e.printStackTrace();\nSystem.exit(1);\n}\n"; return cmd; } else { return ""; } } | (({cmd="System.out.print";}|{cmd="System.out.println";}) [ vread = VarWrite() ]{cmd+="("+vread+");";}) | ( aux = { id=aux.image.toLowerCase(); cmd="for ("+id+"="; } vread = Expressao() { cmd+=vread+";"; } vread = Expressao() { cmd+=id+"<="+vread+";"+id+"++) {\n"; } vread = Sentencas() { cmd+=vread+"}\n"; } ) | ( { cmd+="do {\n";} vread = Sentencas() { cmd+=vread+"} while (!("; } vread = Condicao() { cmd+=vread+"));\n"; } ) | ( { cmd="while ("; } vread = Condicao() { cmd+=vread+") {\n"; } vread = Sentencas() { cmd+=vread+"}\n"; } ) | /*( { cmd="if ("; } vread = Condicao() { cmd+=vread+")";} {cmd+=" {\n";} vread = Sentencas() { cmd+=vread+"}\n";} [ (( {cmd+="else {\n";} vread = Sentencas() {cmd+=vread+"}\n";}) | ( {cmd+="else {\n";} vread = Sentenca() {cmd+=vread+"}\n";})) ] )*/ /* com warning mas funfa */ ( { cmd="if ("; } vread = Condicao() { cmd+=vread+")";} (( {cmd+=" {\n";} vread = Sentenca() { cmd+=vread+"}\n";} ) | ( {cmd+=" {\n";} vread = Sentencas() { cmd+=vread+"}\n";}) ) [ (( {cmd+="else {\n";} vread = Sentencas() {cmd+=vread+"}\n";}) | ( {cmd+="else {\n";} vread = Sentenca() {cmd+=vread+"}\n";}) ) ]) | vread = Variavel() { cmd = "switch ("+vread+") {\n";} ((aux=|/*aux=|aux=|*/aux=) { //Java nao suporta switch com boolean!! Transformar em if! cmd+="case "; if (aux.image.equalsIgnoreCase("true")) { cmd+="true: {\n"; } else if (aux.image.equalsIgnoreCase("false")) { cmd+="false: {\n"; } else { if ((aux.image.length()>3)&&(aux.image.charAt(0)=='\'')) { System.err.println("Case com string não permitido!!!"); System.exit(1); } cmd+=aux.image+": {"; } } (vread=Sentenca() | (vread=Sentencas())) {cmd+=vread+"break;\n}\n";} )* [ (vread=Sentenca() | vread=Sentencas() ) { cmd+="default: {\n"+vread+"\n}\n"; } ] { cmd+="}"; } | aux = vread = ComandoAux() { cmd = aux.image.toLowerCase()+vread+";"; }//(Variavel() Expressao()) //| //(ChamadaDeProcedimento()) ) { return cmd; } } String VarWrite() : { String vv="", ret=""; } { ( { vv="\""+getToken(0).image.substring(1,getToken(0).image.length()-1)+"\""; } [ { vv+="+"; } ret = VarWrite() ] { vv += ret; } | { vv = getToken(0).image.toLowerCase(); } [ { vv+="+"; } ret = VarWrite() ] { vv += ret; } ) { return vv; } } String ComandoAux() : { String exp, va=""; } { va = VariavelAux() exp = Expressao() { return va+"="+exp; } | exp = Argumentos() { return exp; } } String Variavel() : { String var=""; Token t; } { t = var = VariavelAux() { return t.image.toLowerCase()+var; } } String VariavelAux() : { String vaux="",lista; Token t; } { [ lista = ListaDeSubscrito() vaux = VariavelAux() { return "["+lista+"]"+vaux; } | t = vaux = VariavelAux() { return "."+t.image.toLowerCase()+vaux; } | "^" vaux = VariavelAux() { return "."+vaux; } ] { return ""; } } String ListaDeSubscrito() : { String exp, lista=""; } { exp = Expressao() lista = ListaDeSubscritoAux() { return exp+lista; } } String ListaDeSubscritoAux() : { String exp, lista=""; } { [ exp=Expressao() lista=ListaDeSubscritoAux(){return ","+exp+lista;}] { return ""; } } String Expressao() : { String cmd, vaux=""; } { cmd = ExpressaoSimples() vaux = ExpressaoAux() { return cmd+vaux; } } String ExpressaoAux() : { String cmd="", vaux=""; Token taux=null; } { [(taux = |taux = ) cmd = ExpressaoSimples() vaux = ExpressaoAux()] { if (taux != null) { String bla; if (taux.image.equalsIgnoreCase("or")) return "||"+cmd+vaux; else if (taux.image.equalsIgnoreCase("and")) return "&&"+cmd+vaux; else if (taux.image.equals("=")) return "=="+cmd+vaux; else return taux.image.toLowerCase()+cmd+vaux; } else { return cmd+vaux; } } } String ExpressaoSimples() : { String cmd, vaux=""; } { cmd = Termo() vaux = ExpressaoSimplesAux() { return cmd+vaux; } } String ExpressaoSimplesAux() : { String cmd="",vaux=""; Token taux=null; } { [taux = cmd = Termo() vaux = ExpressaoSimplesAux()] { if (taux!=null) return taux.image+cmd+vaux; else return cmd+vaux; } } String Termo() : { String cmd, vaux=""; } { cmd = Fator() vaux = TermoAux() { return cmd+vaux; } } String TermoAux() : { String cmd="", vaux=""; Token taux=null; } { [taux = cmd = Fator() vaux = TermoAux()] { if (taux!=null) return taux.image+cmd+vaux; else return cmd+vaux; } } String Fator() : { String cmd; Token taux = null; } { ( taux = cmd = Fator() | cmd = Exponenciacao() ) { if (taux!=null) return taux.image+cmd; else return cmd; } } String Exponenciacao() : { String prim, exp=""; } { prim = Primario() exp = ExpoAux() { return prim+exp; } } String ExpoAux() : { String exp=""; } { ["**" exp = Exponenciacao() {return "**"+exp; } ] { return exp; } } String Primario() : { String some=""; Token taux = null; } { ( taux = (some = AcessoVariavelAux() | some = Parametros()) | // AcessoVariavel() //| some = ConstanteSemSinal() //| // DesignadorDeFuncao() | some = ConstrutorDeConjunto() | some = Expressao() { some="("+some+")"; } | taux = some = Primario() //descobrir no lex o que eh _NOT, acho q eh 'not' ) { if (taux!=null) return taux.image+some; else return some; } } String ConstanteSemSinal() : { String constante=""; } { constante = NumeroSemSinal() { return constante; } | { return "\""+getToken(0).image.substring(1,getToken(0).image.length()-1)+"\"";} | { return "null"; } } String NumeroSemSinal() : { Token t; } { (t = | t = ) { return t.image; } } String ConstrutorDeConjunto() : { String lista=""; } { [lista = ListaDeDesignadorDeMembros()] { return "["+lista+"]"; } } String ListaDeDesignadorDeMembros() : { String desig, lista=""; } { desig = DesignadorDeMembro() lista = ListaDeDesigAux() { return desig+lista; } } String ListaDeDesigAux() : { String desig, lista=""; } { [ desig=DesignadorDeMembro() lista=ListaDeDesigAux() { return ","+desig+lista; }] { return ""; } } String DesignadorDeMembro() : { String exp, desig=""; } { exp = Expressao() desig = DesignadorDeMembroAux() { return exp+desig; } } String DesignadorDeMembroAux() : { String exp, desig=""; } { [".." exp = Expressao() desig = DesignadorDeMembroAux() {return ".."+exp+desig;}] { return ""; } } String AcessoVariavelAux() : { String saux, algo=""; } { ( [ saux=ListaDeExpressaoDeIndice() algo = AcessoVariavelAux() { algo = "["+saux+"]"+algo; } | {saux = getToken(0).image.toLowerCase();} algo = AcessoVariavelAux() { algo = "."+saux+algo; } | "^" algo = AcessoVariavelAux() //verificar!! ponteiros viram objetos assim como registros ] ) { return algo; } } String ListaDeExpressaoDeIndice() : { String exp, lista=""; } { exp = Expressao() lista = ListaDeExpDeIndAux() { return exp+lista; } } String ListaDeExpDeIndAux() : { String exp, lista=""; } { [ exp = Expressao() lista = ListaDeExpDeIndAux(){return ","+exp+lista;}] { return ""; } } void ListaDeExpressoes() : {} { Expressao() ListaDeExpressaoAux() } void ListaDeExpressaoAux() : {} { [ Expressao() ListaDeExpressaoAux()] } String VarRead() : { String var, aux, aux2; Hashtable tmp; } { { var="try {\n"; aux2 = getToken(0).image.toLowerCase(); tmp = (Hashtable)tabelaDeSimbolos.elementAt(nivelEscopo); aux = (String)tmp.get(aux2); if (aux!=null) { var+="BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));\n"; var+=aux2; if (aux.equals("int")) { var+= "=Integer.parseInt(bf.readLine());\n"; } else if (aux.equals("float")) { var+= "=Float.parseFloat(bf.readLine());\n"; } else if (aux.equals("boolean")) { System.err.println("Tentando ler um boolean???"); System.exit(1); } else if (aux.equals("char")) { var+="=bf.readLine().charAt(0);\n"; } else if (aux.equals("String")) { var+="=bf.readLine();\n"; } else if (aux.equals("byte")) { var+="=Byte.parseByte(bf.readLine());\n"; } else { System.err.println("Tipo não suportado pra leitura!!"); System.exit(1); } } else { System.err.println("Variavel não declarada!!"); System.exit(1); } var+="} catch (Exception e) {\nSystem.err.println("; var+="\"Runtime error :)\");\nSystem.exit(1);\n}\n"; } [aux=MaisVarRead() {var+=aux;}] {return var;} } String MaisVarRead() : { String var=""; } { VarRead() { return var; } } String Condicao() : { String cmd; } { cmd = Expressao() {return cmd; } } void ChamadaDeProcedimento() : {} { Argumentos() } String Argumentos(): { String lista=""; } { [ lista = ListaDeArgumentos() { return "("+lista+")"; } ] { return ""; } } String ListaDeArgumentos() : { String exp, cont=""; } { exp = Expressao() cont = ContinuacaoListaDeArgumentos() { return exp+cont; } } String ContinuacaoListaDeArgumentos() : { String lista; } { [ lista = ListaDeArgumentos() { return ","+lista; } ] { return ""; } }