gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
mjc2wsl -adding more VARS to the actions
[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 < \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 //Expression stack
277 private String createToEStack(int i) {
278 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
279 if (genPrintEStackOnChange)
280 res += "PRINT(\"eStack\",mjvm_estack);";
281 return res;
284 private String createToEStack(String i) {
285 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
286 if (genPrintEStackOnChange)
287 res += "PRINT(\"eStack\",mjvm_estack);";
288 return res;
291 private String createFromEStack(String st) {
292 String res = st
293 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
294 if (genPrintEStackOnChange)
295 res += "PRINT(\"eStack\",mjvm_estack);";
296 return res;
299 private String createPopEStack() {
300 String res = "mjvm_estack := TAIL(mjvm_estack);";
301 if (genPrintEStackOnChange)
302 res += "PRINT(\"eStack\",mjvm_estack);";
303 return res;
306 private String createTopTwoEStack() {
307 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
310 private String createTopEStack() {
311 return createFromEStack("tempa");
314 //Method stack
316 private String createToMStack(int i) {
317 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
320 private String createToMStack(String i) {
321 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
324 private String createFromMStack(String st) {
325 return st + " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
328 private String getRelationFor(int opcode) throws Exception {
329 switch (opcode) {
330 case jeq: return "=";
331 case jne: return "<>";
332 case jlt: return "<";
333 case jle: return "<=";
334 case jgt: return ">";
335 case jge: return ">=";
337 throw new Exception("Wrong opcode for a relation");
340 private boolean isJumpCode(int opcode) {
341 return (opcode >= jmp) && (opcode <= jge);
344 public void convertStream(InputStream ins) throws Exception{
345 mainIn = ins;
346 //process start
347 byte m = (byte) get();
348 byte j = (byte) get();
349 if (m!='M' || j !='J')
350 throw new Exception("Wrong start of bytecode file");
351 int codesize = get4();
352 int numberOfWords = get4();
353 int mainAdr = get4();
355 prl(createStandardStart(numberOfWords));
356 prl("SKIP;\n ACTIONS a" + (14 + mainAdr) + " :");
357 int op = get();
358 while (op >= 0) {
359 if (originalInComments)
360 prl(createComment(describeOpCode(op), C_OC));
361 prl(" a" + counter + " == ");
362 if (genPrintForEachAddress) {
363 prl("PRINT(\"a" + counter + "\");");
364 if (genPauseAfterEachAddress)
365 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
367 switch (op) {
368 case load: {
369 prl(createToEStack(createLocal(get())));
370 break;
372 case load_0:
373 case load_1:
374 case load_2:
375 case load_3: {
376 prl(createToEStack(createLocal(op - load_0)));
377 break;
379 case store: {
380 prl(createFromEStack(createLocal(get())));
381 break;
383 case store_0:
384 case store_1:
385 case store_2:
386 case store_3: {
387 prl(createFromEStack(createLocal(op - store_0)));
388 break;
391 case getstatic: {
392 prl(createToEStack(createStatic(get2())));
393 break;
395 case putstatic: {
396 prl(createFromEStack(createStatic(get2())));
397 break;
400 case getfield: {
401 int f = get2();
402 prl(createTopEStack());
403 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
404 break;
406 case putfield: {
407 int f = get2();
408 // we need to use a temparray as a pointer, WSL
409 // otherwise tries to access it as a list of lists and fails
410 prl(createTopTwoEStack());
411 prl("VAR < tempArray := " + createObject("tempb") + " > :");
412 prl("tempArray[" + (f + 1) + "]:=tempa ENDVAR;");
413 break;
416 case const_: {
417 prl(createToEStack(get4()));
418 break;
421 case const_0:
422 case const_1:
423 case const_2:
424 case const_3:
425 case const_4:
426 case const_5: {
427 prl(createToEStack(op - const_0));
428 break;
431 case add: {
432 prl(createStartVar("tempa", "tempb", "tempres"));
433 prl(createTopTwoEStack());
434 prl("tempres := tempb + tempa;");
435 prl(createToEStack("tempres"));
436 prl(createEndVar());
437 break;
439 case sub: {
440 prl(createStartVar("tempa", "tempb", "tempres"));
441 prl(createTopTwoEStack());
442 prl("tempres := tempb - tempa;");
443 prl(createToEStack("tempres"));
444 prl(createEndVar());
445 break;
447 case mul: {
448 prl(createStartVar("tempa", "tempb", "tempres"));
449 prl(createTopTwoEStack());
450 prl("tempres := tempb * tempa;");
451 prl(createToEStack("tempres"));
452 prl(createEndVar());
453 break;
455 case div: {
456 prl(createStartVar("tempa", "tempb", "tempres"));
457 prl(createTopTwoEStack());
458 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
459 prl("tempres := tempb DIV tempa;");
460 prl(createToEStack("tempres"));
461 prl(createEndVar());
462 break;
464 case rem: {
465 prl(createStartVar("tempa", "tempb", "tempres"));
466 prl(createTopTwoEStack());
467 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
468 prl("tempres := tempb MOD tempa;");
469 prl(createToEStack("tempres"));
470 prl(createEndVar());
471 break;
474 case neg: {
475 prl(createStartVar("tempa"));
476 prl(createTopEStack());
477 prl(createToEStack("-tempa"));
478 prl(createEndVar());
479 break;
482 case shl: {
483 prl(createTopTwoEStack());
484 prl("VAR <tempres :=tempb, i:=1 >:");
485 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
486 prl(createToEStack("tempres"));
487 prl("ENDVAR;");
488 break;
490 case shr: {
491 prl(createTopTwoEStack());
492 prl("VAR <tempres :=tempb, i:=1 >:");
493 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
494 prl(createToEStack("tempres"));
495 prl("ENDVAR;");
496 break;
499 case inc: {
500 int b1 = get(), b2 = get();
501 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
502 break;
505 case new_: {
506 int size = get2();
507 // TODO maybe objects and arrays should be in the same list?
508 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
509 + ",0) >;");
510 prl(createToEStack("LENGTH(mjvm_objects)"));
511 break;
513 case newarray: {
514 get();// 0 - bytes, 1 - words; ignore for now
515 // TODO take into consideration 0/1
516 prl(createTopEStack());
517 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
518 prl(createToEStack("LENGTH(mjvm_arrays)"));
519 break;
522 case aload:
523 case baload: {
524 prl(createTopTwoEStack());
525 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
526 break;
528 case astore:
529 case bastore: {
530 prl(createFromEStack("tempres"));
531 prl(createTopTwoEStack());
532 // we need to use a temparray as a pointer, WSL
533 // otherwise tries to access it as a list of lists and fails
534 prl("VAR < tempArray := " + createArray("tempb") + " > :");
535 prl("tempArray[tempa+1]:=tempres ENDVAR;");
536 break;
538 case arraylength: {
539 prl(createTopEStack());
540 prl("tempb := LENGTH("+ createArray("tempa") + ");");
541 prl(createToEStack("tempb"));
542 break;
545 case dup: {
546 prl(createTopEStack());
547 prl(createToEStack("tempa"));
548 prl(createToEStack("tempa"));
549 break;
551 case dup2: {
552 prl(createTopTwoEStack());
553 prl(createToEStack("tempb"));
554 prl(createToEStack("tempa"));
555 prl(createToEStack("tempb"));
556 prl(createToEStack("tempa"));
557 break;
560 case pop: {
561 prl(createPopEStack());
562 break;
565 case jmp: {
566 prl("CALL a" + (counter + get2()) + ";");
567 break;
570 case jeq:
571 case jne:
572 case jlt:
573 case jle:
574 case jgt:
575 case jge: {
576 prl(createStartVar("tempa", "tempb"));
577 prl(createTopTwoEStack());
578 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
579 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
580 + " FI;");
581 prl(createEndVar());
583 break;
586 case call: {
587 prl("CALL a" + (counter + get2()) + ";");
588 break;
591 case return_: {
592 // we let the actions return
593 // there is nothing to clean up
594 prl("SKIP\n END\n b" + counter + " ==");
595 break;
597 case enter: {
598 int parameters = get();
600 int locals = get();
601 prl(createToMStack("mjvm_locals"));
602 prl("mjvm_locals := ARRAY(" + locals + ",0);");
603 for (int i = parameters - 1; i >= 0; i--)
604 prl(createFromEStack(createLocal(i)));
605 break;
607 case exit: {
608 prl(createFromMStack("mjvm_locals"));
609 break;
612 // read, print
613 case bread: {
614 // TODO make it a char for read
615 messages.message("char is read like a number", TransMessages.M_WAR);
616 prl(createComment("char is read like a number", C_SPEC));
618 case read: {
619 prl(createStartVar("tempa"));
620 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
621 prl(createToEStack("tempa"));
622 prl(createEndVar());
623 break;
626 // the prints
627 case bprint: {
628 // TODO need to make it a char on print
629 messages.message("chars will be printed as number codes", TransMessages.M_WAR);
630 prl(createComment("char will be printed as a number code",
631 C_SPEC));
633 case print: {
634 // TODO printing numbers needs different lengths of spacing
635 prl(createStartVar("tempa", "tempb"));
637 prl(createTopTwoEStack());
638 prl("Print_MJ(tempb,tempa);");
639 prl(createEndVar());
640 break;
643 case trap: {
644 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
645 break;
648 default:
649 prl(createComment("unknown op error: " + op, C_ERR));
650 messages.message("unknown op error: " + op, TransMessages.M_ERR);
651 break;
654 boolean wasJump = isJumpCode(op);
655 op = get();
656 if (op >= 0)
657 if (wasJump)
658 prl("SKIP\n END");
659 else
660 prl("CALL a" + counter + "\n END");
662 prl("SKIP\n END\nENDACTIONS;\n");
663 prl(createStandardEnd());
666 public void convertFile(File f) {
667 try {
668 convertStream(new FileInputStream(f));
669 } catch (Exception ex) {
670 ex.printStackTrace();
674 public void printHelp() {
675 printVersion();
676 printUsage();
677 printHelpOutput();
678 printHelpHelp();
681 public void printLongHelp() {
682 printVersion();
683 printUsage();
684 System.out.println();
685 printHelpOutput();
686 System.out.println();
687 printHelpGenerating();
688 System.out.println();
689 printHelpHelp();
692 public void printHelpOutput() {
693 System.out.println("Output options:");
694 System.out.println(" --screen print output to screen");
695 System.out.println(" -o --oc[+-] include original code in comments");
696 System.out.println(" -v verbose, print warning messages");
697 System.out.println(" -q quiet; don't print even the error messages");
698 System.out.println(" -d print detailed debug messages");
701 public void printHelpGenerating() {
702 System.out.println("Options for generating extra code for tracking code execution");
703 System.out.println(" --genEStackPrint generate print for all EStack changes");
704 System.out.println(" --genAddrPrint generate prints after every address of the original code ");
705 System.out.println(" --genAddrPause generate a pause after every address of the original code ");
706 System.out.println(" --genAddr short for --genAddrPrint and --genAddrPause");
707 System.out.println(" --genAll short for applying all code generation");
710 public void printHelpHelp() {
711 System.out.println("Help and info options");
712 System.out.println(" -h basic help");
713 System.out.println(" --help print more detailed help");
714 System.out.println(" --version or -version print version and exit");
717 public void printUsage(){
718 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
721 public void printVersion() {
722 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
723 + ", by Doni Pracner");
726 public String makeDefaultOutName(String inname){
727 String rez = inname;
728 if (inname.endsWith(".obj"))
729 rez = rez.substring(0, rez.length() - 4);
730 return rez + ".wsl";
733 public void run(String[] args) {
734 if (args.length == 0) {
735 printHelp();
736 } else {
737 int i = 0;
738 while (i < args.length && args[i].charAt(0) == '-') {
739 if (args[i].compareTo("-h") == 0) {
740 printHelp();
741 return;
742 } else if (args[i].compareTo("--help") == 0) {
743 printLongHelp();
744 return;
745 } else if (args[i].compareTo("--version") == 0
746 || args[i].compareTo("-version") == 0) {
747 printVersion();
748 return;
749 } else if (args[i].compareTo("-o") == 0
750 || args[i].startsWith("--oc")) {
751 if (args[i].length() == 2)
752 originalInComments = true;
753 else if (args[i].length() == 5)
754 originalInComments = args[i].charAt(4) == '+';
755 else
756 originalInComments = true;
757 } else if (args[i].compareTo("--screen") == 0) {
758 out = new PrintWriter(System.out);
759 } else if (args[i].compareTo("-d") == 0) {
760 messages.setPrintLevel(TransMessages.M_DEB);// print debug info
761 } else if (args[i].compareTo("-v") == 0) {
762 messages.setPrintLevel(TransMessages.M_WAR);// print warnings
763 } else if (args[i].compareTo("-q") == 0) {
764 messages.setPrintLevel(TransMessages.M_QUIET);// no printing
765 } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
766 genPrintEStackOnChange = true;
767 } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
768 genPauseAfterEachAddress = true;
769 } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
770 genPrintForEachAddress = true;
771 } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
772 genPrintForEachAddress = true;
773 genPauseAfterEachAddress = true;
774 } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
775 genPrintEStackOnChange = true;
776 genPrintForEachAddress = true;
777 genPauseAfterEachAddress = true;
779 i++;
782 if (i >= args.length) {
783 System.out.println("no filename supplied");
784 System.exit(2);
786 File f = new File(args[i]);
788 if (i + 1 < args.length) {
789 try {
790 out = new PrintWriter(args[i + 1]);
791 } catch (Exception e) {
792 System.err.println("error in opening out file:");
793 e.printStackTrace();
796 if (out == null) {
797 // if not set to screen, or a file, make a default filename
798 try {
799 out = new PrintWriter(makeDefaultOutName(args[i]));
800 } catch (Exception e) {
801 System.err.println("error in opening out file:");
802 e.printStackTrace();
805 if (f.exists()) {
806 Calendar now = Calendar.getInstance();
807 convertFile(f);
808 long mili = Calendar.getInstance().getTimeInMillis()
809 - now.getTimeInMillis();
810 System.out.println("conversion time:" + mili + " ms");
811 messages.printMessageCounters();
812 out.close();
813 } else
814 System.out.println("file does not exist");
818 public static void main(String[] args) {
819 new mjc2wsl().run(args);
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner