gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
f5714aa692cb59df48c67ad996b09d2df75e48d8
1 package com
.quemaster
.transformations
.mjc2wsl
;
3 Copyright (C) 2014 Doni Pracner
5 This file is part of mjc2wsl.
7 mjc2wsl is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 mjc2wsl is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with mjc2wsl. If not, see <http://www.gnu.org/licenses/>.
21 import java
.io
.FileInputStream
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.io
.PrintWriter
;
25 import java
.nio
.file
.FileSystems
;
26 import java
.nio
.file
.Files
;
27 import java
.nio
.file
.Path
;
28 import java
.util
.Calendar
;
29 import java
.util
.Properties
;
31 import com
.quemaster
.transformations
.TransMessages
;
34 * This program converts file from compiled MicroJava bytecode to WSL language
35 * which is a part of the FermaT Transformation system. MicroJava is a subset
36 * used in Compiler Construction courses by Hanspeter Moessenboeck, not
39 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
42 //default version name, used if the file is not found
43 private static String versionN
= "0.1.x";
45 private String versionFile
= "/version.properties";
47 private TransMessages messages
= new TransMessages();
49 private boolean genPauseAfterEachAddress
=false,
50 genPrintForEachAddress
= false,
51 genPrintEStackOnChange
= false;
53 private boolean genPopPush
=false;
55 private boolean genInlinePrint
= false;
57 private boolean genLocalVars
= true;
59 /** Constant used for marking a regular comment from the original file */
60 public static final char C_REG
= ' ';
62 * Constant used for marking when original code is inserted in the file,
63 * next to the translations
65 public static final char C_OC
= '#';
66 /** Constant used for marking special messages from the translator */
67 public static final char C_SPEC
= '&';
68 /** Constant used for marking error messages from the translator */
69 public static final char C_ERR
= '!';
71 /** instruction code in MicroJava bytecode. */
72 public static final int
131 private boolean originalInComments
= false;
133 private Properties versionData
;
135 private String
getVersion() {
136 if (versionData
== null) {
137 versionData
= new Properties();
139 versionData
.load(getClass().getResourceAsStream(versionFile
));
140 } catch (IOException e
) {
144 String ver
= versionData
.getProperty("version");
151 MicroJavaInput mjInput
= new MicroJavaInput();
153 private PrintWriter out
= null;
156 private void pr(int i
){
160 private void pr(char i
){
164 private void pr(String i
){
168 private void prl(String i
){
172 public String
createStandardStart(){
173 return createStandardStart(10);
176 public String
createStandardStart(int numWords
){
177 StringBuilder ret
= new StringBuilder(
178 "C:\" This file automatically converted from microjava bytecode\";\n"
179 +"C:\" with mjc2wsl v "+getVersion()+"\";\n");
181 ret
.append("\nBEGIN");
182 ret
.append("\nVAR <\n\t");
184 ret
.append("\n\ttempa := 0, tempb :=0, tempres := 0,");
186 ret
.append("\n\tmjvm_flag_jump := 0,");
187 ret
.append("mjvm_locals := ARRAY(1,0),");
188 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
189 ret
.append("\n\tmjvm_arrays := < >,");
190 ret
.append("\n\tmjvm_objects := < >,");
191 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
193 return ret
.toString();
196 public String
createAsciiString(){
197 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
198 ret
.append("\nascii := \"????????????????????????????????\"++\n");
199 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
201 return ret
.toString();
204 public String
createStandardEnd(){
205 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
206 ret
.append("\nWHERE\n");
208 ret
.append("\nFUNCT CHR(num) ==:\n");
209 ret
.append("\t@List_To_String(< num >)\n");
212 if (!genInlinePrint
) {
213 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
214 ret
.append(createComment("print spacing", C_SPEC
));
215 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=1 TO ");
216 ret
.append("MAX(0, format-SLENGTH(@String(val))) STEP 1 DO PRINFLUSH(\" \") OD\n");
217 ret
.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
219 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
220 ret
.append(createComment("print spacing", C_SPEC
));
221 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
222 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
223 ret
.append("\tFI;\n\tPRINFLUSH(CHR(val))\n");
228 return ret
.toString();
231 private String
createStartVar(String
... vars
){
233 StringBuilder ret
= new StringBuilder("VAR < ");
234 ret
.append(vars
[0] + " := 0");
235 for (int i
= 1; i
< vars
.length
; i
++)
236 ret
.append(", " + vars
[i
] + " := 0");
239 return ret
.toString();
244 private String
createEndVar(){
251 private String
createLocal(int i
) {
252 // arrays start at 1 in WSL, so we need an offset
253 return "mjvm_locals[" + (i
+ 1) + "]";
256 private String
createStatic(int i
) {
257 return "mjvm_statics[" + (i
+ 1) + "]";
260 private String
createArray(int i
) {
261 return "mjvm_arrays[" + i
+ "]";
264 private String
createArray(String i
) {
265 return "mjvm_arrays[" + i
+ "]";
268 private String
createObject(String i
) {
269 return "mjvm_objects[" + i
+ "]";
273 * Creates a WSL comment with care to quote chars.
275 public static String
createComment(String str
){
276 return createComment(str
, C_REG
);
280 * Creates a WSL comment with care to quote chars, of the
281 * given type. Types are given as char constants. They can be
282 * default comments, comments that contain the original code
283 * in them, or additional comments regarding the translation
286 public static String
createComment(String str
, char type
) {
287 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
290 // generalised stack operations
292 private String
createToStack(String stack
, String var
){
294 return "PUSH("+stack
+"," + var
+ ");";
296 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
299 private String
createFromStack(String stack
, String var
){
301 return "POP("+ var
+ ", "+stack
+");";
303 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
307 private String
createToEStack(int i
) {
308 return createToEStack(i
+"");
311 private String
createToEStack(String i
) {
312 String res
= createToStack("mjvm_estack", i
);
313 if (genPrintEStackOnChange
)
314 res
+= "PRINT(\"eStack\",mjvm_estack);";
318 private String
createFromEStack(String st
) {
319 String res
= createFromStack("mjvm_estack",st
);
320 if (genPrintEStackOnChange
)
321 res
+= "PRINT(\"eStack\",mjvm_estack);";
325 private String
createPopEStack() {
326 String res
= "mjvm_estack := TAIL(mjvm_estack);";
327 if (genPrintEStackOnChange
)
328 res
+= "PRINT(\"eStack\",mjvm_estack);";
332 private String
createTopTwoEStack() {
333 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
336 private String
createTopEStack() {
337 return createFromEStack("tempa");
342 private String
createToMStack(int i
) {
343 return createToMStack(i
+"");
346 private String
createToMStack(String i
) {
347 return createToStack("mjvm_mstack", i
);
350 private String
createFromMStack(String st
) {
351 return createFromStack("mjvm_mstack", st
);
354 public void convertStream(InputStream ins
) throws Exception
{
355 mjInput
.setStream(ins
);
357 mjInput
.processHeader(this);
359 prl(createStandardStart(mjInput
.getNumberOfWords(this)));
360 prl("SKIP;\n ACTIONS a" + (14 + mjInput
.getMainAdr(this)) + " :");
361 int op
= mjInput
.get();
363 prl(" a" + mjInput
.getCounter() + " ==");
364 if (originalInComments
)
365 prl(createComment(mjInput
.describeOpCode(op
), C_OC
));
366 if (genPrintForEachAddress
) {
367 prl("PRINT(\"a" + mjInput
.getCounter() + "\");");
368 if (genPauseAfterEachAddress
)
369 prl("@Read_Line_Proc(VAR debug_disposable_string, Standard_Input_Port);");
373 prl(createToEStack(createLocal(mjInput
.get())));
380 prl(createStartVar("tempa"));
381 prl("tempa :="+createLocal(op
- load_0
)+";");
382 prl(createToEStack("tempa"));
387 prl(createFromEStack(createLocal(mjInput
.get())));
394 prl(createStartVar("tempa"));
395 prl(createFromEStack("tempa"));
396 prl(createLocal(op
- store_0
)+" := tempa;");
402 prl(createToEStack(createStatic(mjInput
.get2())));
406 prl(createFromEStack(createStatic(mjInput
.get2())));
411 int f
= mjInput
.get2();
412 prl(createStartVar("tempa"));
413 prl(createTopEStack());
414 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
419 int f
= mjInput
.get2();
420 prl(createStartVar("tempa", "tempb"));
421 prl(createTopTwoEStack());
422 prl(createObject("tempb") + "[" + (f
+ 1) + "]:=tempa;");
428 prl(createToEStack(mjInput
.get4()));
433 prl(createToEStack(-1));
443 prl(createToEStack(op
- const_0
));
448 prl(createStartVar("tempa", "tempb", "tempres"));
449 prl(createTopTwoEStack());
450 prl("tempres := tempb + tempa;");
451 prl(createToEStack("tempres"));
456 prl(createStartVar("tempa", "tempb", "tempres"));
457 prl(createTopTwoEStack());
458 prl("tempres := tempb - tempa;");
459 prl(createToEStack("tempres"));
464 prl(createStartVar("tempa", "tempb", "tempres"));
465 prl(createTopTwoEStack());
466 prl("tempres := tempb * tempa;");
467 prl(createToEStack("tempres"));
472 prl(createStartVar("tempa", "tempb", "tempres"));
473 prl(createTopTwoEStack());
474 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
475 prl("tempres := tempb DIV tempa;");
476 prl(createToEStack("tempres"));
481 prl(createStartVar("tempa", "tempb", "tempres"));
482 prl(createTopTwoEStack());
483 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
484 prl("tempres := tempb MOD tempa;");
485 prl(createToEStack("tempres"));
491 prl(createStartVar("tempa"));
492 prl(createTopEStack());
493 prl(createToEStack("-tempa"));
499 prl(createStartVar("tempa", "tempb"));
500 prl(createTopTwoEStack());
501 prl("VAR <tempres :=tempb, i:=1 >:");
502 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
503 prl(createToEStack("tempres"));
509 prl(createStartVar("tempa", "tempb"));
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"));
520 int b1
= mjInput
.get(), b2
= mjInput
.get();
521 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
526 int size
= mjInput
.get2();
527 // TODO maybe objects and arrays should be in the same list?
528 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
530 prl(createToEStack("LENGTH(mjvm_objects)"));
534 mjInput
.get();// 0 - bytes, 1 - words; ignore for now
535 // TODO take into consideration 0/1
536 prl(createStartVar("tempa"));
537 prl(createTopEStack());
538 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
539 prl(createToEStack("LENGTH(mjvm_arrays)"));
546 prl(createStartVar("tempa", "tempb"));
547 prl(createTopTwoEStack());
548 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
554 prl(createStartVar("tempa", "tempb", "tempres"));
555 prl(createFromEStack("tempres"));
556 prl(createTopTwoEStack());
557 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
562 prl(createStartVar("tempa", "tempb"));
563 prl(createTopEStack());
564 prl("tempb := LENGTH("+ createArray("tempa") + ");");
565 prl(createToEStack("tempb"));
571 prl(createStartVar("tempa", "tempb"));
572 prl(createTopEStack());
573 prl(createToEStack("tempa"));
574 prl(createToEStack("tempa"));
579 prl(createStartVar("tempa", "tempb"));
580 prl(createTopTwoEStack());
581 prl(createToEStack("tempb"));
582 prl(createToEStack("tempa"));
583 prl(createToEStack("tempb"));
584 prl(createToEStack("tempa"));
590 prl(createPopEStack());
595 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
606 prl(createStartVar("tempa", "tempb"));
607 prl(createTopTwoEStack());
608 prl("IF tempb " + mjInput
.getRelationFor(op
)
609 + " tempa THEN mjvm_flag_jump := 1"
610 + " ELSE mjvm_flag_jump := 0"
613 prl("IF mjvm_flag_jump = 1 THEN CALL a"
614 + (mjInput
.getCounter() + mjInput
.get2())
615 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
618 prl(createTopTwoEStack());
619 prl("IF tempb " + mjInput
.getRelationFor(op
)
620 + " tempa THEN CALL a"
621 + (mjInput
.getCounter() + mjInput
.get2())
622 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
629 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
634 // we let the actions return
635 // there is nothing to clean up
636 prl("SKIP\n END\n b" + mjInput
.getCounter() + " ==");
640 int parameters
= mjInput
.get();
642 int locals
= mjInput
.get();
643 prl(createToMStack("mjvm_locals"));
644 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
645 for (int i
= parameters
- 1; i
>= 0; i
--)
646 prl(createFromEStack(createLocal(i
)));
650 prl(createFromMStack("mjvm_locals"));
656 // TODO maybe we'll need a bufer for multi chars!
657 prl(createStartVar("tempa"));
658 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
659 prl("tempa := @String_To_List(tempa)[1];");
660 prl(createToEStack("tempa"));
665 prl(createStartVar("tempa"));
666 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
667 prl("tempa := @String_To_Num(tempa);");
668 prl(createToEStack("tempa"));
675 prl(createStartVar("tempa", "tempb"));
676 prl(createTopTwoEStack());
678 prl(createComment("print spacing and transformation",C_SPEC
));
679 prl("PRINFLUSH(@Format(tempa, @List_To_String(< tempb >)));");
681 prl("Print_MJ_CHAR(tempb,tempa);");
686 prl(createStartVar("tempa", "tempb"));
688 prl(createTopTwoEStack());
690 prl(createComment("print spacing",C_SPEC
));
691 prl("PRINFLUSH(@Format(tempa,tempb));");
694 prl("Print_MJ(tempb,tempa);");
700 prl("ERROR(\"Runtime error: trap(" + mjInput
.get() + ")\");");
705 prl(createComment("unknown op error: " + op
, C_ERR
));
706 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
710 boolean wasJump
= mjInput
.isJumpCode(op
);
716 prl("CALL a" + mjInput
.getCounter() + "\n END");
718 prl("SKIP\n END\nENDACTIONS;\n");
719 pr(createStandardEnd());
722 public void convertFile(File f
) {
724 convertStream(new FileInputStream(f
));
725 } catch (Exception ex
) {
726 ex
.printStackTrace();
730 public void printHelp() {
737 public void printLongHelp() {
740 System
.out
.println();
742 System
.out
.println();
743 printHelpDirectives();
744 System
.out
.println();
745 printHelpGenerating();
746 System
.out
.println();
750 public void printHelpOutput() {
751 System
.out
.println("Output options:");
752 System
.out
.println(" --screen print output to screen");
753 System
.out
.println(" -o --oc[+-] include original code in comments");
754 System
.out
.println(" -v verbose, print warning messages");
755 System
.out
.println(" -q quiet; don't print even the error messages");
756 System
.out
.println(" -d print detailed debug messages");
759 public void printHelpGenerating() {
760 System
.out
.println("Options for generating extra code for tracking code execution");
761 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
762 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
763 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
764 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
765 System
.out
.println(" --genAll short for applying all code generation");
768 public void printHelpDirectives(){
769 System
.out
.println("Alternatives for code generation (* are the defaults):");
770 System
.out
.print(genPopPush?
'*':' ');
771 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
772 System
.out
.print(!genPopPush?
'*':' ');
773 System
.out
.println(" --genHeadTail generate TAIL/HEAD instead of POP/PUSH ");
774 System
.out
.println();
775 System
.out
.print(genInlinePrint?
'*':' ');
776 System
.out
.println(" --genInlinePrint generate prints directly instead of procedure calls");
777 System
.out
.print(!genInlinePrint?
'*':' ');
778 System
.out
.println(" --genProcedurePrint generate prints as custom procedure calls");
779 System
.out
.println();
780 System
.out
.print(genLocalVars?
'*':' ');
781 System
.out
.println(" --genLocalVars generate local VAR block for temp variables");
782 System
.out
.print(!genLocalVars?
'*':' ');
783 System
.out
.println(" --genGlobalVars do NOT generate local VAR block for temp variables");
786 public void printHelpHelp() {
787 System
.out
.println("Help and info options");
788 System
.out
.println(" -h basic help");
789 System
.out
.println(" --help print more detailed help");
790 System
.out
.println(" --version or -version print version and exit");
793 public void printUsage(){
794 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
797 public void printVersion() {
798 System
.out
.println("MicroJava bytecode to WSL converter. v " + getVersion()
799 + ", by Doni Pracner");
802 public String
makeDefaultOutName(String inname
){
804 if (inname
.endsWith(".obj"))
805 rez
= rez
.substring(0, rez
.length() - 4);
809 public void run(String
[] args
) {
810 if (args
.length
== 0) {
814 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
815 if (args
[i
].compareTo("-h") == 0) {
818 } else if (args
[i
].compareTo("--help") == 0) {
821 } else if (args
[i
].compareTo("--version") == 0
822 || args
[i
].compareTo("-version") == 0) {
825 } else if (args
[i
].compareTo("-o") == 0
826 || args
[i
].startsWith("--oc")) {
827 if (args
[i
].length() == 2)
828 originalInComments
= true;
829 else if (args
[i
].length() == 5)
830 originalInComments
= args
[i
].charAt(4) == '+';
832 originalInComments
= true;
833 } else if (args
[i
].compareTo("--screen") == 0) {
834 out
= new PrintWriter(System
.out
);
835 } else if (args
[i
].compareTo("-d") == 0) {
836 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
837 } else if (args
[i
].compareTo("-v") == 0) {
838 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
839 } else if (args
[i
].compareTo("-q") == 0) {
840 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
841 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
842 genPrintEStackOnChange
= true;
843 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
844 genPauseAfterEachAddress
= true;
845 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
846 genPrintForEachAddress
= true;
847 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
848 genPrintForEachAddress
= true;
849 genPauseAfterEachAddress
= true;
850 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
851 genPrintEStackOnChange
= true;
852 genPrintForEachAddress
= true;
853 genPauseAfterEachAddress
= true;
854 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
856 } else if (args
[i
].compareToIgnoreCase("--genInlinePrint") == 0) {
857 genInlinePrint
= true;
858 } else if (args
[i
].compareToIgnoreCase("--genHeadTail") == 0) {
860 } else if (args
[i
].compareToIgnoreCase("--genProcedurePrint") == 0) {
861 genInlinePrint
= false;
862 } else if (args
[i
].compareToIgnoreCase("--genLocalVars") == 0) {
864 } else if (args
[i
].compareToIgnoreCase("--genGlobalVars") == 0) {
865 genLocalVars
= false;
867 System
.err
.println("unknown option: "+args
[i
]);
872 if (i
>= args
.length
) {
873 System
.err
.println("no filename supplied");
877 Path p
= FileSystems
.getDefault().getPath(args
[i
]);
878 if (!Files
.exists(p
)){
879 System
.err
.println("input file does not exist");
883 if (i
+ 1 < args
.length
) {
885 out
= new PrintWriter(args
[i
+ 1]);
886 } catch (Exception e
) {
887 System
.err
.println("error in opening out file:");
892 // if not set to screen, or a file, make a default filename
894 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
895 } catch (Exception e
) {
896 System
.err
.println("error in opening out file:");
900 Calendar now
= Calendar
.getInstance();
902 convertStream(Files
.newInputStream(p
));
903 } catch (Exception e
) {
904 // TODO Auto-generated catch block
907 long mili
= Calendar
.getInstance().getTimeInMillis()
908 - now
.getTimeInMillis();
909 System
.out
.println("conversion time:" + mili
+ " ms");
910 messages
.printMessageCounters();
915 public static void main(String
[] args
) {
916 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner