gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
ant - updates to use the jar for the MJ compiler. The compiler.class.dir can still...
[mjc2wsl.git] / src / mjc2wsl.java
1 /*
2 Copyright (C) 2014 Doni Pracner
4 This file is part of mjc2wsl.
6 mjc2wsl is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 mjc2wsl is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with mjc2wsl. If not, see <http://www.gnu.org/licenses/>.
18 */
19 import java.io.*;
20 import java.util.*;
22 /**
23 * This program converts file from compiled MicroJava bytecode to WSL language
24 * which is a part of the FermaT Transformation system. MicroJava is a subset
25 * used in Compiler Construction courses by Hanspeter Moessenboeck, not
26 * "Java ME".
27 *
28 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
29 */
30 public class mjc2wsl{
31 public static String versionN = "0.1.5";
33 private TransMessages messages = new TransMessages();
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 = ' ';
41 /**
42 * Constant used for marking when original code is inserted in the file,
43 * next to the translations
44 */
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
53 load = 1,
54 load_0 = 2,
55 load_1 = 3,
56 load_2 = 4,
57 load_3 = 5,
58 store = 6,
59 store_0 = 7,
60 store_1 = 8,
61 store_2 = 9,
62 store_3 = 10,
63 getstatic = 11,
64 putstatic = 12,
65 getfield = 13,
66 putfield = 14,
67 const_0 = 15,
68 const_1 = 16,
69 const_2 = 17,
70 const_3 = 18,
71 const_4 = 19,
72 const_5 = 20,
73 const_m1 = 21,
74 const_ = 22,
75 add = 23,
76 sub = 24,
77 mul = 25,
78 div = 26,
79 rem = 27,
80 neg = 28,
81 shl = 29,
82 shr = 30,
83 inc = 31,
84 new_ = 32,
85 newarray = 33,
86 aload = 34,
87 astore = 35,
88 baload = 36,
89 bastore = 37,
90 arraylength = 38,
91 pop = 39,
92 dup = 40,
93 dup2 = 41,
94 jmp = 42,
95 jeq = 43,
96 jne = 44,
97 jlt = 45,
98 jle = 46,
99 jgt = 47,
100 jge = 48,
101 call = 49,
102 return_ = 50,
103 enter = 51,
104 exit = 52,
105 read = 53,
106 print = 54,
107 bread = 55,
108 bprint = 56,
109 trap = 57;
111 private boolean originalInComments = false;
113 private HashMap<Integer,String> opMap = null;
115 private String opCodeFile = "mj-bytecodes.properties";
117 private HashMap<Integer, String> getOpMap() {
118 if (opMap == null) {
119 opMap = new HashMap<Integer, String>(60, 0.98f);
120 try {
121 BufferedReader in = new BufferedReader(new InputStreamReader(
122 getClass().getResourceAsStream(opCodeFile)));
123 String str = in.readLine();
124 while (str != null) {
125 String[] ss = str.split("=");
126 opMap.put(Integer.parseInt(ss[0]), ss[1]);
127 str = in.readLine();
129 in.close();
130 } catch (Exception ex) {
131 ex.printStackTrace();
134 return opMap;
137 public String getOpString(int op) {
138 return getOpMap().get(op);
141 public String describeOpCode(int op) {
142 return op + " (" + getOpString(op) + ")";
145 private InputStream mainIn;
146 private PrintWriter out = null;
147 private int counter = -1;
149 private void pr(int i){
150 out.print(i);
153 private void pr(char i){
154 out.print(i);
157 private void pr(String i){
158 out.print(i);
161 private void prl(String i){
162 out.println(i);
165 private int get() {
166 int res = -1;
167 try {
168 res = mainIn.read();
169 if (res >= 0)
170 res = res << 24 >>> 24;
171 } catch (IOException ex) {
172 ex.printStackTrace();
174 counter++;
175 return res;
178 private int get2() {
179 return (get() * 256 + get()) << 16 >> 16;
182 private int get4() {
183 return (get2() << 16) + (get2() << 16 >>> 16);
186 public String createStandardStart(){
187 return createStandardStart(10);
190 public String createStandardStart(int numWords){
191 StringBuilder ret = new StringBuilder(
192 "C:\" This file automatically converted from microjava bytecode\";\n"
193 +"C:\" with mjc2wsl v "+versionN+"\";\n");
195 ret.append("BEGIN ");
196 ret.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
197 ret.append("mjvm_locals := ARRAY(1,0), ");
198 ret.append("\n\tmjvm_statics := ARRAY("+numWords+",0), ");
199 ret.append("\n\tmjvm_arrays := < >, ");
200 ret.append("\n\tmjvm_objects := < >, ");
201 ret.append("\n mjvm_estack := < >, mjvm_mstack := < > > : ");
203 return ret.toString();
206 public String createStandardEnd(){
207 StringBuilder ret = new StringBuilder("SKIP\nENDVAR");
208 ret.append("\nWHERE\n");
210 ret.append("\nPROC Print_MJ(val, format VAR)==\n");
211 ret.append(createComment("print spacing", C_SPEC));
213 ret.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
214 ret.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
215 ret.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
217 ret.append("\nEND\n");
219 return ret.toString();
222 private String createLocal(int i) {
223 // arrays start at 1 in WSL, so we need an offset
224 return "mjvm_locals[" + (i + 1) + "]";
227 private String createStatic(int i) {
228 return "mjvm_statics[" + (i + 1) + "]";
231 private String createArray(int i) {
232 return "mjvm_arrays[" + i + "]";
235 private String createArray(String i) {
236 return "mjvm_arrays[" + i + "]";
239 private String createObject(String i) {
240 return "mjvm_objects[" + i + "]";
243 /**
244 * Creates a WSL comment with care to quote chars.
245 */
246 public static String createComment(String str){
247 return createComment(str, C_REG);
250 /**
251 * Creates a WSL comment with care to quote chars, of the
252 * given type. Types are given as char constants. They can be
253 * default comments, comments that contain the original code
254 * in them, or additional comments regarding the translation
255 * process.
256 */
257 public static String createComment(String str, char type) {
258 return "C:\"" + type + str.replace("\"", "''") + "\";";
261 //Expression stack
263 private String createToEStack(int i) {
264 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
265 if (genPrintEStackOnChange)
266 res += "PRINT(\"eStack\",mjvm_estack);";
267 return res;
270 private String createToEStack(String i) {
271 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
272 if (genPrintEStackOnChange)
273 res += "PRINT(\"eStack\",mjvm_estack);";
274 return res;
277 private String createFromEStack(String st) {
278 String res = st
279 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
280 if (genPrintEStackOnChange)
281 res += "PRINT(\"eStack\",mjvm_estack);";
282 return res;
285 private String createPopEStack() {
286 String res = "mjvm_estack := TAIL(mjvm_estack);";
287 if (genPrintEStackOnChange)
288 res += "PRINT(\"eStack\",mjvm_estack);";
289 return res;
292 private String createTopTwoEStack() {
293 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
296 private String createTopEStack() {
297 return createFromEStack("tempa");
300 //Method stack
302 private String createToMStack(int i) {
303 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
306 private String createToMStack(String i) {
307 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
310 private String createFromMStack(String st) {
311 return st + " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
314 private String getRelationFor(int opcode) throws Exception {
315 switch (opcode) {
316 case jeq: return "=";
317 case jne: return "<>";
318 case jlt: return "<";
319 case jle: return "<=";
320 case jgt: return ">";
321 case jge: return ">=";
323 throw new Exception("Wrong opcode for a relation");
326 private boolean isJumpCode(int opcode) {
327 return (opcode >= jmp) && (opcode <= jge);
330 public void convertStream(InputStream ins) throws Exception{
331 mainIn = ins;
332 //process start
333 byte m = (byte) get();
334 byte j = (byte) get();
335 if (m!='M' || j !='J')
336 throw new Exception("Wrong start of bytecode file");
337 int codesize = get4();
338 int numberOfWords = get4();
339 int mainAdr = get4();
341 prl(createStandardStart(numberOfWords));
342 prl("SKIP;\n ACTIONS a" + (14 + mainAdr) + " :");
343 int op = get();
344 while (op >= 0) {
345 if (originalInComments)
346 prl(createComment(describeOpCode(op), C_OC));
347 prl(" a" + counter + " == ");
348 if (genPrintForEachAddress) {
349 prl("PRINT(\"a" + counter + "\");");
350 if (genPauseAfterEachAddress)
351 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
353 switch (op) {
354 case load: {
355 prl(createToEStack(createLocal(get())));
356 break;
358 case load_0:
359 case load_1:
360 case load_2:
361 case load_3: {
362 prl(createToEStack(createLocal(op - load_0)));
363 break;
365 case store: {
366 prl(createFromEStack(createLocal(get())));
367 break;
369 case store_0:
370 case store_1:
371 case store_2:
372 case store_3: {
373 prl(createFromEStack(createLocal(op - store_0)));
374 break;
377 case getstatic: {
378 prl(createToEStack(createStatic(get2())));
379 break;
381 case putstatic: {
382 prl(createFromEStack(createStatic(get2())));
383 break;
386 case getfield: {
387 int f = get2();
388 prl(createTopEStack());
389 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
390 break;
392 case putfield: {
393 int f = get2();
394 // we need to use a temparray as a pointer, WSL
395 // otherwise tries to access it as a list of lists and fails
396 prl(createTopTwoEStack());
397 prl("VAR < tempArray := " + createObject("tempb") + " > :");
398 prl("tempArray[" + (f + 1) + "]:=tempa ENDVAR;");
399 break;
402 case const_: {
403 prl(createToEStack(get4()));
404 break;
407 case const_0:
408 case const_1:
409 case const_2:
410 case const_3:
411 case const_4:
412 case const_5: {
413 prl(createToEStack(op - const_0));
414 break;
417 case add: {
418 prl(createTopTwoEStack());
419 prl("tempres := tempb + tempa;");
420 prl(createToEStack("tempres"));
421 break;
423 case sub: {
424 prl(createTopTwoEStack());
425 prl("tempres := tempb - tempa;");
426 prl(createToEStack("tempres"));
427 break;
429 case mul: {
430 prl(createTopTwoEStack());
431 prl("tempres := tempb * tempa;");
432 prl(createToEStack("tempres"));
433 break;
435 case div: {
436 prl(createTopTwoEStack());
437 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
438 prl("tempres := tempb DIV tempa;");
439 prl(createToEStack("tempres"));
440 break;
442 case rem: {
443 prl(createTopTwoEStack());
444 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
445 prl("tempres := tempb MOD tempa;");
446 prl(createToEStack("tempres"));
447 break;
450 case neg: {
451 prl(createTopEStack());
452 prl(createToEStack("-tempa"));
453 break;
456 case shl: {
457 prl(createTopTwoEStack());
458 prl("VAR <tempres :=tempb, i:=1 >:");
459 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
460 prl(createToEStack("tempres"));
461 prl("ENDVAR;");
462 break;
464 case shr: {
465 prl(createTopTwoEStack());
466 prl("VAR <tempres :=tempb, i:=1 >:");
467 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
468 prl(createToEStack("tempres"));
469 prl("ENDVAR;");
470 break;
473 case inc: {
474 int b1 = get(), b2 = get();
475 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
476 break;
479 case new_: {
480 int size = get2();
481 // TODO maybe objects and arrays should be in the same list?
482 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
483 + ",0) >;");
484 prl(createToEStack("LENGTH(mjvm_objects)"));
485 break;
487 case newarray: {
488 get();// 0 - bytes, 1 - words; ignore for now
489 // TODO take into consideration 0/1
490 prl(createTopEStack());
491 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
492 prl(createToEStack("LENGTH(mjvm_arrays)"));
493 break;
496 case aload:
497 case baload: {
498 prl(createTopTwoEStack());
499 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
500 break;
502 case astore:
503 case bastore: {
504 prl(createFromEStack("tempres"));
505 prl(createTopTwoEStack());
506 // we need to use a temparray as a pointer, WSL
507 // otherwise tries to access it as a list of lists and fails
508 prl("VAR < tempArray := " + createArray("tempb") + " > :");
509 prl("tempArray[tempa+1]:=tempres ENDVAR;");
510 break;
512 case arraylength: {
513 prl(createTopEStack());
514 prl("tempb := LENGTH("+ createArray("tempa") + ");");
515 prl(createToEStack("tempb"));
516 break;
519 case dup: {
520 prl(createTopEStack());
521 prl(createToEStack("tempa"));
522 prl(createToEStack("tempa"));
523 break;
525 case dup2: {
526 prl(createTopTwoEStack());
527 prl(createToEStack("tempb"));
528 prl(createToEStack("tempa"));
529 prl(createToEStack("tempb"));
530 prl(createToEStack("tempa"));
531 break;
534 case pop: {
535 prl(createPopEStack());
536 break;
539 case jmp: {
540 prl("CALL a" + (counter + get2()) + ";");
541 break;
544 case jeq:
545 case jne:
546 case jlt:
547 case jle:
548 case jgt:
549 case jge: {
550 prl(createTopTwoEStack());
551 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
552 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
553 + " FI;");
554 break;
557 case call: {
558 prl("CALL a" + (counter + get2()) + ";");
559 break;
562 case return_: {
563 // we let the actions return
564 // there is nothing to clean up
565 prl("SKIP\n END\n b" + counter + " ==");
566 break;
568 case enter: {
569 int parameters = get();
571 int locals = get();
572 prl(createToMStack("mjvm_locals"));
573 prl("mjvm_locals := ARRAY(" + locals + ",0);");
574 for (int i = parameters - 1; i >= 0; i--)
575 prl(createFromEStack(createLocal(i)));
576 break;
578 case exit: {
579 prl(createFromMStack("mjvm_locals"));
580 break;
583 // read, print
584 case bread: {
585 // TODO make it a char for read
586 messages.message("char is read like a number", TransMessages.M_WAR);
587 prl(createComment("char is read like a number", C_SPEC));
589 case read: {
590 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
591 prl(createToEStack("tempa"));
592 break;
595 // the prints
596 case bprint: {
597 // TODO need to make it a char on print
598 messages.message("chars will be printed as number codes", TransMessages.M_WAR);
599 prl(createComment("char will be printed as a number code",
600 C_SPEC));
602 case print: {
603 // TODO printing numbers needs different lengths of spacing
604 prl(createTopTwoEStack());
605 prl("Print_MJ(tempb,tempa);");
606 break;
609 case trap: {
610 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
611 break;
614 default:
615 prl(createComment("unknown op error: " + op, C_ERR));
616 messages.message("unknown op error: " + op, TransMessages.M_ERR);
617 break;
620 boolean wasJump = isJumpCode(op);
621 op = get();
622 if (op >= 0)
623 if (wasJump)
624 prl("SKIP\n END");
625 else
626 prl("CALL a" + counter + "\n END");
628 prl("SKIP\n END\nENDACTIONS;\n");
629 prl(createStandardEnd());
632 public void convertFile(File f) {
633 try {
634 convertStream(new FileInputStream(f));
635 } catch (Exception ex) {
636 ex.printStackTrace();
640 public void printHelp() {
641 printVersion();
642 printUsage();
643 printHelpOutput();
644 printHelpHelp();
647 public void printLongHelp() {
648 printVersion();
649 printUsage();
650 System.out.println();
651 printHelpOutput();
652 System.out.println();
653 printHelpGenerating();
654 System.out.println();
655 printHelpHelp();
658 public void printHelpOutput() {
659 System.out.println("Output options:");
660 System.out.println(" --screen print output to screen");
661 System.out.println(" -o --oc[+-] include original code in comments");
662 System.out.println(" -v verbose, print warning messages");
663 System.out.println(" -q quiet; don't print even the error messages");
664 System.out.println(" -d print detailed debug messages");
667 public void printHelpGenerating() {
668 System.out.println("Options for generating extra code for tracking code execution");
669 System.out.println(" --genEStackPrint generate print for all EStack changes");
670 System.out.println(" --genAddrPrint generate prints after every address of the original code ");
671 System.out.println(" --genAddrPause generate a pause after every address of the original code ");
672 System.out.println(" --genAddr short for --genAddrPrint and --genAddrPause");
673 System.out.println(" --genAll short for applying all code generation");
676 public void printHelpHelp() {
677 System.out.println("Help and info options");
678 System.out.println(" -h basic help");
679 System.out.println(" --help print more detailed help");
680 System.out.println(" --version or -version print version and exit");
683 public void printUsage(){
684 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
687 public void printVersion() {
688 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
689 + ", by Doni Pracner");
692 public String makeDefaultOutName(String inname){
693 String rez = inname;
694 if (inname.endsWith(".obj"))
695 rez = rez.substring(0, rez.length() - 4);
696 return rez + ".wsl";
699 public void run(String[] args) {
700 if (args.length == 0) {
701 printHelp();
702 } else {
703 int i = 0;
704 while (i < args.length && args[i].charAt(0) == '-') {
705 if (args[i].compareTo("-h") == 0) {
706 printHelp();
707 return;
708 } else if (args[i].compareTo("--help") == 0) {
709 printLongHelp();
710 return;
711 } else if (args[i].compareTo("--version") == 0
712 || args[i].compareTo("-version") == 0) {
713 printVersion();
714 return;
715 } else if (args[i].compareTo("-o") == 0
716 || args[i].startsWith("--oc")) {
717 if (args[i].length() == 2)
718 originalInComments = true;
719 else if (args[i].length() == 5)
720 originalInComments = args[i].charAt(4) == '+';
721 else
722 originalInComments = true;
723 } else if (args[i].compareTo("--screen") == 0) {
724 out = new PrintWriter(System.out);
725 } else if (args[i].compareTo("-d") == 0) {
726 messages.setPrintLevel(TransMessages.M_DEB);// print debug info
727 } else if (args[i].compareTo("-v") == 0) {
728 messages.setPrintLevel(TransMessages.M_WAR);// print warnings
729 } else if (args[i].compareTo("-q") == 0) {
730 messages.setPrintLevel(TransMessages.M_QUIET);// no printing
731 } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
732 genPrintEStackOnChange = true;
733 } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
734 genPauseAfterEachAddress = true;
735 } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
736 genPrintForEachAddress = true;
737 } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
738 genPrintForEachAddress = true;
739 genPauseAfterEachAddress = true;
740 } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
741 genPrintEStackOnChange = true;
742 genPrintForEachAddress = true;
743 genPauseAfterEachAddress = true;
745 i++;
748 if (i >= args.length) {
749 System.out.println("no filename supplied");
750 System.exit(2);
752 File f = new File(args[i]);
754 if (i + 1 < args.length) {
755 try {
756 out = new PrintWriter(args[i + 1]);
757 } catch (Exception e) {
758 System.err.println("error in opening out file:");
759 e.printStackTrace();
762 if (out == null) {
763 // if not set to screen, or a file, make a default filename
764 try {
765 out = new PrintWriter(makeDefaultOutName(args[i]));
766 } catch (Exception e) {
767 System.err.println("error in opening out file:");
768 e.printStackTrace();
771 if (f.exists()) {
772 Calendar now = Calendar.getInstance();
773 convertFile(f);
774 long mili = Calendar.getInstance().getTimeInMillis()
775 - now.getTimeInMillis();
776 System.out.println("conversion time:" + mili + " ms");
777 messages.printMessageCounters();
778 out.close();
779 } else
780 System.out.println("file does not exist");
784 public static void main(String[] args) {
785 new mjc2wsl().run(args);
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner