gitweb on Svarog

projekti pod git sistemom za održavanje verzija -- projects under the git version control system
mjc2wsl, introduce longhelp with options for generating extra code
[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("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
196 ret.append("mjvm_locals := ARRAY(1,0), ");
197 ret.append("\n\tmjvm_statics := ARRAY("+numWords+",0), ");
198 ret.append("\n\tmjvm_arrays := < >, ");
199 ret.append("\n\tmjvm_objects := < >, ");
200 ret.append("\n mjvm_estack := < >, mjvm_mstack := < >, ");
201 ret.append("\n mjvm_fp := 0, mjvm_sp := 0,");
202 ret.append("\n t_e_m_p := 0 > :");
204 return ret.toString();
207 public String createStandardEnd(){
208 return "SKIP\nENDVAR";
211 private String createLocal(int i) {
212 // arrays start at 1 in WSL, so we need an offset
213 return "mjvm_locals[" + (i + 1) + "]";
216 private String createStatic(int i) {
217 return "mjvm_statics[" + (i + 1) + "]";
220 private String createArray(int i) {
221 return "mjvm_arrays[" + i + "]";
224 private String createArray(String i) {
225 return "mjvm_arrays[" + i + "]";
228 private String createObject(String i) {
229 return "mjvm_objects[" + i + "]";
232 /**
233 * Creates a WSL comment with care to quote chars.
234 */
235 public static String createComment(String str){
236 return createComment(str, C_REG);
239 /**
240 * Creates a WSL comment with care to quote chars, of the
241 * given type. Types are given as char constants. They can be
242 * default comments, comments that contain the original code
243 * in them, or additional comments regarding the translation
244 * process.
245 */
246 public static String createComment(String str, char type) {
247 return "C:\"" + type + str.replace("\"", "''") + "\";";
250 //Expression stack
252 private String createToEStack(int i) {
253 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
254 if (genPrintEStackOnChange)
255 res += "PRINT(\"eStack\",mjvm_estack);";
256 return res;
259 private String createToEStack(String i) {
260 String res = "mjvm_estack := <" + i + " > ++ mjvm_estack;";
261 if (genPrintEStackOnChange)
262 res += "PRINT(\"eStack\",mjvm_estack);";
263 return res;
266 private String createFromEStack(String st) {
267 String res = st
268 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
269 if (genPrintEStackOnChange)
270 res += "PRINT(\"eStack\",mjvm_estack);";
271 return res;
274 private String createPopEStack() {
275 String res = "mjvm_estack := TAIL(mjvm_estack);";
276 if (genPrintEStackOnChange)
277 res += "PRINT(\"eStack\",mjvm_estack);";
278 return res;
281 private String createTopTwoEStack() {
282 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
285 private String createTopEStack() {
286 return createFromEStack("tempa");
289 //Method stack
291 private String createToMStack(int i) {
292 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
295 private String createToMStack(String i) {
296 return "mjvm_mstack := <" + i + " > ++ mjvm_mstack;";
299 private String createFromMStack(String st) {
300 return st + " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
303 private String getRelationFor(int opcode) throws Exception {
304 switch (opcode) {
305 case jeq: return "=";
306 case jne: return "<>";
307 case jlt: return "<";
308 case jle: return "<=";
309 case jgt: return ">";
310 case jge: return ">=";
312 throw new Exception("Wrong opcode for a relation");
315 private boolean isJumpCode(int opcode) {
316 return (opcode >= jmp) && (opcode <= jge);
319 public void convertStream(InputStream ins) throws Exception{
320 mainIn = ins;
321 //process start
322 byte m = (byte) get();
323 byte j = (byte) get();
324 if (m!='M' || j !='J')
325 throw new Exception("Wrong start of bytecode file");
326 int codesize = get4();
327 int numberOfWords = get4();
328 int mainAdr = get4();
330 prl(createStandardStart(numberOfWords));
331 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a" + (14 + mainAdr)
332 + " END");
333 int op = get();
334 while (op >= 0) {
335 if (originalInComments)
336 prl(createComment(describeOpCode(op), C_OC));
337 prl("a" + counter + " == ");
338 if (genPrintForEachAddress) {
339 prl("PRINT(\"a" + counter + "\");");
340 if (genPauseAfterEachAddress)
341 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
343 switch (op) {
344 case load: {
345 prl(createToEStack(createLocal(get())));
346 break;
348 case load_0:
349 case load_1:
350 case load_2:
351 case load_3: {
352 prl(createToEStack(createLocal(op - load_0)));
353 break;
355 case store: {
356 prl(createFromEStack(createLocal(get())));
357 break;
359 case store_0:
360 case store_1:
361 case store_2:
362 case store_3: {
363 prl(createFromEStack(createLocal(op - store_0)));
364 break;
367 case getstatic: {
368 prl(createToEStack(createStatic(get2())));
369 break;
371 case putstatic: {
372 prl(createFromEStack(createStatic(get2())));
373 break;
376 case getfield: {
377 int f = get2();
378 prl(createTopEStack());
379 prl(createToEStack(createObject("tempa") + "[" + (f + 1) + "]"));
380 break;
382 case putfield: {
383 int f = get2();
384 // we need to use a temparray as a pointer, WSL
385 // otherwise tries to access it as a list of lists and fails
386 prl(createTopTwoEStack());
387 prl("VAR < tempArray := " + createObject("tempb") + " > :");
388 prl("tempArray[" + (f + 1) + "]:=tempa ENDVAR;");
389 break;
392 case const_: {
393 prl(createToEStack(get4()));
394 break;
397 case const_0:
398 case const_1:
399 case const_2:
400 case const_3:
401 case const_4:
402 case const_5: {
403 prl(createToEStack(op - const_0));
404 break;
407 case add: {
408 prl(createTopTwoEStack());
409 prl("tempres := tempb + tempa;");
410 prl(createToEStack("tempres"));
411 break;
413 case sub: {
414 prl(createTopTwoEStack());
415 prl("tempres := tempb - tempa;");
416 prl(createToEStack("tempres"));
417 break;
419 case mul: {
420 prl(createTopTwoEStack());
421 prl("tempres := tempb * tempa;");
422 prl(createToEStack("tempres"));
423 break;
425 case div: {
426 prl(createTopTwoEStack());
427 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
428 prl("tempres := tempb DIV tempa;");
429 prl(createToEStack("tempres"));
430 break;
432 case rem: {
433 prl(createTopTwoEStack());
434 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
435 prl("tempres := tempb MOD tempa;");
436 prl(createToEStack("tempres"));
437 break;
440 case neg: {
441 prl(createTopEStack());
442 prl(createToEStack("-tempa"));
443 break;
446 case shl: {
447 prl(createTopTwoEStack());
448 prl("VAR <tempres :=tempb, i:=1 >:");
449 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
450 prl(createToEStack("tempres"));
451 prl("ENDVAR;");
452 break;
454 case shr: {
455 prl(createTopTwoEStack());
456 prl("VAR <tempres :=tempb, i:=1 >:");
457 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
458 prl(createToEStack("tempres"));
459 prl("ENDVAR;");
460 break;
463 case inc: {
464 int b1 = get(), b2 = get();
465 prl(createLocal(b1) + " := " + createLocal(b1) + " + " + b2 + ";");
466 break;
469 case new_: {
470 int size = get2();
471 // TODO maybe objects and arrays should be in the same list?
472 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
473 + ",0) >;");
474 prl(createToEStack("LENGTH(mjvm_objects)"));
475 break;
477 case newarray: {
478 get();// 0 - bytes, 1 - words; ignore for now
479 // TODO take into consideration 0/1
480 prl(createTopEStack());
481 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
482 prl(createToEStack("LENGTH(mjvm_arrays)"));
483 break;
486 case aload:
487 case baload: {
488 prl(createTopTwoEStack());
489 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
490 break;
492 case astore:
493 case bastore: {
494 prl(createFromEStack("tempres"));
495 prl(createTopTwoEStack());
496 // we need to use a temparray as a pointer, WSL
497 // otherwise tries to access it as a list of lists and fails
498 prl("VAR < tempArray := " + createArray("tempb") + " > :");
499 prl("tempArray[tempa+1]:=tempres ENDVAR;");
500 break;
502 case arraylength: {
503 prl(createTopEStack());
504 // TODO make an array length function of some sort!
505 prl(createComment(
506 "array length not known - LENGTH not aplicable to arrays",
507 C_ERR));
508 messages.message("array length not known - LENGTH not aplicable to arrays", TransMessages.M_ERR);
509 prl(createComment("put 1 on the stack for consistency", C_SPEC));
510 prl(createToEStack(1));
511 break;
514 case dup: {
515 prl(createTopEStack());
516 prl(createToEStack("tempa"));
517 prl(createToEStack("tempa"));
518 break;
520 case dup2: {
521 prl(createTopTwoEStack());
522 prl(createToEStack("tempb"));
523 prl(createToEStack("tempa"));
524 prl(createToEStack("tempb"));
525 prl(createToEStack("tempa"));
526 break;
529 case pop: {
530 prl(createPopEStack());
531 break;
534 case jmp: {
535 prl("CALL a" + (counter + get2()) + ";");
536 break;
539 case jeq:
540 case jne:
541 case jlt:
542 case jle:
543 case jgt:
544 case jge: {
545 prl(createTopTwoEStack());
546 prl("IF tempb " + getRelationFor(op) + " tempa THEN CALL a"
547 + (counter + get2()) + " ELSE CALL a" + (counter + 1)
548 + " FI;");
549 break;
552 case call: {
553 prl("CALL a" + (counter + get2()) + ";");
554 break;
557 case return_: {
558 // we let the actions return
559 // there is nothing to clean up
560 prl("SKIP END b" + counter + " ==");
561 break;
563 case enter: {
564 int parameters = get();
566 int locals = get();
567 prl(createToMStack("mjvm_locals"));
568 prl("mjvm_locals := ARRAY(" + locals + ",0);");
569 for (int i = parameters - 1; i >= 0; i--)
570 prl(createFromEStack(createLocal(i)));
571 break;
573 case exit: {
574 prl(createFromMStack("mjvm_locals"));
575 break;
578 // read, print
579 case bread: {
580 // TODO make it a char for read
581 messages.message("char is read like a number", TransMessages.M_WAR);
582 prl(createComment("char is read like a number", C_SPEC));
584 case read: {
585 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
586 prl(createToEStack("tempa"));
587 break;
590 // the prints
591 case bprint: {
592 // TODO need to make it a char on print
593 messages.message("chars will be printed as number codes", TransMessages.M_WAR);
594 prl(createComment("char will be printed as a number code",
595 C_SPEC));
597 case print: {
598 // TODO printing numbers needs different lengths of spacing
599 prl(createTopTwoEStack());
600 pr(createComment("print spacing", C_SPEC));
601 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
602 prl("PRINFLUSH(tempb);");
603 break;
606 case trap: {
607 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
608 break;
611 default:
612 prl(createComment("unknown op error: " + op, C_ERR));
613 messages.message("unknown op error: " + op, TransMessages.M_ERR);
614 break;
617 boolean wasJump = isJumpCode(op);
618 op = get();
619 if (op >= 0)
620 if (wasJump)
621 prl("SKIP END");
622 else
623 prl("CALL a" + counter + " END");
625 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
626 prl(createStandardEnd());
629 public void convertFile(File f) {
630 try {
631 convertStream(new FileInputStream(f));
632 } catch (Exception ex) {
633 ex.printStackTrace();
637 public void printHelp() {
638 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
639 + ", by Doni Pracner");
640 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
641 System.out.println("basic options:\n\t--screen print output to screen");
642 System.out.println("\t-o --oc[+-] include original code in comments");
643 System.out.println("\t-v verbose, print warning messages");
644 System.out.println("\t-q quiet; don't print even the error messages");
645 System.out.println("\t-d print detailed debug messages");
646 System.out.println("\t-h basic help; this screen");
647 System.out.println("\t--help print more detailed help");
650 public void printLongHelp() {
651 System.out.println("MicroJava bytecode to WSL converter. v " + versionN
652 + ", by Doni Pracner");
653 System.out.println("usage:\n\t mjc2wsl {options} filename [outfile]");
654 System.out.println("Output options:");
655 System.out.println(" --screen print output to screen");
656 System.out.println(" -o --oc[+-] include original code in comments");
657 System.out.println(" -v verbose, print warning messages");
658 System.out.println(" -q quiet; don't print even the error messages");
659 System.out.println(" -d print detailed debug messages");
661 System.out.println("\nOptions for generating extra code for tracking code execution");
662 System.out.println(" --genEStackPrint generate print for all EStack changes");
663 System.out.println(" --genAddrPrint generate prints after every address of the original code ");
664 System.out.println(" --genAddrPause generate a pause after every address of the original code ");
665 System.out.println(" --genAddr short for --genAddrPrint and --genAddrPause");
666 System.out.println(" --genAll short for applying all code generation");
668 System.out.println("\nHelp options");
669 System.out.println(" -h basic help");
670 System.out.println(" --help print more detailed help; this screen");
673 public String makeDefaultOutName(String inname){
674 String rez = inname;
675 if (inname.endsWith(".obj"))
676 rez = rez.substring(0, rez.length() - 4);
677 return rez + ".wsl";
680 public void run(String[] args) {
681 if (args.length == 0) {
682 printHelp();
683 } else {
684 int i = 0;
685 while (i < args.length && args[i].charAt(0) == '-') {
686 if (args[i].compareTo("-h") == 0) {
687 printHelp();
688 return;
689 } else if (args[i].compareTo("--help") == 0) {
690 printLongHelp();
691 return;
692 } else if (args[i].compareTo("-o") == 0
693 || args[i].startsWith("--oc")) {
694 if (args[i].length() == 2)
695 originalInComments = true;
696 else if (args[i].length() == 5)
697 originalInComments = args[i].charAt(4) == '+';
698 else
699 originalInComments = true;
700 } else if (args[i].compareTo("--screen") == 0) {
701 out = new PrintWriter(System.out);
702 } else if (args[i].compareTo("-d") == 0) {
703 messages.setPrintLevel(TransMessages.M_DEB);// print debug info
704 } else if (args[i].compareTo("-v") == 0) {
705 messages.setPrintLevel(TransMessages.M_WAR);// print warnings
706 } else if (args[i].compareTo("-q") == 0) {
707 messages.setPrintLevel(TransMessages.M_QUIET);// no printing
708 } else if (args[i].compareToIgnoreCase("--genEStackPrint") == 0) {
709 genPrintEStackOnChange = true;
710 } else if (args[i].compareToIgnoreCase("--genAddrPause") == 0) {
711 genPauseAfterEachAddress = true;
712 } else if (args[i].compareToIgnoreCase("--genAddrPrint") == 0) {
713 genPrintForEachAddress = true;
714 } else if (args[i].compareToIgnoreCase("--genAddr") == 0) {
715 genPrintForEachAddress = true;
716 genPauseAfterEachAddress = true;
717 } else if (args[i].compareToIgnoreCase("--genAll") == 0) {
718 genPrintEStackOnChange = true;
719 genPrintForEachAddress = true;
720 genPauseAfterEachAddress = true;
722 i++;
725 if (i >= args.length) {
726 System.out.println("no filename supplied");
727 System.exit(2);
729 File f = new File(args[i]);
731 if (i + 1 < args.length) {
732 try {
733 out = new PrintWriter(args[i + 1]);
734 } catch (Exception e) {
735 System.err.println("error in opening out file:");
736 e.printStackTrace();
739 if (out == null) {
740 // if not set to screen, or a file, make a default filename
741 try {
742 out = new PrintWriter(makeDefaultOutName(args[i]));
743 } catch (Exception e) {
744 System.err.println("error in opening out file:");
745 e.printStackTrace();
748 if (f.exists()) {
749 Calendar now = Calendar.getInstance();
750 convertFile(f);
751 long mili = Calendar.getInstance().getTimeInMillis()
752 - now.getTimeInMillis();
753 System.out.println("conversion time:" + mili + " ms");
754 messages.printMessageCounters();
755 out.close();
756 } else
757 System.out.println("file does not exist");
761 public static void main(String[] args) {
762 new mjc2wsl().run(args);
Svarog.pmf.uns.ac.rs/gitweb maintanance Doni Pracner