gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
003081897da1d559f6220449cdd7bd6517f1d2c2
5 * This program converts file from compiled MicroJava bytecode to WSL language
6 * which is a part of the FermaT Transformation system. MicroJava is a subset
7 * used in Compiler Construction courses by Hanspeter Moessenboeck, not
10 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
13 public static String versionN
= "0.1.4";
15 public static final int M_ERR
= 2, M_WAR
= 1, M_DEB
= 0;
17 private int printLevel
= M_ERR
;
19 private int[] messageCounters
= new int[M_ERR
+1];
21 private void message(String mes
, int level
){
22 if (level
>=printLevel
)
23 System
.out
.println(mes
);
24 messageCounters
[level
]++;
27 private void printMessageCounters(){
28 printMessageCounters(System
.out
);
31 private void printMessageCounters(PrintStream out
){
32 out
.println("total errors:"+messageCounters
[M_ERR
]+" warnings:"+messageCounters
[M_WAR
]);
35 private boolean genPauseAfterEachAddress
=false,
36 genPrintForEachAddress
= false,
37 genPrintEStackOnChange
= false;
39 /** Constant used for marking a regular comment from the original file */
40 public static final char C_REG
= ' ';
42 * Constant used for marking when original code is inserted in the file,
43 * next to the translations
45 public static final char C_OC
= '#';
46 /** Constant used for marking special messages from the translator */
47 public static final char C_SPEC
= '&';
48 /** Constant used for marking error messages from the translator */
49 public static final char C_ERR
= '!';
51 /** instruction code in MicroJava bytecode. */
52 public static final int
111 public String
getStandardStart(){
112 return getStandardStart(10);
115 public String
getStandardStart(int numWords
){
116 StringBuilder ret
= new StringBuilder(
117 "C:\" This file automatically converted from microjava bytecode\";\n"
118 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
120 ret
.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
121 ret
.append("mjvm_locals := ARRAY(1,0), ");
122 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0), ");
123 ret
.append("\n\tmjvm_arrays := < >, ");
124 ret
.append("\n\tmjvm_objects := < >, ");
125 ret
.append("\n mjvm_estack := < >, mjvm_mstack := < >, ");
126 ret
.append("\n mjvm_fp := 0, mjvm_sp := 0,");
127 ret
.append("\n t_e_m_p := 0 > :");
129 return ret
.toString();
132 public String
getStandardEnd(){
133 return "SKIP\nENDVAR";
136 private boolean originalInComments
= false;
138 private HashMap
<Integer
,String
> opMap
= null;
140 private String opCodeFile
= "mj-bytecodes.properties";
142 private HashMap
<Integer
, String
> getOpMap() {
144 opMap
= new HashMap
<Integer
, String
>(60, 0.98f
);
146 BufferedReader in
= new BufferedReader(new InputStreamReader(
147 getClass().getResourceAsStream(opCodeFile
)));
148 String str
= in
.readLine();
149 while (str
!= null) {
150 String
[] ss
= str
.split("=");
151 opMap
.put(Integer
.parseInt(ss
[0]), ss
[1]);
155 } catch (Exception ex
) {
156 ex
.printStackTrace();
162 public String
getOpString(int op
) {
163 return getOpMap().get(op
);
166 public String
describeOpCode(int op
) {
167 return op
+ " (" + getOpString(op
) + ")";
170 private InputStream mainIn
;
171 private PrintWriter out
= null;
172 private int counter
= -1;
174 private void pr(int i
){
178 private void pr(char i
){
182 private void pr(String i
){
186 private void prl(String i
){
195 res
= res
<< 24 >>> 24;
196 } catch (IOException ex
) {
197 ex
.printStackTrace();
204 return (get() * 256 + get()) << 16 >> 16;
208 return (get2() << 16) + (get2() << 16 >>> 16);
211 private String
loc(int i
) {
212 // arrays start at 1 in WSL, so we need an offset
213 return "mjvm_locals[" + (i
+ 1) + "]";
216 private String
genStatic(int i
) {
217 return "mjvm_statics[" + (i
+ 1) + "]";
220 private String
genArray(int i
) {
221 return "mjvm_arrays[" + i
+ "]";
224 private String
genArray(String i
) {
225 return "mjvm_arrays[" + i
+ "]";
228 private String
genObject(String i
) {
229 return "mjvm_objects[" + i
+ "]";
233 * Creates a WSL comment with care to quote chars.
235 public static String
createComment(String str
){
236 return createComment(str
, C_REG
);
240 * Creates a WSL comment with care to quote chars, of the
241 * given type. Types are given as char constants. They can be
242 * default comments, comments that contain the original code
243 * in them, or additional comments regarding the translation
246 public static String
createComment(String str
, char type
) {
247 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
252 private String
cmdToEStack(int i
) {
253 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
254 if (genPrintEStackOnChange
)
255 res
+= "PRINT(\"eStack\",mjvm_estack);";
259 private String
cmdToEStack(String i
) {
260 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
261 if (genPrintEStackOnChange
)
262 res
+= "PRINT(\"eStack\",mjvm_estack);";
266 private String
cmdFromEStack(String st
) {
268 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
269 if (genPrintEStackOnChange
)
270 res
+= "PRINT(\"eStack\",mjvm_estack);";
274 private String
cmdPopEStack() {
275 String res
= "mjvm_estack := TAIL(mjvm_estack);";
276 if (genPrintEStackOnChange
)
277 res
+= "PRINT(\"eStack\",mjvm_estack);";
281 private String
getTopTwo() {
282 return cmdFromEStack("tempa") + "\n" + cmdFromEStack("tempb");
285 private String
getTop() {
286 return cmdFromEStack("tempa");
291 private String
cmdToMStack(int i
) {
292 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
295 private String
cmdToMStack(String i
) {
296 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
299 private String
cmdFromMStack(String st
) {
300 return st
+ " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
303 private String
getRelationFor(int opcode
) throws Exception
{
305 case jeq
: return "=";
306 case jne
: return "<>";
307 case jlt
: return "<";
308 case jle
: return "<=";
309 case jgt
: return ">";
310 case jge
: return ">=";
312 throw new Exception("Wrong opcode for a relation");
315 private boolean isJumpCode(int opcode
) {
316 return (opcode
>= jmp
) && (opcode
<= jge
);
319 public void convertStream(InputStream ins
) throws Exception
{
322 byte m
= (byte) get();
323 byte j
= (byte) get();
324 if (m
!='M' || j
!='J')
325 throw new Exception("Wrong start of bytecode file");
326 int codesize
= get4();
327 int numberOfWords
= get4();
328 int mainAdr
= get4();
330 prl(getStandardStart(numberOfWords
));
331 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a" + (14 + mainAdr
)
335 if (originalInComments
)
336 prl(createComment(describeOpCode(op
), C_OC
));
337 prl("a" + counter
+ " == ");
338 if (genPrintForEachAddress
) {
339 prl("PRINT(\"a" + counter
+ "\");");
340 if (genPauseAfterEachAddress
)
341 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
345 prl(cmdToEStack(loc(get())));
352 prl(cmdToEStack(loc(op
- load_0
)));
356 prl(cmdFromEStack(loc(get())));
363 prl(cmdFromEStack(loc(op
- store_0
)));
368 prl(cmdToEStack(genStatic(get2())));
372 prl(cmdFromEStack(genStatic(get2())));
379 prl(cmdToEStack(genObject("tempa") + "[" + (f
+ 1) + "]"));
384 // we need to use a temparray as a pointer, WSL
385 // otherwise tries to access it as a list of lists and fails
387 prl("VAR < tempArray := " + genObject("tempb") + " > :");
388 prl("tempArray[" + (f
+ 1) + "]:=tempa ENDVAR;");
393 prl(cmdToEStack(get4()));
403 prl(cmdToEStack(op
- const_0
));
409 prl("tempres := tempb + tempa;");
410 prl(cmdToEStack("tempres"));
415 prl("tempres := tempb - tempa;");
416 prl(cmdToEStack("tempres"));
421 prl("tempres := tempb * tempa;");
422 prl(cmdToEStack("tempres"));
427 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
428 prl("tempres := tempb DIV tempa;");
429 prl(cmdToEStack("tempres"));
434 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
435 prl("tempres := tempb MOD tempa;");
436 prl(cmdToEStack("tempres"));
442 prl(cmdToEStack("-tempa"));
448 prl("VAR <tempres :=tempb, i:=1 >:");
449 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
450 prl(cmdToEStack("tempres"));
456 prl("VAR <tempres :=tempb, i:=1 >:");
457 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
458 prl(cmdToEStack("tempres"));
464 int b1
= get(), b2
= get();
465 prl(loc(b1
) + " := " + loc(b1
) + " + " + b2
+ ";");
471 // TODO maybe objects and arrays should be in the same list?
472 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
474 prl(cmdToEStack("LENGTH(mjvm_objects)"));
478 get();// 0 - bytes, 1 - words; ignore for now
479 // TODO take into consideration 0/1
481 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
482 prl(cmdToEStack("LENGTH(mjvm_arrays)"));
489 prl(cmdToEStack(genArray("tempb") + "[tempa+1]"));
494 prl(cmdFromEStack("tempres"));
496 // we need to use a temparray as a pointer, WSL
497 // otherwise tries to access it as a list of lists and fails
498 prl("VAR < tempArray := " + genArray("tempb") + " > :");
499 prl("tempArray[tempa+1]:=tempres ENDVAR;");
504 // TODO make an array length function of some sort!
506 "array length not known - LENGTH not aplicable to arrays",
508 message("array length not known - LENGTH not aplicable to arrays",
510 prl(createComment("put 1 on the stack for consistency", C_SPEC
));
517 prl(cmdToEStack("tempa"));
518 prl(cmdToEStack("tempa"));
523 prl(cmdToEStack("tempb"));
524 prl(cmdToEStack("tempa"));
525 prl(cmdToEStack("tempb"));
526 prl(cmdToEStack("tempa"));
536 prl("CALL a" + (counter
+ get2()) + ";");
547 prl("IF tempb " + getRelationFor(op
) + " tempa THEN CALL a"
548 + (counter
+ get2()) + " ELSE CALL a" + (counter
+ 1)
554 prl("CALL a" + (counter
+ get2()) + ";");
559 // we let the actions return
560 // there is nothing to clean up
561 prl("SKIP END b" + counter
+ " ==");
565 int parameters
= get();
568 prl(cmdToMStack("mjvm_locals"));
569 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
570 for (int i
= parameters
- 1; i
>= 0; i
--)
571 prl(cmdFromEStack(loc(i
)));
575 prl(cmdFromMStack("mjvm_locals"));
581 // TODO make it a char for read
582 message("char is read like a number", M_WAR
);
583 prl(createComment("char is read like a number", C_SPEC
));
586 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
587 prl(cmdToEStack("tempa"));
593 // TODO need to make it a char on print
594 message("chars will be printed as number codes", M_WAR
);
595 prl(createComment("char will be printed as a number code",
599 // TODO printing numbers needs different lengths of spacing
601 pr(createComment("print spacing", C_SPEC
));
602 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
603 prl("PRINFLUSH(tempb);");
608 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
613 prl(createComment("unknown op error: " + op
, C_ERR
));
614 message("unknown op error: " + op
, M_ERR
);
618 boolean wasJump
= isJumpCode(op
);
624 prl("CALL a" + counter
+ " END");
626 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
627 prl(getStandardEnd());
630 public void convertFile(File f
) {
632 convertStream(new FileInputStream(f
));
633 } catch (Exception ex
) {
634 ex
.printStackTrace();
638 public void printHelp() {
639 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
640 + ", by Doni Pracner");
641 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
642 System
.out
.println("options:\n\t--screen print output to screen");
643 System
.out
.println("\t-o --oc[+-] include original code in comments");
644 System
.out
.println("\t-v verbose, print warning messages");
645 System
.out
.println("\t-q don't print even the error messages");
646 System
.out
.println("\t-d print detailed debug messages");
649 public String
makeDefaultOutName(String inname
){
651 if (inname
.endsWith(".obj"))
652 rez
= rez
.substring(0, rez
.length() - 4);
656 public void run(String
[] args
) {
657 if (args
.length
== 0) {
661 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
662 if (args
[i
].compareTo("-h") == 0) {
665 } else if (args
[i
].compareTo("-o") == 0
666 || args
[i
].startsWith("--oc")) {
667 if (args
[i
].length() == 2)
668 originalInComments
= true;
669 else if (args
[i
].length() == 5)
670 originalInComments
= args
[i
].charAt(4) == '+';
672 originalInComments
= true;
673 } else if (args
[i
].compareTo("--screen") == 0) {
674 out
= new PrintWriter(System
.out
);
675 } else if (args
[i
].compareTo("-d") == 0) {
676 printLevel
= M_DEB
;// print debug info
677 } else if (args
[i
].compareTo("-v") == 0) {
678 printLevel
= M_WAR
;// print warnings
679 } else if (args
[i
].compareTo("-q") == 0) {
680 printLevel
= M_ERR
+ 1;// no printing
681 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
682 genPrintEStackOnChange
= true;
683 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
684 genPauseAfterEachAddress
= true;
685 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
686 genPrintForEachAddress
= true;
687 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
688 genPrintForEachAddress
= true;
689 genPauseAfterEachAddress
= true;
690 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
691 genPrintEStackOnChange
= true;
692 genPrintForEachAddress
= true;
693 genPauseAfterEachAddress
= true;
698 if (i
>= args
.length
) {
699 System
.out
.println("no filename supplied");
702 File f
= new File(args
[i
]);
704 if (i
+ 1 < args
.length
) {
706 out
= new PrintWriter(args
[i
+ 1]);
707 } catch (Exception e
) {
708 System
.err
.println("error in opening out file:");
713 // if not set to screen, or a file, make a default filename
715 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
716 } catch (Exception e
) {
717 System
.err
.println("error in opening out file:");
722 Calendar now
= Calendar
.getInstance();
724 long mili
= Calendar
.getInstance().getTimeInMillis()
725 - now
.getTimeInMillis();
726 System
.out
.println("conversion time:" + mili
+ " ms");
727 printMessageCounters();
730 System
.out
.println("file does not exist");
734 public static void main(String
[] args
) {
735 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner