gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
refactor - generalise stack operations for easier future changes
[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.6";
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 < \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 createStartVar(String... vars){
223 StringBuilder ret = new StringBuilder("VAR < ");
224 ret.append(vars[0] + " := 0");
225 for (int i=1; i<vars.length; i++)
226 ret.append(", "+ vars[i] +" := 0");
227 ret.append(" > : ");
229 return ret.toString();
232 private String createEndVar(){
233 return "ENDVAR;";
236 private String createLocal(int i) {
237 // arrays start at 1 in WSL, so we need an offset
238 return "mjvm_locals[" + (i + 1) + "]";
241 private String createStatic(int i) {
242 return "mjvm_statics[" + (i + 1) + "]";
245 private String createArray(int i) {
246 return "mjvm_arrays[" + i + "]";
249 private String createArray(String i) {
250 return "mjvm_arrays[" + i + "]";
253 private String createObject(String i) {
254 return "mjvm_objects[" + i + "]";
257 /**
258 * Creates a WSL comment with care to quote chars.
259 */
260 public static String createComment(String str){
261 return createComment(str, C_REG);
264 /**
265 * Creates a WSL comment with care to quote chars, of the
266 * given type. Types are given as char constants. They can be
267 * default comments, comments that contain the original code
268 * in them, or additional comments regarding the translation
269 * process.
270 */
271 public static String createComment(String str, char type) {
272 return "C:\"" + type + str.replace("\"", "''") + "\";";
275 // generalised stack operations
277 private String createToStack(String stack, String var){
278 return stack + " := <" + var + " > ++ " + stack +";";
281 private String createFromStack(String stack, String var){
282 return var + ":= HEAD("+stack+"); "+stack+" := TAIL("+stack+");";
284 //Expression stack
286 private String createToEStack(int i) {
287 return createToEStack(i+"");
290 private String createToEStack(String i) {
291 String res = createToStack("mjvm_estack", i);
292 if (genPrintEStackOnChange)
293 res += "PRINT(\"eStack\",mjvm_estack);";
294 return res;
297 private String createFromEStack(String st) {
298 String res = createFromStack("mjvm_estack",st);
299 if (genPrintEStackOnChange)
300 res += "PRINT(\"eStack\",mjvm_estack);";
301 return res;
304 private String createPopEStack() {
305 String res = "mjvm_estack := TAIL(mjvm_estack);";
306 if (genPrintEStackOnChange)
307 res += "PRINT(\"eStack\",mjvm_estack);";
308 return res;
311 private String createTopTwoEStack() {
312 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
315 private String createTopEStack() {
316 return createFromEStack("tempa");
319 //Method stack
321 private String createToMStack(int i) {
322 return createToMStack(i+"");
325 private String createToMStack(String i) {
326 return createToStack("mjvm_mstack", i);
329 private String createFromMStack(String st) {
330 return createFromStack("mjvm_mstack", st);
333 private String getRelationFor(int opcode) throws Exception {
334 switch (opcode) {
335 case jeq: return "=";
336 case jne: return "<>";
337 case jlt: return "<";
338 case jle: return "<=";
339 case jgt: return ">";
340 case jge: return ">=";
342 throw new Exception("Wrong opcode for a relation");
345 private boolean isJumpCode(int opcode) {
346 return (opcode >= jmp) && (opcode <= jge);
349 public void convertStream(InputStream ins) throws Exception{
350 mainIn = ins;
351 //process start
352 byte m = (byte) get();
353 byte j = (byte) get();
354 if (m!='M' || j !='J')
355 throw new Exception("Wrong start of bytecode file");
356 int codesize = get4();
357 int numberOfWords = get4();
358 int mainAdr = get4();
360 prl(createStandardStart(numberOfWords));
361 prl("SKIP;\n ACTIONS a" + (14 + mainAdr) + " :");
362 int op = get();
363 while (op >= 0) {
364 if (originalInComments)
365 prl(createComment(describeOpCode(op), C_OC));
366 prl(" a" + counter + " == ");
367 if (genPrintForEachAddress) {
368 prl("PRINT(\"a" + counter + "\");");
369 if (genPauseAfterEachAddress)
370 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
372 switch (op) {
373 case load: {
374 prl(createToEStack(createLocal(get())));
375 break;
377 case load_0:
378 case load_1:
379 case load_2:
380 case load_3: {
381 prl(createToEStack(createLocal(op - load_0)));
382 break;
384 case store: {
385 prl(createFromEStack(createLocal(get())));
386 break;
388 case store_0:
389 case store_1:
390 case store_2:
391 case store_3: {
392 prl(createFromEStack(createLocal(op - store_0)));
393 break;
396 case getstatic: {
397 prl(createToEStack(createStatic(get2())));
398 break;
400 case putstatic: {
401 prl(createFromEStack(createStatic(get2())));
402 break;
405 case getfield: {
406 int f = get2();
407 prl(createTopEStack());
408 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
409 break;
411 case putfield: {
412 int f = get2();
413 // we need to use a temparray as a pointer, WSL
414 // otherwise tries to access it as a list of lists and fails
415 prl(createTopTwoEStack());
416 prl("VAR < tempArray := " + createObject("tempb") + " > :");
417 prl("tempArray[" + (f + 1) + "]:=tempa ENDVAR;");
418 break;
421 case const_: {
422 prl(createToEStack(get4()));
423 break;
426 case const_0:
427 case const_1:
428 case const_2:
429 case const_3:
430 case const_4:
431 case const_5: {
432 prl(createToEStack(op - const_0));
433 break;
436 case add: {
437 prl(createStartVar("tempa", "tempb", "tempres"));
438 prl(createTopTwoEStack());
439 prl("tempres := tempb + tempa;");
440 prl(createToEStack("tempres"));
441 prl(createEndVar());
442 break;
444 case sub: {
445 prl(createStartVar("tempa", "tempb", "tempres"));
446 prl(createTopTwoEStack());
447 prl("tempres := tempb - tempa;");
448 prl(createToEStack("tempres"));
449 prl(createEndVar());
450 break;
452 case mul: {
453 prl(createStartVar("tempa", "tempb", "tempres"));
454 prl(createTopTwoEStack());
455 prl("tempres := tempb * tempa;");
456 prl(createToEStack("tempres"));
457 prl(createEndVar());
458 break;
460 case div: {
461 prl(createStartVar("tempa", "tempb", "tempres"));
462 prl(createTopTwoEStack());
463 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
464 prl("tempres := tempb DIV tempa;");
465 prl(createToEStack("tempres"));
466 prl(createEndVar());
467 break;
469 case rem: {
470 prl(createStartVar("tempa", "tempb", "tempres"));
471 prl(createTopTwoEStack());
472 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
473 prl("tempres := tempb MOD tempa;");
474 prl(createToEStack("tempres"));
475 prl(createEndVar());
476 break;
479 case neg: {
480 prl(createStartVar("tempa"));
481 prl(createTopEStack());
482 prl(createToEStack("-tempa"));
483 prl(createEndVar());
484 break;
487 case shl: {
488 prl(createTopTwoEStack());
489 prl("VAR <tempres :=tempb, i:=1 >:");
490 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
491 prl(createToEStack("tempres"));
492 prl("ENDVAR;");
493 break;
495 case shr: {
496 prl(createTopTwoEStack());
497 prl("VAR <tempres :=tempb, i:=1 >:");
498 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
499 prl(createToEStack("tempres"));
500 prl("ENDVAR;");
501 break;
504 case inc: {
505 int b1 = get(), b2 = get();
506 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
507 break;
510 case new_: {
511 int size = get2();
512 // TODO maybe objects and arrays should be in the same list?
513 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
514 + ",0) >;");
515 prl(createToEStack("LENGTH(mjvm_objects)"));
516 break;
518 case newarray: {
519 get();// 0 - bytes, 1 - words; ignore for now
520 // TODO take into consideration 0/1
521 prl(createTopEStack());
522 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
523 prl(createToEStack("LENGTH(mjvm_arrays)"));
524 break;
527 case aload:
528 case baload: {
529 prl(createTopTwoEStack());
530 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
531 break;
533 case astore:
534 case bastore: {
535 prl(createFromEStack("tempres"));
536 prl(createTopTwoEStack());
537 // we need to use a temparray as a pointer, WSL
538 // otherwise tries to access it as a list of lists and fails
539 prl("VAR < tempArray := " + createArray("tempb") + " > :");
540 prl("tempArray[tempa+1]:=tempres ENDVAR;");
541 break;
543 case arraylength: {
544 prl(createTopEStack());
545 prl("tempb := LENGTH("+ createArray("tempa") + ");");
546 prl(createToEStack("tempb"));
547 break;
550 case dup: {
551 prl(createTopEStack());
552 prl(createToEStack("tempa"));
553 prl(createToEStack("tempa"));
554 break;
556 case dup2: {
557 prl(createTopTwoEStack());
558 prl(createToEStack("tempb"));
559 prl(createToEStack("tempa"));
560 prl(createToEStack("tempb"));
561 prl(createToEStack("tempa"));
562 break;
565 case pop: {
566 prl(createPopEStack());
567 break;
570 case jmp: {
571 prl("CALL a" + (counter + get2()) + ";");
572 break;
575 case jeq:
576 case jne:
577 case jlt:
578 case jle:
579 case jgt:
580 case jge: {
581 prl(createStartVar("tempa", "tempb"));
582 prl(createTopTwoEStack());
583 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
584 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
585 + " FI;");
586 prl(createEndVar());
588 break;
591 case call: {
592 prl("CALL a" + (counter + get2()) + ";");
593 break;
596 case return_: {
597 // we let the actions return
598 // there is nothing to clean up
599 prl("SKIP\n END\n b" + counter + " ==");
600 break;
602 case enter: {
603 int parameters = get();
605 int locals = get();
606 prl(createToMStack("mjvm_locals"));
607 prl("mjvm_locals := ARRAY(" + locals + ",0);");
608 for (int i = parameters - 1; i >= 0; i--)
609 prl(createFromEStack(createLocal(i)));
610 break;
612 case exit: {
613 prl(createFromMStack("mjvm_locals"));
614 break;
617 // read, print
618 case bread: {
619 // TODO make it a char for read
620 messages.message("char is read like a number", TransMessages.M_WAR);
621 prl(createComment("char is read like a number", C_SPEC));
623 case read: {
624 prl(createStartVar("tempa"));
625 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
626 prl(createToEStack("tempa"));
627 prl(createEndVar());
628 break;
631 // the prints
632 case bprint: {
633 // TODO need to make it a char on print
634 messages.message("chars will be printed as number codes", TransMessages.M_WAR);
635 prl(createComment("char will be printed as a number code",
636 C_SPEC));
638 case print: {
639 // TODO printing numbers needs different lengths of spacing
640 prl(createStartVar("tempa", "tempb"));
642 prl(createTopTwoEStack());
643 prl("Print_MJ(tempb,tempa);");
644 prl(createEndVar());
645 break;
648 case trap: {
649 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
650 break;
653 default:
654 prl(createComment("unknown op error: " + op, C_ERR));
655 messages.message("unknown op error: " + op, TransMessages.M_ERR);
656 break;
659 boolean wasJump = isJumpCode(op);
660 op = get();
661 if (op >= 0)
662 if (wasJump)
663 prl("SKIP\n END");
664 else
665 prl("CALL a" + counter + "\n END");
667 prl("SKIP\n END\nENDACTIONS;\n");
668 prl(createStandardEnd());
671 public void convertFile(File f) {
672 try {
673 convertStream(new FileInputStream(f));
674 } catch (Exception ex) {
675 ex.printStackTrace();
679 public void printHelp() {
680 printVersion();
681 printUsage();
682 printHelpOutput();
683 printHelpHelp();
686 public void printLongHelp() {
687 printVersion();
688 printUsage();
689 System.out.println();
690 printHelpOutput();
691 System.out.println();
692 printHelpGenerating();
693 System.out.println();
694 printHelpHelp();
697 public void printHelpOutput() {
698 System.out.println("Output options:");
699 System.out.println(" --screen print output to screen");
700 System.out.println(" -o --oc[+-] include original code in comments");
701 System.out.println(" -v verbose, print warning messages");
702 System.out.println(" -q quiet; don't print even the error messages");
703 System.out.println(" -d print detailed debug messages");
706 public void printHelpGenerating() {
707 System.out.println("Options for generating extra code for tracking code execution");
708 System.out.println(" --genEStackPrint generate print for all EStack changes");
709 System.out.println(" --genAddrPrint generate prints after every address of the original code ");
710 System.out.println(" --genAddrPause generate a pause after every address of the original code ");
711 System.out.println(" --genAddr short for --genAddrPrint and --genAddrPause");
712 System.out.println(" --genAll short for applying all code generation");
715 public void printHelpHelp() {
716 System.out.println("Help and info options");
717 System.out.println(" -h basic help");
718 System.out.println(" --help print more detailed help");
719 System.out.println(" --version or -version print version and exit");
722 public void printUsage(){
723 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
726 public void printVersion() {
727 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
728 + ", by Doni Pracner");
731 public String makeDefaultOutName(String inname){
732 String rez = inname;
733 if (inname.endsWith(".obj"))
734 rez = rez.substring(0, rez.length() - 4);
735 return rez + ".wsl";
738 public void run(String[] args) {
739 if (args.length == 0) {
740 printHelp();
741 } else {
742 int i = 0;
743 while (i < args.length && args[i].charAt(0) == '-') {
744 if (args[i].compareTo("-h") == 0) {
745 printHelp();
746 return;
747 } else if (args[i].compareTo("--help") == 0) {
748 printLongHelp();
749 return;
750 } else if (args[i].compareTo("--version") == 0
751 || args[i].compareTo("-version") == 0) {
752 printVersion();
753 return;
754 } else if (args[i].compareTo("-o") == 0
755 || args[i].startsWith("--oc")) {
756 if (args[i].length() == 2)
757 originalInComments = true;
758 else if (args[i].length() == 5)
759 originalInComments = args[i].charAt(4) == '+';
760 else
761 originalInComments = true;
762 } else if (args[i].compareTo("--screen") == 0) {
763 out = new PrintWriter(System.out);
764 } else if (args[i].compareTo("-d") == 0) {
765 messages.setPrintLevel(TransMessages.M_DEB);// print debug info
766 } else if (args[i].compareTo("-v") == 0) {
767 messages.setPrintLevel(TransMessages.M_WAR);// print warnings
768 } else if (args[i].compareTo("-q") == 0) {
769 messages.setPrintLevel(TransMessages.M_QUIET);// no printing
770 } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
771 genPrintEStackOnChange = true;
772 } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
773 genPauseAfterEachAddress = true;
774 } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
775 genPrintForEachAddress = true;
776 } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
777 genPrintForEachAddress = true;
778 genPauseAfterEachAddress = true;
779 } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
780 genPrintEStackOnChange = true;
781 genPrintForEachAddress = true;
782 genPauseAfterEachAddress = true;
784 i++;
787 if (i >= args.length) {
788 System.out.println("no filename supplied");
789 System.exit(2);
791 File f = new File(args[i]);
793 if (i + 1 < args.length) {
794 try {
795 out = new PrintWriter(args[i + 1]);
796 } catch (Exception e) {
797 System.err.println("error in opening out file:");
798 e.printStackTrace();
801 if (out == null) {
802 // if not set to screen, or a file, make a default filename
803 try {
804 out = new PrintWriter(makeDefaultOutName(args[i]));
805 } catch (Exception e) {
806 System.err.println("error in opening out file:");
807 e.printStackTrace();
810 if (f.exists()) {
811 Calendar now = Calendar.getInstance();
812 convertFile(f);
813 long mili = Calendar.getInstance().getTimeInMillis()
814 - now.getTimeInMillis();
815 System.out.println("conversion time:" + mili + " ms");
816 messages.printMessageCounters();
817 out.close();
818 } else
819 System.out.println("file does not exist");
823 public static void main(String[] args) {
824 new mjc2wsl().run(args);
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner