gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
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 private TransMessages messages
= new TransMessages();
17 private boolean genPauseAfterEachAddress
=false,
18 genPrintForEachAddress
= false,
19 genPrintEStackOnChange
= false;
21 /** Constant used for marking a regular comment from the original file */
22 public static final char C_REG
= ' ';
24 * Constant used for marking when original code is inserted in the file,
25 * next to the translations
27 public static final char C_OC
= '#';
28 /** Constant used for marking special messages from the translator */
29 public static final char C_SPEC
= '&';
30 /** Constant used for marking error messages from the translator */
31 public static final char C_ERR
= '!';
33 /** instruction code in MicroJava bytecode. */
34 public static final int
93 private boolean originalInComments
= false;
95 private HashMap
<Integer
,String
> opMap
= null;
97 private String opCodeFile
= "mj-bytecodes.properties";
99 private HashMap
<Integer
, String
> getOpMap() {
101 opMap
= new HashMap
<Integer
, String
>(60, 0.98f
);
103 BufferedReader in
= new BufferedReader(new InputStreamReader(
104 getClass().getResourceAsStream(opCodeFile
)));
105 String str
= in
.readLine();
106 while (str
!= null) {
107 String
[] ss
= str
.split("=");
108 opMap
.put(Integer
.parseInt(ss
[0]), ss
[1]);
112 } catch (Exception ex
) {
113 ex
.printStackTrace();
119 public String
getOpString(int op
) {
120 return getOpMap().get(op
);
123 public String
describeOpCode(int op
) {
124 return op
+ " (" + getOpString(op
) + ")";
127 private InputStream mainIn
;
128 private PrintWriter out
= null;
129 private int counter
= -1;
131 private void pr(int i
){
135 private void pr(char i
){
139 private void pr(String i
){
143 private void prl(String i
){
152 res
= res
<< 24 >>> 24;
153 } catch (IOException ex
) {
154 ex
.printStackTrace();
161 return (get() * 256 + get()) << 16 >> 16;
165 return (get2() << 16) + (get2() << 16 >>> 16);
168 public String
createStandardStart(){
169 return createStandardStart(10);
172 public String
createStandardStart(int numWords
){
173 StringBuilder ret
= new StringBuilder(
174 "C:\" This file automatically converted from microjava bytecode\";\n"
175 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
177 ret
.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
178 ret
.append("mjvm_locals := ARRAY(1,0), ");
179 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0), ");
180 ret
.append("\n\tmjvm_arrays := < >, ");
181 ret
.append("\n\tmjvm_objects := < >, ");
182 ret
.append("\n mjvm_estack := < >, mjvm_mstack := < >, ");
183 ret
.append("\n mjvm_fp := 0, mjvm_sp := 0,");
184 ret
.append("\n t_e_m_p := 0 > :");
186 return ret
.toString();
189 public String
createStandardEnd(){
190 return "SKIP\nENDVAR";
193 private String
createLocal(int i
) {
194 // arrays start at 1 in WSL, so we need an offset
195 return "mjvm_locals[" + (i
+ 1) + "]";
198 private String
createStatic(int i
) {
199 return "mjvm_statics[" + (i
+ 1) + "]";
202 private String
createArray(int i
) {
203 return "mjvm_arrays[" + i
+ "]";
206 private String
createArray(String i
) {
207 return "mjvm_arrays[" + i
+ "]";
210 private String
createObject(String i
) {
211 return "mjvm_objects[" + i
+ "]";
215 * Creates a WSL comment with care to quote chars.
217 public static String
createComment(String str
){
218 return createComment(str
, C_REG
);
222 * Creates a WSL comment with care to quote chars, of the
223 * given type. Types are given as char constants. They can be
224 * default comments, comments that contain the original code
225 * in them, or additional comments regarding the translation
228 public static String
createComment(String str
, char type
) {
229 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
234 private String
createToEStack(int i
) {
235 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
236 if (genPrintEStackOnChange
)
237 res
+= "PRINT(\"eStack\",mjvm_estack);";
241 private String
createToEStack(String i
) {
242 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
243 if (genPrintEStackOnChange
)
244 res
+= "PRINT(\"eStack\",mjvm_estack);";
248 private String
createFromEStack(String st
) {
250 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
251 if (genPrintEStackOnChange
)
252 res
+= "PRINT(\"eStack\",mjvm_estack);";
256 private String
createPopEStack() {
257 String res
= "mjvm_estack := TAIL(mjvm_estack);";
258 if (genPrintEStackOnChange
)
259 res
+= "PRINT(\"eStack\",mjvm_estack);";
263 private String
createTopTwoEStack() {
264 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
267 private String
createTopEStack() {
268 return createFromEStack("tempa");
273 private String
createToMStack(int i
) {
274 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
277 private String
createToMStack(String i
) {
278 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
281 private String
createFromMStack(String st
) {
282 return st
+ " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
285 private String
getRelationFor(int opcode
) throws Exception
{
287 case jeq
: return "=";
288 case jne
: return "<>";
289 case jlt
: return "<";
290 case jle
: return "<=";
291 case jgt
: return ">";
292 case jge
: return ">=";
294 throw new Exception("Wrong opcode for a relation");
297 private boolean isJumpCode(int opcode
) {
298 return (opcode
>= jmp
) && (opcode
<= jge
);
301 public void convertStream(InputStream ins
) throws Exception
{
304 byte m
= (byte) get();
305 byte j
= (byte) get();
306 if (m
!='M' || j
!='J')
307 throw new Exception("Wrong start of bytecode file");
308 int codesize
= get4();
309 int numberOfWords
= get4();
310 int mainAdr
= get4();
312 prl(createStandardStart(numberOfWords
));
313 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a" + (14 + mainAdr
)
317 if (originalInComments
)
318 prl(createComment(describeOpCode(op
), C_OC
));
319 prl("a" + counter
+ " == ");
320 if (genPrintForEachAddress
) {
321 prl("PRINT(\"a" + counter
+ "\");");
322 if (genPauseAfterEachAddress
)
323 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
327 prl(createToEStack(createLocal(get())));
334 prl(createToEStack(createLocal(op
- load_0
)));
338 prl(createFromEStack(createLocal(get())));
345 prl(createFromEStack(createLocal(op
- store_0
)));
350 prl(createToEStack(createStatic(get2())));
354 prl(createFromEStack(createStatic(get2())));
360 prl(createTopEStack());
361 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
366 // we need to use a temparray as a pointer, WSL
367 // otherwise tries to access it as a list of lists and fails
368 prl(createTopTwoEStack());
369 prl("VAR < tempArray := " + createObject("tempb") + " > :");
370 prl("tempArray[" + (f
+ 1) + "]:=tempa ENDVAR;");
375 prl(createToEStack(get4()));
385 prl(createToEStack(op
- const_0
));
390 prl(createTopTwoEStack());
391 prl("tempres := tempb + tempa;");
392 prl(createToEStack("tempres"));
396 prl(createTopTwoEStack());
397 prl("tempres := tempb - tempa;");
398 prl(createToEStack("tempres"));
402 prl(createTopTwoEStack());
403 prl("tempres := tempb * tempa;");
404 prl(createToEStack("tempres"));
408 prl(createTopTwoEStack());
409 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
410 prl("tempres := tempb DIV tempa;");
411 prl(createToEStack("tempres"));
415 prl(createTopTwoEStack());
416 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
417 prl("tempres := tempb MOD tempa;");
418 prl(createToEStack("tempres"));
423 prl(createTopEStack());
424 prl(createToEStack("-tempa"));
429 prl(createTopTwoEStack());
430 prl("VAR <tempres :=tempb, i:=1 >:");
431 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
432 prl(createToEStack("tempres"));
437 prl(createTopTwoEStack());
438 prl("VAR <tempres :=tempb, i:=1 >:");
439 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
440 prl(createToEStack("tempres"));
446 int b1
= get(), b2
= get();
447 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
453 // TODO maybe objects and arrays should be in the same list?
454 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
456 prl(createToEStack("LENGTH(mjvm_objects)"));
460 get();// 0 - bytes, 1 - words; ignore for now
461 // TODO take into consideration 0/1
462 prl(createTopEStack());
463 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
464 prl(createToEStack("LENGTH(mjvm_arrays)"));
470 prl(createTopTwoEStack());
471 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
476 prl(createFromEStack("tempres"));
477 prl(createTopTwoEStack());
478 // we need to use a temparray as a pointer, WSL
479 // otherwise tries to access it as a list of lists and fails
480 prl("VAR < tempArray := " + createArray("tempb") + " > :");
481 prl("tempArray[tempa+1]:=tempres ENDVAR;");
485 prl(createTopEStack());
486 // TODO make an array length function of some sort!
488 "array length not known - LENGTH not aplicable to arrays",
490 messages
.message("array length not known - LENGTH not aplicable to arrays", TransMessages
.M_ERR
);
491 prl(createComment("put 1 on the stack for consistency", C_SPEC
));
492 prl(createToEStack(1));
497 prl(createTopEStack());
498 prl(createToEStack("tempa"));
499 prl(createToEStack("tempa"));
503 prl(createTopTwoEStack());
504 prl(createToEStack("tempb"));
505 prl(createToEStack("tempa"));
506 prl(createToEStack("tempb"));
507 prl(createToEStack("tempa"));
512 prl(createPopEStack());
517 prl("CALL a" + (counter
+ get2()) + ";");
527 prl(createTopTwoEStack());
528 prl("IF tempb " + getRelationFor(op
) + " tempa THEN CALL a"
529 + (counter
+ get2()) + " ELSE CALL a" + (counter
+ 1)
535 prl("CALL a" + (counter
+ get2()) + ";");
540 // we let the actions return
541 // there is nothing to clean up
542 prl("SKIP END b" + counter
+ " ==");
546 int parameters
= get();
549 prl(createToMStack("mjvm_locals"));
550 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
551 for (int i
= parameters
- 1; i
>= 0; i
--)
552 prl(createFromEStack(createLocal(i
)));
556 prl(createFromMStack("mjvm_locals"));
562 // TODO make it a char for read
563 messages
.message("char is read like a number", TransMessages
.M_WAR
);
564 prl(createComment("char is read like a number", C_SPEC
));
567 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
568 prl(createToEStack("tempa"));
574 // TODO need to make it a char on print
575 messages
.message("chars will be printed as number codes", TransMessages
.M_WAR
);
576 prl(createComment("char will be printed as a number code",
580 // TODO printing numbers needs different lengths of spacing
581 prl(createTopTwoEStack());
582 pr(createComment("print spacing", C_SPEC
));
583 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
584 prl("PRINFLUSH(tempb);");
589 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
594 prl(createComment("unknown op error: " + op
, C_ERR
));
595 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
599 boolean wasJump
= isJumpCode(op
);
605 prl("CALL a" + counter
+ " END");
607 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
608 prl(createStandardEnd());
611 public void convertFile(File f
) {
613 convertStream(new FileInputStream(f
));
614 } catch (Exception ex
) {
615 ex
.printStackTrace();
619 public void printHelp() {
620 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
621 + ", by Doni Pracner");
622 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
623 System
.out
.println("options:\n\t--screen print output to screen");
624 System
.out
.println("\t-o --oc[+-] include original code in comments");
625 System
.out
.println("\t-v verbose, print warning messages");
626 System
.out
.println("\t-q don't print even the error messages");
627 System
.out
.println("\t-d print detailed debug messages");
630 public String
makeDefaultOutName(String inname
){
632 if (inname
.endsWith(".obj"))
633 rez
= rez
.substring(0, rez
.length() - 4);
637 public void run(String
[] args
) {
638 if (args
.length
== 0) {
642 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
643 if (args
[i
].compareTo("-h") == 0) {
646 } else if (args
[i
].compareTo("-o") == 0
647 || args
[i
].startsWith("--oc")) {
648 if (args
[i
].length() == 2)
649 originalInComments
= true;
650 else if (args
[i
].length() == 5)
651 originalInComments
= args
[i
].charAt(4) == '+';
653 originalInComments
= true;
654 } else if (args
[i
].compareTo("--screen") == 0) {
655 out
= new PrintWriter(System
.out
);
656 } else if (args
[i
].compareTo("-d") == 0) {
657 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
658 } else if (args
[i
].compareTo("-v") == 0) {
659 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
660 } else if (args
[i
].compareTo("-q") == 0) {
661 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
662 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
663 genPrintEStackOnChange
= true;
664 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
665 genPauseAfterEachAddress
= true;
666 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
667 genPrintForEachAddress
= true;
668 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
669 genPrintForEachAddress
= true;
670 genPauseAfterEachAddress
= true;
671 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
672 genPrintEStackOnChange
= true;
673 genPrintForEachAddress
= true;
674 genPauseAfterEachAddress
= true;
679 if (i
>= args
.length
) {
680 System
.out
.println("no filename supplied");
683 File f
= new File(args
[i
]);
685 if (i
+ 1 < args
.length
) {
687 out
= new PrintWriter(args
[i
+ 1]);
688 } catch (Exception e
) {
689 System
.err
.println("error in opening out file:");
694 // if not set to screen, or a file, make a default filename
696 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
697 } catch (Exception e
) {
698 System
.err
.println("error in opening out file:");
703 Calendar now
= Calendar
.getInstance();
705 long mili
= Calendar
.getInstance().getTimeInMillis()
706 - now
.getTimeInMillis();
707 System
.out
.println("conversion time:" + mili
+ " ms");
708 messages
.printMessageCounters();
711 System
.out
.println("file does not exist");
715 public static void main(String
[] args
) {
716 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner