gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
mjc2wsl - shr and shl added
[mjc2wsl.git] / src / mjc2wsl.java
index 970089e..1682978 100644 (file)
@@ -10,16 +10,46 @@ import java.util.*;
  * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
  */
 public class mjc2wsl{
-       public static String versionN = "0.1.2";
-               
-       //regular comments from the original file
-       //OC when original code is inserted in the file, next to the translations
-       //SPEC special messages from the translator
-       //ERR error messages from the translator
-       public static final char C_REG = ' ', C_OC = '#', C_SPEC = '&', C_ERR = '!';
-
-               /** instruction code */
-               public static final int 
+       public static String versionN = "0.1.4";
+
+       public static final int M_ERR = 2, M_WAR = 1, M_DEB = 0;
+       
+       private int printLevel = M_ERR;
+       
+       private int[] messageCounters = new int[M_ERR+1];
+       
+       private void message(String mes, int level){
+                       if (level>=printLevel)
+                                       System.out.println(mes);
+                       messageCounters[level]++;
+       }
+       
+       private void printMessageCounters(){
+                       printMessageCounters(System.out);
+       }
+       
+       private void printMessageCounters(PrintStream out){
+                       out.println("total errors:"+messageCounters[M_ERR]+" warnings:"+messageCounters[M_WAR]);
+       }
+       
+       private boolean genPauseAfterEachAddress=false, 
+               genPrintForEachAddress = false,
+               genPrintEStackOnChange = false;
+       
+       /** Constant used for marking a regular comment from the original file */
+       public static final char C_REG = ' ';
+       /**
+        * Constant used for marking when original code is inserted in the file,
+        * next to the translations
+        */
+       public static final char C_OC = '#';
+       /** Constant used for marking special messages from the translator */
+       public static final char C_SPEC = '&';
+       /** Constant used for marking error messages from the translator */
+       public static final char C_ERR = '!';
+
+       /** instruction code in MicroJava bytecode. */
+       public static final int 
                load        =  1,
                load_0      =  2,
                load_1      =  3,
@@ -79,14 +109,22 @@ public class mjc2wsl{
                trap            = 57;
 
        public String getStandardStart(){
+                       return getStandardStart(10);
+       }
+       
+       public String getStandardStart(int numWords){
                StringBuilder ret = new StringBuilder(
                        "C:\" This file automatically converted from microjava bytecode\";\n"
                        +"C:\" with mjc2wsl v "+versionN+"\";\n");
 
-               ret.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n");
-               for (int i = 0; i <= 3; i++)
-                       ret.append("loc" + i + " := 0, ");
-               ret.append("\n  estack := < >, t_e_m_p := 0 > :");
+               ret.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
+               ret.append("mjvm_locals := ARRAY(1,0), ");
+               ret.append("\n\tmjvm_statics := ARRAY("+numWords+",0), ");
+               ret.append("\n\tmjvm_arrays := < >, ");
+               ret.append("\n\tmjvm_objects := < >, ");
+               ret.append("\n  mjvm_estack := < >, mjvm_mstack := < >, "); 
+               ret.append("\n  mjvm_fp := 0, mjvm_sp := 0,");
+               ret.append("\n  t_e_m_p := 0 > :");
 
                return ret.toString();
        }
@@ -97,6 +135,38 @@ public class mjc2wsl{
        
        private boolean originalInComments = false;     
        
+       private HashMap<Integer,String> opMap = null;
+       
+       private String opCodeFile = "mj-bytecodes.properties";
+       
+       private HashMap<Integer,String> getOpMap() {
+                       if (opMap==null) {
+                                       opMap = new HashMap<Integer, String> (60, 0.98f);
+                                       try{
+                                       BufferedReader in = new BufferedReader(
+                                                       new InputStreamReader(getClass().getResourceAsStream(opCodeFile)));
+                                       String str = in.readLine();
+                                       while (str != null) {
+                                                       String[] ss = str.split("=");
+                                                       opMap.put(Integer.parseInt(ss[0]),ss[1]);
+                                                       str = in.readLine();
+                                       }
+                                       in.close();
+                                       }catch (Exception ex) {
+                                               ex.printStackTrace();
+                                       }
+                       }
+                       return opMap;
+       }
+       
+       public String getOpString(int op) {
+                       return getOpMap().get(op);
+       }
+       
+       public String describeOpCode(int op) {
+                       return op + " (" + getOpString(op) + ")";
+       }
+       
        private InputStream mainIn;
        private PrintWriter out = null;
        private int counter = -1;
@@ -139,7 +209,24 @@ public class mjc2wsl{
        }
        
        private String loc(int i){
-               return "loc" + i;
+               //arrays start at 1 in WSL, so we need an offset
+               return "mjvm_locals[" + (i+1)+"]";
+       }
+       
+       private String genStatic(int i){
+                       return "mjvm_statics[" + (i+1)+"]";
+       }
+       
+       private String genArray(int i){
+                       return "mjvm_arrays["+ i +"]";
+       }
+       
+       private String genArray(String i){
+                       return "mjvm_arrays["+ i+"]";
+       }
+       
+       private String genObject(String i){
+                       return "mjvm_objects["+ i+"]";
        }
        
        /**
@@ -160,18 +247,33 @@ public class mjc2wsl{
                return "C:\"" + type + str.replace("\"", "''") + "\";";
        }
 
+       //Expression stack
+       
        private String cmdToEStack(int i) {
-               return "estack := <" + i + " > ++ estack;";
+               String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
+               if (genPrintEStackOnChange) res +="PRINT(\"eStack\",mjvm_estack);";
+               return res;
        }
 
        private String cmdToEStack(String i) {
-               return "estack := <" + i + " > ++ estack;";
+               String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
+               if (genPrintEStackOnChange) res +="PRINT(\"eStack\",mjvm_estack);";
+               return res;
        }
 
        private String cmdFromEStack(String st) {
-               return st + " := HEAD(estack); estack := TAIL(estack);";
+               String res = st + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
+               if (genPrintEStackOnChange) res +="PRINT(\"eStack\",mjvm_estack);";
+               return res;
        }
        
+       private String cmdPopEStack() {
+               String res = "mjvm_estack := TAIL(mjvm_estack);";
+               if (genPrintEStackOnChange) res +="PRINT(\"eStack\",mjvm_estack);";
+               return res;
+       }
+       
+       
        private String getTopTwo(){
                return cmdFromEStack("tempa") + "\n" + cmdFromEStack("tempb");
        }
@@ -179,20 +281,60 @@ public class mjc2wsl{
        private String getTop() {
                return cmdFromEStack("tempa");
        }
+       
+       //Method stack
+       
+       private String cmdToMStack(int i) {
+               return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
+       }
+
+       private String cmdToMStack(String i) {
+               return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
+       }
+
+       private String cmdFromMStack(String st) {
+               return st + " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
+       }
+       
+       private String getRelationFor(int opcode) throws Exception {
+                       switch (opcode) {
+                                       case jeq: return "=";
+                                       case jne: return "<>";
+                                       case jlt: return "<";
+                                       case jle: return "<=";
+                                       case jgt: return ">";
+                                       case jge: return ">=";
+                       }
+                       throw new Exception("Wrong opcode for a relation");
+       }
+       
+       private boolean isJumpCode(int opcode) {
+                       return (opcode>=jmp) && (opcode<=jge);
+       }
 
-       public void convertStream(InputStream ins){
+       public void convertStream(InputStream ins) throws Exception{
                mainIn = ins;
-               //skip start TODO make better
-               for (int i = 0; i < 14; i++)
-                       get();
+               //process start 
+               byte m = (byte) get();
+               byte j = (byte) get();
+               if (m!='M' || j !='J') 
+                               throw new Exception("Wrong start of bytecode file");
+               int codesize = get4();
+               int numberOfWords = get4();
+               int mainAdr = get4();
                
-               prl(getStandardStart());
-               prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a14 END");
+               prl(getStandardStart(numberOfWords));
+               prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a"+(14+mainAdr)+" END");
                int op = get();
                while (op >= 0) {
                        if (originalInComments)
-                               prl(createComment("" + op, C_OC));
+                               prl(createComment(describeOpCode(op), C_OC));
                        prl("a" + counter + " == ");
+                       if (genPrintForEachAddress) {
+                                       prl("PRINT(\"a"+counter+"\");");
+                                       if (genPauseAfterEachAddress)
+                                                       prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
+                       }
                        switch (op) {
                        case load: {
                                prl(cmdToEStack(loc(get())));
@@ -216,6 +358,32 @@ public class mjc2wsl{
                                prl(cmdFromEStack(loc(op - store_0)));
                                break;
                        }
+                       
+                       case getstatic:{
+                               prl(cmdToEStack(genStatic(get2())));
+                               break;
+                       } 
+                       case putstatic: {
+                               prl(cmdFromEStack(genStatic(get2())));
+                               break;
+                       }
+
+                       case getfield:{
+                                       int f = get2();
+                                       prl(getTop());
+                                       prl(cmdToEStack(genObject("tempa")+"["+(f+1)+"]"));
+                                       break;
+                       }
+                       case putfield:{
+                                       int f = get2();
+                                       //we need to use a temparray as a pointer, WSL
+                                       //otherwise tries to access it as a list of lists and fails
+                                       prl(getTopTwo());
+                                       prl("VAR < tempArray := "+genObject("tempb")+" > :");
+                                       prl("tempArray["+(f+1)+"]:=tempa ENDVAR;");                             
+                                       break;
+                       }
+                       
                        case const_: {
                                prl(cmdToEStack(get4()));
                                break;
@@ -231,6 +399,130 @@ public class mjc2wsl{
                                break;
                        }
 
+                       case add: {
+                               prl(getTopTwo());
+                               prl("tempres := tempb + tempa;");
+                               prl(cmdToEStack("tempres"));
+                               break;
+                       }
+                       case sub: {
+                               prl(getTopTwo());
+                               prl("tempres := tempb - tempa;");
+                               prl(cmdToEStack("tempres"));
+                               break;
+                       }
+                       case mul: {
+                               prl(getTopTwo());
+                               prl("tempres := tempb * tempa;");
+                               prl(cmdToEStack("tempres"));
+                               break;
+                       }
+                       case div: {
+                               prl(getTopTwo());
+                               prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
+                               prl("tempres := tempb DIV tempa;");
+                               prl(cmdToEStack("tempres"));
+                               break;
+                       }
+                       case rem: {
+                               prl(getTopTwo());
+                               prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
+                               prl("tempres := tempb MOD tempa;");
+                               prl(cmdToEStack("tempres"));
+                               break;
+                       }
+
+                       case neg :{
+                               prl(getTop());
+                               prl(cmdToEStack("-tempa"));
+                               break;
+                       }                       
+
+                       case shl  : {
+                               prl(getTopTwo());
+                               prl("VAR <tempres :=tempb, i:=1 >:");
+                               prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
+                               prl(cmdToEStack("tempres"));
+                               prl("ENDVAR;");
+                               break;
+                       }
+                       case shr  : {
+                               prl(getTopTwo());
+                               prl("VAR <tempres :=tempb, i:=1 >:");
+                               prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
+                               prl(cmdToEStack("tempres"));
+                               prl("ENDVAR;");
+                               break;
+                       }
+
+                       case inc  : {
+                               int b1 = get(), b2 = get();
+                               prl(loc(b1)+" := " +loc(b1)+" + "+b2+";");
+                               break;
+                       }
+
+                       case new_ :{
+                                       int size = get2();
+                                       //TODO maybe objects and arrays should be in the same list?
+                                       prl("mjvm_objects := mjvm_objects ++ < ARRAY("+size+",0) >;");
+                                       prl(cmdToEStack("LENGTH(mjvm_objects)"));
+                                       break;
+                       }
+                       case newarray :{
+                                       get();// 0 - bytes, 1 - words; ignore for now
+                                       //TODO take into consideration 0/1
+                                       prl(getTop());
+                                       prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
+                                       prl(cmdToEStack("LENGTH(mjvm_arrays)"));
+                                       break;
+                       }
+                       
+                       case aload:
+                       case baload:{
+                               prl(getTopTwo());
+                               prl(cmdToEStack(genArray("tempb")+"[tempa+1]"));
+                               break;
+                       }
+                       case astore:
+                       case bastore:{
+                               prl(cmdFromEStack("tempres"));
+                               prl(getTopTwo());
+                               //we need to use a temparray as a pointer, WSL
+                               //otherwise tries to access it as a list of lists and fails
+                               prl("VAR < tempArray := "+genArray("tempb")+" > :");
+                               prl("tempArray[tempa+1]:=tempres ENDVAR;");
+                               break;
+                       }
+                       case arraylength :{
+                               prl(getTop());
+                               //TODO make an array length function of some sort!
+                               prl(createComment("array length not known - LENGTH not aplicable to arrays",C_ERR));
+                               message("array length not known - LENGTH not aplicable to arrays",M_ERR);
+                               prl(createComment("put 1 on the stack for consistency",C_SPEC));
+                               prl(cmdToEStack(1));
+                               break;
+                       }
+                       
+                       case dup : {
+                                       prl(getTop());
+                                       prl(cmdToEStack("tempa"));
+                                       prl(cmdToEStack("tempa"));
+                                       break;                                  
+                       }
+                       case dup2 : {
+                                       prl(getTopTwo());
+                                       prl(cmdToEStack("tempb"));
+                                       prl(cmdToEStack("tempa"));
+                                       prl(cmdToEStack("tempb"));
+                                       prl(cmdToEStack("tempa"));
+                                       break;                                  
+                       }
+                       
+                       case pop : {
+                                       prl(cmdPopEStack());
+                                       break;                                  
+                       }
+                       
                        case jmp: {
                                prl("CALL a" + (counter + get2()) + ";");
                                break;
@@ -243,59 +535,85 @@ public class mjc2wsl{
                        case jgt:
                        case jge: {
                                prl(getTopTwo());
-                               prl("IF tempb >= tempa THEN CALL a" + (counter + get2())
+                               prl("IF tempb "+ getRelationFor(op)
+                                               +" tempa THEN CALL a" + (counter + get2())
+                                               +" ELSE CALL a" + (counter+1)
                                                + " FI;");
                                break;
                        }
 
-                       case add: {
-                               prl(getTopTwo());
-                               prl("tempres := tempb + tempa;");
-                               prl(cmdToEStack("tempres"));
+                       case call: {
+                               prl("CALL a" + (counter + get2()) + ";");
                                break;
                        }
-                       case div: {
-                               prl(getTopTwo());
-                               prl("tempres := tempb / tempa;");
-                               prl(cmdToEStack("tempres"));
+
+                       case return_: {
+                               //we let the actions return
+                               // there is nothing to clean up
+                               prl("SKIP END b"+counter+" ==");
                                break;
                        }
-
                        case enter: {
-                               prl(createComment("enter not fully procesed yet"));
-                               get();
-                               get();
+                               int parameters = get();
+                               
+                               int locals = get();
+                               prl(cmdToMStack("mjvm_locals"));
+                               prl("mjvm_locals := ARRAY("+locals+",0);");
+                               for (int i = parameters-1; i >= 0; i--)
+                                               prl(cmdFromEStack(loc(i)));
                                break;
                        }
-                       case return_: {
-                               prl(createComment("return not fully procesed yet"));
+                       case exit: {
+                               prl(cmdFromMStack("mjvm_locals"));
                                break;
                        }
-                       case exit: {
-                               prl(createComment("exit not fully procesed yet"));
+
+                       // read, print
+                       case bread:{
+                               //TODO make it a char for read
+                               message("char is read like a number", M_WAR);
+                               prl(createComment("char is read like a number",C_SPEC));
+                       }
+                       case read: {
+                               prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
+                               prl(cmdToEStack("tempa"));
                                break;
                        }
 
                        // the prints
-                       case bprint: {
-                               prl(getTopTwo());
-                               prl("PRINT(tempb);");
-                               break;
+                       case bprint:{
+                               // TODO need to make it a char on print
+                               message("chars will be printed as number codes", M_WAR);
+                               prl(createComment("char will be printed as a number code",C_SPEC));
                        }
                        case print: {
-                               // TODO need to make it a char
+                               // TODO printing numbers needs different lengths of spacing
                                prl(getTopTwo());
-                               prl("PRINT(tempb);");
+                               pr(createComment("print spacing",C_SPEC));
+                               prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
+                               prl("PRINFLUSH(tempb);");
+                               break;
+                       }
+
+                       case trap: {
+                               prl("ERROR(\"Runtime error: trap("+get()+")\");");
                                break;
                        }
+                       
+       
                        default:
                                prl(createComment("unknown op error: " + op, C_ERR));
+                               message("unknown op error: "+ op, M_ERR);
                                break;
                        }
 
+                       boolean wasJump = isJumpCode(op);
                        op = get();
                        if (op >= 0)
-                               prl("CALL a" + counter + " END");
+                               if (wasJump)
+                                               prl("SKIP END");
+                               else
+                                               prl("CALL a" + counter + " END");
                }
                prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
                prl(getStandardEnd());
@@ -313,9 +631,12 @@ public class mjc2wsl{
        public void printHelp() {
                System.out.println("MicroJava bytecode to WSL converter. v " + versionN
                                + ", by Doni Pracner");
-               System.out.println("usage:\n\t {options} mjc2wsl  filename [outfile]");
+               System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
                System.out.println("options:\n\t--screen print output to screen");
-               System.out.println("\t-o --oc include original code in comments");
+               System.out.println("\t-o --oc[+-] include original code in comments");
+               System.out.println("\t-v verbose, print warning messages");
+               System.out.println("\t-q don't print even the error messages");
+               System.out.println("\t-d print detailed debug messages");
        }
        
        public String makeDefaultOutName(String inname){
@@ -342,10 +663,28 @@ public class mjc2wsl{
                                                originalInComments = args[i].charAt(4) == '+';
                                        else
                                                originalInComments = true;
-                               } else if (args[i].startsWith("--screen")) {
+                               } else if (args[i].compareTo("--screen") == 0) {
                                        out = new PrintWriter(System.out);
-                               }
-                               i++;
+                               } else if (args[i].compareTo("-d") == 0) {
+                                       printLevel = M_DEB;//print debug info
+                               } else if (args[i].compareTo("-v") == 0) {
+                                       printLevel = M_WAR;//print warnings
+                               } else if (args[i].compareTo("-q") == 0) {
+                                       printLevel = M_ERR+1;//no printing                              
+                               } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
+                                       genPrintEStackOnChange = true;
+                               } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
+                                       genPauseAfterEachAddress = true;
+                               } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
+                                       genPrintForEachAddress = true;
+                               } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
+                                       genPrintForEachAddress = true;
+                                       genPauseAfterEachAddress = true;
+                               } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
+                                       genPrintEStackOnChange = true;
+                                       genPrintForEachAddress = true;
+                                       genPauseAfterEachAddress = true;
+                               }i++;
                        }
 
                        if (i >= args.length) {
@@ -377,6 +716,7 @@ public class mjc2wsl{
                                long mili = Calendar.getInstance().getTimeInMillis()
                                                - now.getTimeInMillis();
                                System.out.println("conversion time:" + mili + " ms");
+                               printMessageCounters();
                                out.close();
                        } else
                                System.out.println("file does not exist");
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner