gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
gitignore directory kde
[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 private boolean genPopPush=false;
41 /** Constant used for marking a regular comment from the original file */
42 public static final char C_REG = ' ';
43 /**
44 * Constant used for marking when original code is inserted in the file,
45 * next to the translations
46 */
47 public static final char C_OC = '#';
48 /** Constant used for marking special messages from the translator */
49 public static final char C_SPEC = '&';
50 /** Constant used for marking error messages from the translator */
51 public static final char C_ERR = '!';
53 /** instruction code in MicroJava bytecode. */
54 public static final int
55 load = 1,
56 load_0 = 2,
57 load_1 = 3,
58 load_2 = 4,
59 load_3 = 5,
60 store = 6,
61 store_0 = 7,
62 store_1 = 8,
63 store_2 = 9,
64 store_3 = 10,
65 getstatic = 11,
66 putstatic = 12,
67 getfield = 13,
68 putfield = 14,
69 const_0 = 15,
70 const_1 = 16,
71 const_2 = 17,
72 const_3 = 18,
73 const_4 = 19,
74 const_5 = 20,
75 const_m1 = 21,
76 const_ = 22,
77 add = 23,
78 sub = 24,
79 mul = 25,
80 div = 26,
81 rem = 27,
82 neg = 28,
83 shl = 29,
84 shr = 30,
85 inc = 31,
86 new_ = 32,
87 newarray = 33,
88 aload = 34,
89 astore = 35,
90 baload = 36,
91 bastore = 37,
92 arraylength = 38,
93 pop = 39,
94 dup = 40,
95 dup2 = 41,
96 jmp = 42,
97 jeq = 43,
98 jne = 44,
99 jlt = 45,
100 jle = 46,
101 jgt = 47,
102 jge = 48,
103 call = 49,
104 return_ = 50,
105 enter = 51,
106 exit = 52,
107 read = 53,
108 print = 54,
109 bread = 55,
110 bprint = 56,
111 trap = 57;
113 private boolean originalInComments = false;
115 private HashMap<Integer,String> opMap = null;
117 private String opCodeFile = "mj-bytecodes.properties";
119 private HashMap<Integer, String> getOpMap() {
120 if (opMap == null) {
121 opMap = new HashMap<Integer, String>(60, 0.98f);
122 try {
123 BufferedReader in = new BufferedReader(new InputStreamReader(
124 getClass().getResourceAsStream(opCodeFile)));
125 String str = in.readLine();
126 while (str != null) {
127 String[] ss = str.split("=");
128 opMap.put(Integer.parseInt(ss[0]), ss[1]);
129 str = in.readLine();
131 in.close();
132 } catch (Exception ex) {
133 ex.printStackTrace();
136 return opMap;
139 public String getOpString(int op) {
140 return getOpMap().get(op);
143 public String describeOpCode(int op) {
144 return op + " (" + getOpString(op) + ")";
147 private InputStream mainIn;
148 private PrintWriter out = null;
149 private int counter = -1;
151 private void pr(int i){
152 out.print(i);
155 private void pr(char i){
156 out.print(i);
159 private void pr(String i){
160 out.print(i);
163 private void prl(String i){
164 out.println(i);
167 private int get() {
168 int res = -1;
169 try {
170 res = mainIn.read();
171 if (res >= 0)
172 res = res << 24 >>> 24;
173 } catch (IOException ex) {
174 ex.printStackTrace();
176 counter++;
177 return res;
180 private int get2() {
181 return (get() * 256 + get()) << 16 >> 16;
184 private int get4() {
185 return (get2() << 16) + (get2() << 16 >>> 16);
188 public String createStandardStart(){
189 return createStandardStart(10);
192 public String createStandardStart(int numWords){
193 StringBuilder ret = new StringBuilder(
194 "C:\" This file automatically converted from microjava bytecode\";\n"
195 +"C:\" with mjc2wsl v "+versionN+"\";\n");
197 ret.append("BEGIN ");
198 ret.append("VAR < \n\t");
199 ret.append("mjvm_locals := ARRAY(1,0), ");
200 ret.append("\n\tmjvm_statics := ARRAY("+numWords+",0), ");
201 ret.append("\n\tmjvm_arrays := < >, ");
202 ret.append("\n\tmjvm_objects := < >, ");
203 ret.append("\n mjvm_estack := < >, mjvm_mstack := < > > : ");
205 return ret.toString();
208 public String createStandardEnd(){
209 StringBuilder ret = new StringBuilder("SKIP\nENDVAR");
210 ret.append("\nWHERE\n");
212 ret.append("\nPROC Print_MJ(val, format VAR)==\n");
213 ret.append(createComment("print spacing", C_SPEC));
215 ret.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
216 ret.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
217 ret.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
219 ret.append("\nEND\n");
221 return ret.toString();
224 private String createStartVar(String... vars){
225 StringBuilder ret = new StringBuilder("VAR < ");
226 ret.append(vars[0] + " := 0");
227 for (int i=1; i<vars.length; i++)
228 ret.append(", "+ vars[i] +" := 0");
229 ret.append(" > : ");
231 return ret.toString();
234 private String createEndVar(){
235 return "ENDVAR;";
238 private String createLocal(int i) {
239 // arrays start at 1 in WSL, so we need an offset
240 return "mjvm_locals[" + (i + 1) + "]";
243 private String createStatic(int i) {
244 return "mjvm_statics[" + (i + 1) + "]";
247 private String createArray(int i) {
248 return "mjvm_arrays[" + i + "]";
251 private String createArray(String i) {
252 return "mjvm_arrays[" + i + "]";
255 private String createObject(String i) {
256 return "mjvm_objects[" + i + "]";
259 /**
260 * Creates a WSL comment with care to quote chars.
261 */
262 public static String createComment(String str){
263 return createComment(str, C_REG);
266 /**
267 * Creates a WSL comment with care to quote chars, of the
268 * given type. Types are given as char constants. They can be
269 * default comments, comments that contain the original code
270 * in them, or additional comments regarding the translation
271 * process.
272 */
273 public static String createComment(String str, char type) {
274 return "C:\"" + type + str.replace("\"", "''") + "\";";
277 // generalised stack operations
279 private String createToStack(String stack, String var){
280 if (genPopPush)
281 return "PUSH("+stack+"," + var + ");";
282 else
283 return stack + " := <" + var + " > ++ " + stack +";";
286 private String createFromStack(String stack, String var){
287 if (genPopPush)
288 return "POP("+ var + ", "+stack+");";
289 else
290 return var + ":= HEAD("+stack+"); "+stack+" := TAIL("+stack+");";
292 //Expression stack
294 private String createToEStack(int i) {
295 return createToEStack(i+"");
298 private String createToEStack(String i) {
299 String res = createToStack("mjvm_estack", i);
300 if (genPrintEStackOnChange)
301 res += "PRINT(\"eStack\",mjvm_estack);";
302 return res;
305 private String createFromEStack(String st) {
306 String res = createFromStack("mjvm_estack",st);
307 if (genPrintEStackOnChange)
308 res += "PRINT(\"eStack\",mjvm_estack);";
309 return res;
312 private String createPopEStack() {
313 String res = "mjvm_estack := TAIL(mjvm_estack);";
314 if (genPrintEStackOnChange)
315 res += "PRINT(\"eStack\",mjvm_estack);";
316 return res;
319 private String createTopTwoEStack() {
320 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
323 private String createTopEStack() {
324 return createFromEStack("tempa");
327 //Method stack
329 private String createToMStack(int i) {
330 return createToMStack(i+"");
333 private String createToMStack(String i) {
334 return createToStack("mjvm_mstack", i);
337 private String createFromMStack(String st) {
338 return createFromStack("mjvm_mstack", st);
341 private String getRelationFor(int opcode) throws Exception {
342 switch (opcode) {
343 case jeq: return "=";
344 case jne: return "<>";
345 case jlt: return "<";
346 case jle: return "<=";
347 case jgt: return ">";
348 case jge: return ">=";
350 throw new Exception("Wrong opcode for a relation");
353 private boolean isJumpCode(int opcode) {
354 return (opcode >= jmp) && (opcode <= jge);
357 public void convertStream(InputStream ins) throws Exception{
358 mainIn = ins;
359 //process start
360 byte m = (byte) get();
361 byte j = (byte) get();
362 if (m!='M' || j !='J')
363 throw new Exception("Wrong start of bytecode file");
364 int codesize = get4();
365 int numberOfWords = get4();
366 int mainAdr = get4();
368 prl(createStandardStart(numberOfWords));
369 prl("SKIP;\n ACTIONS a" + (14 + mainAdr) + " :");
370 int op = get();
371 while (op >= 0) {
372 if (originalInComments)
373 prl(createComment(describeOpCode(op), C_OC));
374 prl(" a" + counter + " == ");
375 if (genPrintForEachAddress) {
376 prl("PRINT(\"a" + counter + "\");");
377 if (genPauseAfterEachAddress)
378 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
380 switch (op) {
381 case load: {
382 prl(createToEStack(createLocal(get())));
383 break;
385 case load_0:
386 case load_1:
387 case load_2:
388 case load_3: {
389 prl(createStartVar("tempa"));
390 prl("tempa :="+createLocal(op - load_0)+";");
391 prl(createToEStack("tempa"));
392 prl(createEndVar());
393 break;
395 case store: {
396 prl(createFromEStack(createLocal(get())));
397 break;
399 case store_0:
400 case store_1:
401 case store_2:
402 case store_3: {
403 prl(createStartVar("tempa"));
404 prl(createFromEStack("tempa"));
405 prl(createLocal(op - store_0)+" := tempa;");
406 prl(createEndVar());
407 break;
410 case getstatic: {
411 prl(createToEStack(createStatic(get2())));
412 break;
414 case putstatic: {
415 prl(createFromEStack(createStatic(get2())));
416 break;
419 case getfield: {
420 int f = get2();
421 prl(createTopEStack());
422 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
423 break;
425 case putfield: {
426 int f = get2();
427 // we need to use a temparray as a pointer, WSL
428 // otherwise tries to access it as a list of lists and fails
429 prl(createTopTwoEStack());
430 prl("VAR < tempArray := " + createObject("tempb") + " > :");
431 prl("tempArray[" + (f + 1) + "]:=tempa ENDVAR;");
432 break;
435 case const_: {
436 prl(createToEStack(get4()));
437 break;
440 case const_0:
441 case const_1:
442 case const_2:
443 case const_3:
444 case const_4:
445 case const_5: {
446 prl(createToEStack(op - const_0));
447 break;
450 case add: {
451 prl(createStartVar("tempa", "tempb", "tempres"));
452 prl(createTopTwoEStack());
453 prl("tempres := tempb + tempa;");
454 prl(createToEStack("tempres"));
455 prl(createEndVar());
456 break;
458 case sub: {
459 prl(createStartVar("tempa", "tempb", "tempres"));
460 prl(createTopTwoEStack());
461 prl("tempres := tempb - tempa;");
462 prl(createToEStack("tempres"));
463 prl(createEndVar());
464 break;
466 case mul: {
467 prl(createStartVar("tempa", "tempb", "tempres"));
468 prl(createTopTwoEStack());
469 prl("tempres := tempb * tempa;");
470 prl(createToEStack("tempres"));
471 prl(createEndVar());
472 break;
474 case div: {
475 prl(createStartVar("tempa", "tempb", "tempres"));
476 prl(createTopTwoEStack());
477 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
478 prl("tempres := tempb DIV tempa;");
479 prl(createToEStack("tempres"));
480 prl(createEndVar());
481 break;
483 case rem: {
484 prl(createStartVar("tempa", "tempb", "tempres"));
485 prl(createTopTwoEStack());
486 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
487 prl("tempres := tempb MOD tempa;");
488 prl(createToEStack("tempres"));
489 prl(createEndVar());
490 break;
493 case neg: {
494 prl(createStartVar("tempa"));
495 prl(createTopEStack());
496 prl(createToEStack("-tempa"));
497 prl(createEndVar());
498 break;
501 case shl: {
502 prl(createTopTwoEStack());
503 prl("VAR <tempres :=tempb, i:=1 >:");
504 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
505 prl(createToEStack("tempres"));
506 prl("ENDVAR;");
507 break;
509 case shr: {
510 prl(createTopTwoEStack());
511 prl("VAR <tempres :=tempb, i:=1 >:");
512 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
513 prl(createToEStack("tempres"));
514 prl("ENDVAR;");
515 break;
518 case inc: {
519 int b1 = get(), b2 = get();
520 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
521 break;
524 case new_: {
525 int size = get2();
526 // TODO maybe objects and arrays should be in the same list?
527 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
528 + ",0) >;");
529 prl(createToEStack("LENGTH(mjvm_objects)"));
530 break;
532 case newarray: {
533 get();// 0 - bytes, 1 - words; ignore for now
534 // TODO take into consideration 0/1
535 prl(createTopEStack());
536 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
537 prl(createToEStack("LENGTH(mjvm_arrays)"));
538 break;
541 case aload:
542 case baload: {
543 prl(createTopTwoEStack());
544 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
545 break;
547 case astore:
548 case bastore: {
549 prl(createFromEStack("tempres"));
550 prl(createTopTwoEStack());
551 // we need to use a temparray as a pointer, WSL
552 // otherwise tries to access it as a list of lists and fails
553 prl("VAR < tempArray := " + createArray("tempb") + " > :");
554 prl("tempArray[tempa+1]:=tempres ENDVAR;");
555 break;
557 case arraylength: {
558 prl(createTopEStack());
559 prl("tempb := LENGTH("+ createArray("tempa") + ");");
560 prl(createToEStack("tempb"));
561 break;
564 case dup: {
565 prl(createTopEStack());
566 prl(createToEStack("tempa"));
567 prl(createToEStack("tempa"));
568 break;
570 case dup2: {
571 prl(createTopTwoEStack());
572 prl(createToEStack("tempb"));
573 prl(createToEStack("tempa"));
574 prl(createToEStack("tempb"));
575 prl(createToEStack("tempa"));
576 break;
579 case pop: {
580 prl(createPopEStack());
581 break;
584 case jmp: {
585 prl("CALL a" + (counter + get2()) + ";");
586 break;
589 case jeq:
590 case jne:
591 case jlt:
592 case jle:
593 case jgt:
594 case jge: {
595 prl(createStartVar("tempa", "tempb"));
596 prl(createTopTwoEStack());
597 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
598 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
599 + " FI;");
600 prl(createEndVar());
602 break;
605 case call: {
606 prl("CALL a" + (counter + get2()) + ";");
607 break;
610 case return_: {
611 // we let the actions return
612 // there is nothing to clean up
613 prl("SKIP\n END\n b" + counter + " ==");
614 break;
616 case enter: {
617 int parameters = get();
619 int locals = get();
620 prl(createToMStack("mjvm_locals"));
621 prl("mjvm_locals := ARRAY(" + locals + ",0);");
622 for (int i = parameters - 1; i >= 0; i--)
623 prl(createFromEStack(createLocal(i)));
624 break;
626 case exit: {
627 prl(createFromMStack("mjvm_locals"));
628 break;
631 // read, print
632 case bread: {
633 // TODO make it a char for read
634 messages.message("char is read like a number", TransMessages.M_WAR);
635 prl(createComment("char is read like a number", C_SPEC));
637 case read: {
638 prl(createStartVar("tempa"));
639 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
640 prl(createToEStack("tempa"));
641 prl(createEndVar());
642 break;
645 // the prints
646 case bprint: {
647 // TODO need to make it a char on print
648 messages.message("chars will be printed as number codes", TransMessages.M_WAR);
649 prl(createComment("char will be printed as a number code",
650 C_SPEC));
652 case print: {
653 // TODO printing numbers needs different lengths of spacing
654 prl(createStartVar("tempa", "tempb"));
656 prl(createTopTwoEStack());
657 prl("Print_MJ(tempb,tempa);");
658 prl(createEndVar());
659 break;
662 case trap: {
663 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
664 break;
667 default:
668 prl(createComment("unknown op error: " + op, C_ERR));
669 messages.message("unknown op error: " + op, TransMessages.M_ERR);
670 break;
673 boolean wasJump = isJumpCode(op);
674 op = get();
675 if (op >= 0)
676 if (wasJump)
677 prl("SKIP\n END");
678 else
679 prl("CALL a" + counter + "\n END");
681 prl("SKIP\n END\nENDACTIONS;\n");
682 prl(createStandardEnd());
685 public void convertFile(File f) {
686 try {
687 convertStream(new FileInputStream(f));
688 } catch (Exception ex) {
689 ex.printStackTrace();
693 public void printHelp() {
694 printVersion();
695 printUsage();
696 printHelpOutput();
697 printHelpHelp();
700 public void printLongHelp() {
701 printVersion();
702 printUsage();
703 System.out.println();
704 printHelpOutput();
705 System.out.println();
706 printHelpDirectives();
707 System.out.println();
708 printHelpGenerating();
709 System.out.println();
710 printHelpHelp();
713 public void printHelpOutput() {
714 System.out.println("Output options:");
715 System.out.println(" --screen print output to screen");
716 System.out.println(" -o --oc[+-] include original code in comments");
717 System.out.println(" -v verbose, print warning messages");
718 System.out.println(" -q quiet; don't print even the error messages");
719 System.out.println(" -d print detailed debug messages");
722 public void printHelpGenerating() {
723 System.out.println("Options for generating extra code for tracking code execution");
724 System.out.println(" --genEStackPrint generate print for all EStack changes");
725 System.out.println(" --genAddrPrint generate prints after every address of the original code ");
726 System.out.println(" --genAddrPause generate a pause after every address of the original code ");
727 System.out.println(" --genAddr short for --genAddrPrint and --genAddrPause");
728 System.out.println(" --genAll short for applying all code generation");
731 public void printHelpDirectives(){
732 System.out.println("Alternatives for code generation:");
733 System.out.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
736 public void printHelpHelp() {
737 System.out.println("Help and info options");
738 System.out.println(" -h basic help");
739 System.out.println(" --help print more detailed help");
740 System.out.println(" --version or -version print version and exit");
743 public void printUsage(){
744 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
747 public void printVersion() {
748 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
749 + ", by Doni Pracner");
752 public String makeDefaultOutName(String inname){
753 String rez = inname;
754 if (inname.endsWith(".obj"))
755 rez = rez.substring(0, rez.length() - 4);
756 return rez + ".wsl";
759 public void run(String[] args) {
760 if (args.length == 0) {
761 printHelp();
762 } else {
763 int i = 0;
764 while (i < args.length && args[i].charAt(0) == '-') {
765 if (args[i].compareTo("-h") == 0) {
766 printHelp();
767 return;
768 } else if (args[i].compareTo("--help") == 0) {
769 printLongHelp();
770 return;
771 } else if (args[i].compareTo("--version") == 0
772 || args[i].compareTo("-version") == 0) {
773 printVersion();
774 return;
775 } else if (args[i].compareTo("-o") == 0
776 || args[i].startsWith("--oc")) {
777 if (args[i].length() == 2)
778 originalInComments = true;
779 else if (args[i].length() == 5)
780 originalInComments = args[i].charAt(4) == '+';
781 else
782 originalInComments = true;
783 } else if (args[i].compareTo("--screen") == 0) {
784 out = new PrintWriter(System.out);
785 } else if (args[i].compareTo("-d") == 0) {
786 messages.setPrintLevel(TransMessages.M_DEB);// print debug info
787 } else if (args[i].compareTo("-v") == 0) {
788 messages.setPrintLevel(TransMessages.M_WAR);// print warnings
789 } else if (args[i].compareTo("-q") == 0) {
790 messages.setPrintLevel(TransMessages.M_QUIET);// no printing
791 } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
792 genPrintEStackOnChange = true;
793 } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
794 genPauseAfterEachAddress = true;
795 } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
796 genPrintForEachAddress = true;
797 } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
798 genPrintForEachAddress = true;
799 genPauseAfterEachAddress = true;
800 } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
801 genPrintEStackOnChange = true;
802 genPrintForEachAddress = true;
803 genPauseAfterEachAddress = true;
804 } else if (args[i].compareToIgnoreCase("--genPopPush") == 0) {
805 genPopPush = true;
807 i++;
810 if (i >= args.length) {
811 System.out.println("no filename supplied");
812 System.exit(2);
814 File f = new File(args[i]);
816 if (i + 1 < args.length) {
817 try {
818 out = new PrintWriter(args[i + 1]);
819 } catch (Exception e) {
820 System.err.println("error in opening out file:");
821 e.printStackTrace();
824 if (out == null) {
825 // if not set to screen, or a file, make a default filename
826 try {
827 out = new PrintWriter(makeDefaultOutName(args[i]));
828 } catch (Exception e) {
829 System.err.println("error in opening out file:");
830 e.printStackTrace();
833 if (f.exists()) {
834 Calendar now = Calendar.getInstance();
835 convertFile(f);
836 long mili = Calendar.getInstance().getTimeInMillis()
837 - now.getTimeInMillis();
838 System.out.println("conversion time:" + mili + " ms");
839 messages.printMessageCounters();
840 out.close();
841 } else
842 System.out.println("file does not exist");
846 public static void main(String[] args) {
847 new mjc2wsl().run(args);
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner