gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
refactor - extract the Messages system into a new class
[mjc2wsl.git] / src / mjc2wsl.java
1 import java.io.*;
2 import java.util.*;
4 /**
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
8 * "Java ME".
9 *
10 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
11 */
12 public class mjc2wsl{
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 = ' ';
23 /**
24 * Constant used for marking when original code is inserted in the file,
25 * next to the translations
26 */
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
35 load = 1,
36 load_0 = 2,
37 load_1 = 3,
38 load_2 = 4,
39 load_3 = 5,
40 store = 6,
41 store_0 = 7,
42 store_1 = 8,
43 store_2 = 9,
44 store_3 = 10,
45 getstatic = 11,
46 putstatic = 12,
47 getfield = 13,
48 putfield = 14,
49 const_0 = 15,
50 const_1 = 16,
51 const_2 = 17,
52 const_3 = 18,
53 const_4 = 19,
54 const_5 = 20,
55 const_m1 = 21,
56 const_ = 22,
57 add = 23,
58 sub = 24,
59 mul = 25,
60 div = 26,
61 rem = 27,
62 neg = 28,
63 shl = 29,
64 shr = 30,
65 inc = 31,
66 new_ = 32,
67 newarray = 33,
68 aload = 34,
69 astore = 35,
70 baload = 36,
71 bastore = 37,
72 arraylength = 38,
73 pop = 39,
74 dup = 40,
75 dup2 = 41,
76 jmp = 42,
77 jeq = 43,
78 jne = 44,
79 jlt = 45,
80 jle = 46,
81 jgt = 47,
82 jge = 48,
83 call = 49,
84 return_ = 50,
85 enter = 51,
86 exit = 52,
87 read = 53,
88 print = 54,
89 bread = 55,
90 bprint = 56,
91 trap = 57;
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() {
100 if (opMap == null) {
101 opMap = new HashMap<Integer, String>(60, 0.98f);
102 try {
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]);
109 str = in.readLine();
111 in.close();
112 } catch (Exception ex) {
113 ex.printStackTrace();
116 return opMap;
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){
132 out.print(i);
135 private void pr(char i){
136 out.print(i);
139 private void pr(String i){
140 out.print(i);
143 private void prl(String i){
144 out.println(i);
147 private int get() {
148 int res = -1;
149 try {
150 res = mainIn.read();
151 if (res >= 0)
152 res = res << 24 >>> 24;
153 } catch (IOException ex) {
154 ex.printStackTrace();
156 counter++;
157 return res;
160 private int get2() {
161 return (get() * 256 + get()) << 16 >> 16;
164 private int get4() {
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 + "]";
214 /**
215 * Creates a WSL comment with care to quote chars.
216 */
217 public static String createComment(String str){
218 return createComment(str, C_REG);
221 /**
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
226 * process.
227 */
228 public static String createComment(String str, char type) {
229 return "C:\"" + type + str.replace("\"", "''") + "\";";
232 //Expression stack
234 private String createToEStack(int i) {
235 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
236 if (genPrintEStackOnChange)
237 res += "PRINT(\"eStack\",mjvm_estack);";
238 return res;
241 private String createToEStack(String i) {
242 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
243 if (genPrintEStackOnChange)
244 res += "PRINT(\"eStack\",mjvm_estack);";
245 return res;
248 private String createFromEStack(String st) {
249 String res = st
250 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
251 if (genPrintEStackOnChange)
252 res += "PRINT(\"eStack\",mjvm_estack);";
253 return res;
256 private String createPopEStack() {
257 String res = "mjvm_estack := TAIL(mjvm_estack);";
258 if (genPrintEStackOnChange)
259 res += "PRINT(\"eStack\",mjvm_estack);";
260 return res;
263 private String createTopTwoEStack() {
264 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
267 private String createTopEStack() {
268 return createFromEStack("tempa");
271 //Method stack
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 {
286 switch (opcode) {
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{
302 mainIn = ins;
303 //process start
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)
314 + " END");
315 int op = get();
316 while (op >= 0) {
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);");
325 switch (op) {
326 case load: {
327 prl(createToEStack(createLocal(get())));
328 break;
330 case load_0:
331 case load_1:
332 case load_2:
333 case load_3: {
334 prl(createToEStack(createLocal(op - load_0)));
335 break;
337 case store: {
338 prl(createFromEStack(createLocal(get())));
339 break;
341 case store_0:
342 case store_1:
343 case store_2:
344 case store_3: {
345 prl(createFromEStack(createLocal(op - store_0)));
346 break;
349 case getstatic: {
350 prl(createToEStack(createStatic(get2())));
351 break;
353 case putstatic: {
354 prl(createFromEStack(createStatic(get2())));
355 break;
358 case getfield: {
359 int f = get2();
360 prl(createTopEStack());
361 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
362 break;
364 case putfield: {
365 int f = get2();
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;");
371 break;
374 case const_: {
375 prl(createToEStack(get4()));
376 break;
379 case const_0:
380 case const_1:
381 case const_2:
382 case const_3:
383 case const_4:
384 case const_5: {
385 prl(createToEStack(op - const_0));
386 break;
389 case add: {
390 prl(createTopTwoEStack());
391 prl("tempres := tempb + tempa;");
392 prl(createToEStack("tempres"));
393 break;
395 case sub: {
396 prl(createTopTwoEStack());
397 prl("tempres := tempb - tempa;");
398 prl(createToEStack("tempres"));
399 break;
401 case mul: {
402 prl(createTopTwoEStack());
403 prl("tempres := tempb * tempa;");
404 prl(createToEStack("tempres"));
405 break;
407 case div: {
408 prl(createTopTwoEStack());
409 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
410 prl("tempres := tempb DIV tempa;");
411 prl(createToEStack("tempres"));
412 break;
414 case rem: {
415 prl(createTopTwoEStack());
416 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
417 prl("tempres := tempb MOD tempa;");
418 prl(createToEStack("tempres"));
419 break;
422 case neg: {
423 prl(createTopEStack());
424 prl(createToEStack("-tempa"));
425 break;
428 case shl: {
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"));
433 prl("ENDVAR;");
434 break;
436 case shr: {
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"));
441 prl("ENDVAR;");
442 break;
445 case inc: {
446 int b1 = get(), b2 = get();
447 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
448 break;
451 case new_: {
452 int size = get2();
453 // TODO maybe objects and arrays should be in the same list?
454 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
455 + ",0) >;");
456 prl(createToEStack("LENGTH(mjvm_objects)"));
457 break;
459 case newarray: {
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)"));
465 break;
468 case aload:
469 case baload: {
470 prl(createTopTwoEStack());
471 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
472 break;
474 case astore:
475 case bastore: {
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;");
482 break;
484 case arraylength: {
485 prl(createTopEStack());
486 // TODO make an array length function of some sort!
487 prl(createComment(
488 "array length not known - LENGTH not aplicable to arrays",
489 C_ERR));
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));
493 break;
496 case dup: {
497 prl(createTopEStack());
498 prl(createToEStack("tempa"));
499 prl(createToEStack("tempa"));
500 break;
502 case dup2: {
503 prl(createTopTwoEStack());
504 prl(createToEStack("tempb"));
505 prl(createToEStack("tempa"));
506 prl(createToEStack("tempb"));
507 prl(createToEStack("tempa"));
508 break;
511 case pop: {
512 prl(createPopEStack());
513 break;
516 case jmp: {
517 prl("CALL a" + (counter + get2()) + ";");
518 break;
521 case jeq:
522 case jne:
523 case jlt:
524 case jle:
525 case jgt:
526 case jge: {
527 prl(createTopTwoEStack());
528 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
529 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
530 + " FI;");
531 break;
534 case call: {
535 prl("CALL a" + (counter + get2()) + ";");
536 break;
539 case return_: {
540 // we let the actions return
541 // there is nothing to clean up
542 prl("SKIP END b" + counter + " ==");
543 break;
545 case enter: {
546 int parameters = get();
548 int locals = 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)));
553 break;
555 case exit: {
556 prl(createFromMStack("mjvm_locals"));
557 break;
560 // read, print
561 case bread: {
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));
566 case read: {
567 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
568 prl(createToEStack("tempa"));
569 break;
572 // the prints
573 case bprint: {
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",
577 C_SPEC));
579 case print: {
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);");
585 break;
588 case trap: {
589 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
590 break;
593 default:
594 prl(createComment("unknown op error: " + op, C_ERR));
595 messages.message("unknown op error: " + op, TransMessages.M_ERR);
596 break;
599 boolean wasJump = isJumpCode(op);
600 op = get();
601 if (op >= 0)
602 if (wasJump)
603 prl("SKIP END");
604 else
605 prl("CALL a" + counter + " END");
607 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
608 prl(createStandardEnd());
611 public void convertFile(File f) {
612 try {
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){
631 String rez = inname;
632 if (inname.endsWith(".obj"))
633 rez = rez.substring(0, rez.length() - 4);
634 return rez + ".wsl";
637 public void run(String[] args) {
638 if (args.length == 0) {
639 printHelp();
640 } else {
641 int i = 0;
642 while (i < args.length && args[i].charAt(0) == '-') {
643 if (args[i].compareTo("-h") == 0) {
644 printHelp();
645 return;
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) == '+';
652 else
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;
676 i++;
679 if (i >= args.length) {
680 System.out.println("no filename supplied");
681 System.exit(2);
683 File f = new File(args[i]);
685 if (i + 1 < args.length) {
686 try {
687 out = new PrintWriter(args[i + 1]);
688 } catch (Exception e) {
689 System.err.println("error in opening out file:");
690 e.printStackTrace();
693 if (out == null) {
694 // if not set to screen, or a file, make a default filename
695 try {
696 out = new PrintWriter(makeDefaultOutName(args[i]));
697 } catch (Exception e) {
698 System.err.println("error in opening out file:");
699 e.printStackTrace();
702 if (f.exists()) {
703 Calendar now = Calendar.getInstance();
704 convertFile(f);
705 long mili = Calendar.getInstance().getTimeInMillis()
706 - now.getTimeInMillis();
707 System.out.println("conversion time:" + mili + " ms");
708 messages.printMessageCounters();
709 out.close();
710 } else
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