gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
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/>.
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
28 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
31 public static String versionN
= "0.1.7";
33 private TransMessages messages
= new TransMessages();
35 private boolean genPauseAfterEachAddress
=false,
36 genPrintForEachAddress
= false,
37 genPrintEStackOnChange
= false;
39 private boolean genPopPush
=false;
41 private boolean genInlinePrint
=false;
43 /** Constant used for marking a regular comment from the original file */
44 public static final char C_REG
= ' ';
46 * Constant used for marking when original code is inserted in the file,
47 * next to the translations
49 public static final char C_OC
= '#';
50 /** Constant used for marking special messages from the translator */
51 public static final char C_SPEC
= '&';
52 /** Constant used for marking error messages from the translator */
53 public static final char C_ERR
= '!';
55 /** instruction code in MicroJava bytecode. */
56 public static final int
115 private boolean originalInComments
= false;
117 private HashMap
<Integer
,String
> opMap
= null;
119 private String opCodeFile
= "mj-bytecodes.properties";
121 private HashMap
<Integer
, String
> getOpMap() {
123 opMap
= new HashMap
<Integer
, String
>(60, 0.98f
);
125 BufferedReader in
= new BufferedReader(new InputStreamReader(
126 getClass().getResourceAsStream(opCodeFile
)));
127 String str
= in
.readLine();
128 while (str
!= null) {
129 String
[] ss
= str
.split("=");
130 opMap
.put(Integer
.parseInt(ss
[0]), ss
[1]);
134 } catch (Exception ex
) {
135 ex
.printStackTrace();
141 public String
getOpString(int op
) {
142 return getOpMap().get(op
);
145 public String
describeOpCode(int op
) {
146 return op
+ " (" + getOpString(op
) + ")";
149 private InputStream mainIn
;
150 private PrintWriter out
= null;
151 private int counter
= -1;
153 private void pr(int i
){
157 private void pr(char i
){
161 private void pr(String i
){
165 private void prl(String i
){
174 res
= res
<< 24 >>> 24;
175 } catch (IOException ex
) {
176 ex
.printStackTrace();
183 return (get() * 256 + get()) << 16 >> 16;
187 return (get2() << 16) + (get2() << 16 >>> 16);
190 public String
createStandardStart(){
191 return createStandardStart(10);
194 public String
createStandardStart(int numWords
){
195 StringBuilder ret
= new StringBuilder(
196 "C:\" This file automatically converted from microjava bytecode\";\n"
197 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
199 ret
.append("\nBEGIN");
200 ret
.append("\nVAR <\n\t");
201 ret
.append("mjvm_locals := ARRAY(1,0),");
202 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
203 ret
.append("\n\tmjvm_arrays := < >,");
204 ret
.append("\n\tmjvm_flag_jump := 0,");
205 ret
.append("\n\tmjvm_objects := < >,");
206 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
208 return ret
.toString();
211 public String
createAsciiString(){
212 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
213 ret
.append("\nascii := \"????????????????????????????????\"++\n");
214 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
216 return ret
.toString();
219 public String
createStandardEnd(){
220 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
221 ret
.append("\nWHERE\n");
223 ret
.append("\nFUNCT CHR(num) ==:\n");
224 ret
.append("\t@List_To_String(< num >)\n");
227 if (!genInlinePrint
) {
228 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
229 ret
.append(createComment("print spacing", C_SPEC
));
230 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
231 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
232 ret
.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
234 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
235 ret
.append(createComment("print spacing", C_SPEC
));
236 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
237 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
238 ret
.append("\tFI;\n\tPRINFLUSH(CHR(val))\n");
243 return ret
.toString();
246 private String
createStartVar(String
... vars
){
247 StringBuilder ret
= new StringBuilder("VAR < ");
248 ret
.append(vars
[0] + " := 0");
249 for (int i
=1; i
<vars
.length
; i
++)
250 ret
.append(", "+ vars
[i
] +" := 0");
253 return ret
.toString();
256 private String
createEndVar(){
260 private String
createLocal(int i
) {
261 // arrays start at 1 in WSL, so we need an offset
262 return "mjvm_locals[" + (i
+ 1) + "]";
265 private String
createStatic(int i
) {
266 return "mjvm_statics[" + (i
+ 1) + "]";
269 private String
createArray(int i
) {
270 return "mjvm_arrays[" + i
+ "]";
273 private String
createArray(String i
) {
274 return "mjvm_arrays[" + i
+ "]";
277 private String
createObject(String i
) {
278 return "mjvm_objects[" + i
+ "]";
282 * Creates a WSL comment with care to quote chars.
284 public static String
createComment(String str
){
285 return createComment(str
, C_REG
);
289 * Creates a WSL comment with care to quote chars, of the
290 * given type. Types are given as char constants. They can be
291 * default comments, comments that contain the original code
292 * in them, or additional comments regarding the translation
295 public static String
createComment(String str
, char type
) {
296 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
299 // generalised stack operations
301 private String
createToStack(String stack
, String var
){
303 return "PUSH("+stack
+"," + var
+ ");";
305 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
308 private String
createFromStack(String stack
, String var
){
310 return "POP("+ var
+ ", "+stack
+");";
312 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
316 private String
createToEStack(int i
) {
317 return createToEStack(i
+"");
320 private String
createToEStack(String i
) {
321 String res
= createToStack("mjvm_estack", i
);
322 if (genPrintEStackOnChange
)
323 res
+= "PRINT(\"eStack\",mjvm_estack);";
327 private String
createFromEStack(String st
) {
328 String res
= createFromStack("mjvm_estack",st
);
329 if (genPrintEStackOnChange
)
330 res
+= "PRINT(\"eStack\",mjvm_estack);";
334 private String
createPopEStack() {
335 String res
= "mjvm_estack := TAIL(mjvm_estack);";
336 if (genPrintEStackOnChange
)
337 res
+= "PRINT(\"eStack\",mjvm_estack);";
341 private String
createTopTwoEStack() {
342 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
345 private String
createTopEStack() {
346 return createFromEStack("tempa");
351 private String
createToMStack(int i
) {
352 return createToMStack(i
+"");
355 private String
createToMStack(String i
) {
356 return createToStack("mjvm_mstack", i
);
359 private String
createFromMStack(String st
) {
360 return createFromStack("mjvm_mstack", st
);
363 private String
getRelationFor(int opcode
) throws Exception
{
365 case jeq
: return "=";
366 case jne
: return "<>";
367 case jlt
: return "<";
368 case jle
: return "<=";
369 case jgt
: return ">";
370 case jge
: return ">=";
372 throw new Exception("Wrong opcode for a relation");
375 private boolean isJumpCode(int opcode
) {
376 return (opcode
>= jmp
) && (opcode
<= jge
);
379 public void convertStream(InputStream ins
) throws Exception
{
382 byte m
= (byte) get();
383 byte j
= (byte) get();
384 if (m
!='M' || j
!='J')
385 throw new Exception("Wrong start of bytecode file");
386 int codesize
= get4();
387 int numberOfWords
= get4();
388 int mainAdr
= get4();
390 prl(createStandardStart(numberOfWords
));
391 prl("SKIP;\n ACTIONS a" + (14 + mainAdr
) + " :");
394 prl(" a" + counter
+ " ==");
395 if (originalInComments
)
396 prl(createComment(describeOpCode(op
), C_OC
));
397 if (genPrintForEachAddress
) {
398 prl("PRINT(\"a" + counter
+ "\");");
399 if (genPauseAfterEachAddress
)
400 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
404 prl(createToEStack(createLocal(get())));
411 prl(createStartVar("tempa"));
412 prl("tempa :="+createLocal(op
- load_0
)+";");
413 prl(createToEStack("tempa"));
418 prl(createFromEStack(createLocal(get())));
425 prl(createStartVar("tempa"));
426 prl(createFromEStack("tempa"));
427 prl(createLocal(op
- store_0
)+" := tempa;");
433 prl(createToEStack(createStatic(get2())));
437 prl(createFromEStack(createStatic(get2())));
443 prl(createStartVar("tempa"));
444 prl(createTopEStack());
445 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
451 prl(createStartVar("tempa", "tempb"));
452 prl(createTopTwoEStack());
453 prl(createObject("tempb") + "[" + (f
+ 1) + "]:=tempa;");
459 prl(createToEStack(get4()));
464 prl(createToEStack(-1));
474 prl(createToEStack(op
- const_0
));
479 prl(createStartVar("tempa", "tempb", "tempres"));
480 prl(createTopTwoEStack());
481 prl("tempres := tempb + tempa;");
482 prl(createToEStack("tempres"));
487 prl(createStartVar("tempa", "tempb", "tempres"));
488 prl(createTopTwoEStack());
489 prl("tempres := tempb - tempa;");
490 prl(createToEStack("tempres"));
495 prl(createStartVar("tempa", "tempb", "tempres"));
496 prl(createTopTwoEStack());
497 prl("tempres := tempb * tempa;");
498 prl(createToEStack("tempres"));
503 prl(createStartVar("tempa", "tempb", "tempres"));
504 prl(createTopTwoEStack());
505 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
506 prl("tempres := tempb DIV tempa;");
507 prl(createToEStack("tempres"));
512 prl(createStartVar("tempa", "tempb", "tempres"));
513 prl(createTopTwoEStack());
514 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
515 prl("tempres := tempb MOD tempa;");
516 prl(createToEStack("tempres"));
522 prl(createStartVar("tempa"));
523 prl(createTopEStack());
524 prl(createToEStack("-tempa"));
530 prl(createStartVar("tempa", "tempb"));
531 prl(createTopTwoEStack());
532 prl("VAR <tempres :=tempb, i:=1 >:");
533 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
534 prl(createToEStack("tempres"));
540 prl(createStartVar("tempa", "tempb"));
541 prl(createTopTwoEStack());
542 prl("VAR <tempres :=tempb, i:=1 >:");
543 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
544 prl(createToEStack("tempres"));
551 int b1
= get(), b2
= get();
552 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
558 // TODO maybe objects and arrays should be in the same list?
559 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
561 prl(createToEStack("LENGTH(mjvm_objects)"));
565 get();// 0 - bytes, 1 - words; ignore for now
566 // TODO take into consideration 0/1
567 prl(createStartVar("tempa"));
568 prl(createTopEStack());
569 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
570 prl(createToEStack("LENGTH(mjvm_arrays)"));
577 prl(createStartVar("tempa", "tempb"));
578 prl(createTopTwoEStack());
579 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
585 prl(createStartVar("tempa", "tempb", "tempres"));
586 prl(createFromEStack("tempres"));
587 prl(createTopTwoEStack());
588 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
593 prl(createStartVar("tempa", "tempb"));
594 prl(createTopEStack());
595 prl("tempb := LENGTH("+ createArray("tempa") + ");");
596 prl(createToEStack("tempb"));
602 prl(createStartVar("tempa", "tempb"));
603 prl(createTopEStack());
604 prl(createToEStack("tempa"));
605 prl(createToEStack("tempa"));
610 prl(createStartVar("tempa", "tempb"));
611 prl(createTopTwoEStack());
612 prl(createToEStack("tempb"));
613 prl(createToEStack("tempa"));
614 prl(createToEStack("tempb"));
615 prl(createToEStack("tempa"));
621 prl(createPopEStack());
626 prl("CALL a" + (counter
+ get2()) + ";");
636 prl(createStartVar("tempa", "tempb"));
637 prl(createTopTwoEStack());
638 prl("IF tempb " + getRelationFor(op
)
639 + " tempa THEN mjvm_flag_jump := 1"
640 + " ELSE mjvm_flag_jump := 0"
643 prl("IF mjvm_flag_jump = 1 THEN CALL a"
645 + " ELSE CALL a" + (counter
+ 1)
652 prl("CALL a" + (counter
+ get2()) + ";");
657 // we let the actions return
658 // there is nothing to clean up
659 prl("SKIP\n END\n b" + counter
+ " ==");
663 int parameters
= get();
666 prl(createToMStack("mjvm_locals"));
667 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
668 for (int i
= parameters
- 1; i
>= 0; i
--)
669 prl(createFromEStack(createLocal(i
)));
673 prl(createFromMStack("mjvm_locals"));
679 // TODO make it a char for read
680 messages
.message("char is read like a number", TransMessages
.M_WAR
);
681 prl(createComment("char is read like a number", C_SPEC
));
684 prl(createStartVar("tempa"));
685 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
686 prl(createToEStack("tempa"));
693 prl(createStartVar("tempa", "tempb"));
694 prl(createTopTwoEStack());
696 prl(createComment("print spacing and transformation",C_SPEC
));
697 prl("PRINFLUSH(SUBSTR(\" \", 0, MIN(10, MAX(0,tempa-1))), @List_To_String(< tempb >));");
699 prl("Print_MJ_CHAR(tempb,tempa);");
704 // TODO printing numbers needs different lengths of spacing
705 prl(createStartVar("tempa", "tempb"));
707 prl(createTopTwoEStack());
709 prl(createComment("print spacing",C_SPEC
));
710 prl("PRINFLUSH(SUBSTR(\" \", 0, MIN(10, MAX(0, tempa-1))), tempb);");
713 prl("Print_MJ(tempb,tempa);");
719 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
724 prl(createComment("unknown op error: " + op
, C_ERR
));
725 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
729 boolean wasJump
= isJumpCode(op
);
735 prl("CALL a" + counter
+ "\n END");
737 prl("SKIP\n END\nENDACTIONS;\n");
738 pr(createStandardEnd());
741 public void convertFile(File f
) {
743 convertStream(new FileInputStream(f
));
744 } catch (Exception ex
) {
745 ex
.printStackTrace();
749 public void printHelp() {
756 public void printLongHelp() {
759 System
.out
.println();
761 System
.out
.println();
762 printHelpDirectives();
763 System
.out
.println();
764 printHelpGenerating();
765 System
.out
.println();
769 public void printHelpOutput() {
770 System
.out
.println("Output options:");
771 System
.out
.println(" --screen print output to screen");
772 System
.out
.println(" -o --oc[+-] include original code in comments");
773 System
.out
.println(" -v verbose, print warning messages");
774 System
.out
.println(" -q quiet; don't print even the error messages");
775 System
.out
.println(" -d print detailed debug messages");
778 public void printHelpGenerating() {
779 System
.out
.println("Options for generating extra code for tracking code execution");
780 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
781 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
782 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
783 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
784 System
.out
.println(" --genAll short for applying all code generation");
787 public void printHelpDirectives(){
788 System
.out
.println("Alternatives for code generation:");
789 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
792 public void printHelpHelp() {
793 System
.out
.println("Help and info options");
794 System
.out
.println(" -h basic help");
795 System
.out
.println(" --help print more detailed help");
796 System
.out
.println(" --version or -version print version and exit");
799 public void printUsage(){
800 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
803 public void printVersion() {
804 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
805 + ", by Doni Pracner");
808 public String
makeDefaultOutName(String inname
){
810 if (inname
.endsWith(".obj"))
811 rez
= rez
.substring(0, rez
.length() - 4);
815 public void run(String
[] args
) {
816 if (args
.length
== 0) {
820 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
821 if (args
[i
].compareTo("-h") == 0) {
824 } else if (args
[i
].compareTo("--help") == 0) {
827 } else if (args
[i
].compareTo("--version") == 0
828 || args
[i
].compareTo("-version") == 0) {
831 } else if (args
[i
].compareTo("-o") == 0
832 || args
[i
].startsWith("--oc")) {
833 if (args
[i
].length() == 2)
834 originalInComments
= true;
835 else if (args
[i
].length() == 5)
836 originalInComments
= args
[i
].charAt(4) == '+';
838 originalInComments
= true;
839 } else if (args
[i
].compareTo("--screen") == 0) {
840 out
= new PrintWriter(System
.out
);
841 } else if (args
[i
].compareTo("-d") == 0) {
842 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
843 } else if (args
[i
].compareTo("-v") == 0) {
844 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
845 } else if (args
[i
].compareTo("-q") == 0) {
846 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
847 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
848 genPrintEStackOnChange
= true;
849 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
850 genPauseAfterEachAddress
= true;
851 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
852 genPrintForEachAddress
= true;
853 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
854 genPrintForEachAddress
= true;
855 genPauseAfterEachAddress
= true;
856 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
857 genPrintEStackOnChange
= true;
858 genPrintForEachAddress
= true;
859 genPauseAfterEachAddress
= true;
860 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
862 } else if (args
[i
].compareToIgnoreCase("--genInlinePrint") == 0) {
863 genInlinePrint
= true;
868 if (i
>= args
.length
) {
869 System
.out
.println("no filename supplied");
872 File f
= new File(args
[i
]);
874 if (i
+ 1 < args
.length
) {
876 out
= new PrintWriter(args
[i
+ 1]);
877 } catch (Exception e
) {
878 System
.err
.println("error in opening out file:");
883 // if not set to screen, or a file, make a default filename
885 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
886 } catch (Exception e
) {
887 System
.err
.println("error in opening out file:");
892 Calendar now
= Calendar
.getInstance();
894 long mili
= Calendar
.getInstance().getTimeInMillis()
895 - now
.getTimeInMillis();
896 System
.out
.println("conversion time:" + mili
+ " ms");
897 messages
.printMessageCounters();
900 System
.out
.println("file does not exist");
904 public static void main(String
[] args
) {
905 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner