gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
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.2.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("PRINFLUSH(@Format(format, val ))");
215 ret
.append("\nEND\n");
217 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
218 ret
.append("PRINFLUSH(@Format(format, CHR(val)))");
219 ret
.append("\nEND\n");
223 return ret
.toString();
226 private String
createStartVar(String
... vars
){
228 StringBuilder ret
= new StringBuilder("VAR < ");
229 ret
.append(vars
[0] + " := 0");
230 for (int i
= 1; i
< vars
.length
; i
++)
231 ret
.append(", " + vars
[i
] + " := 0");
234 return ret
.toString();
239 private String
createEndVar(){
246 private String
createLocal(int i
) {
247 // arrays start at 1 in WSL, so we need an offset
248 return "mjvm_locals[" + (i
+ 1) + "]";
251 private String
createStatic(int i
) {
252 return "mjvm_statics[" + (i
+ 1) + "]";
255 private String
createArray(int i
) {
256 return "mjvm_arrays[" + i
+ "]";
259 private String
createArray(String i
) {
260 return "mjvm_arrays[" + i
+ "]";
263 private String
createObject(String i
) {
264 return "mjvm_objects[" + i
+ "]";
268 * Creates a WSL comment with care to quote chars.
270 public static String
createComment(String str
){
271 return createComment(str
, C_REG
);
275 * Creates a WSL comment with care to quote chars, of the
276 * given type. Types are given as char constants. They can be
277 * default comments, comments that contain the original code
278 * in them, or additional comments regarding the translation
281 public static String
createComment(String str
, char type
) {
282 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
285 // generalised stack operations
287 private String
createToStack(String stack
, String var
){
289 return "PUSH("+stack
+"," + var
+ ");";
291 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
294 private String
createFromStack(String stack
, String var
){
296 return "POP("+ var
+ ", "+stack
+");";
298 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
302 private String
createToEStack(int i
) {
303 return createToEStack(i
+"");
306 private String
createToEStack(String i
) {
307 String res
= createToStack("mjvm_estack", i
);
308 if (genPrintEStackOnChange
)
309 res
+= "PRINT(\"eStack\",mjvm_estack);";
313 private String
createFromEStack(String st
) {
314 String res
= createFromStack("mjvm_estack",st
);
315 if (genPrintEStackOnChange
)
316 res
+= "PRINT(\"eStack\",mjvm_estack);";
320 private String
createPopEStack() {
321 String res
= "mjvm_estack := TAIL(mjvm_estack);";
322 if (genPrintEStackOnChange
)
323 res
+= "PRINT(\"eStack\",mjvm_estack);";
327 private String
createTopTwoEStack() {
328 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
331 private String
createTopEStack() {
332 return createFromEStack("tempa");
337 private String
createToMStack(int i
) {
338 return createToMStack(i
+"");
341 private String
createToMStack(String i
) {
342 return createToStack("mjvm_mstack", i
);
345 private String
createFromMStack(String st
) {
346 return createFromStack("mjvm_mstack", st
);
349 public void convertStream(InputStream ins
) throws Exception
{
350 mjInput
.setStream(ins
);
352 mjInput
.processHeader(this);
354 prl(createStandardStart(mjInput
.getNumberOfWords(this)));
355 prl("SKIP;\n ACTIONS a" + (14 + mjInput
.getMainAdr(this)) + " :");
356 int op
= mjInput
.get();
358 prl(" a" + mjInput
.getCounter() + " ==");
359 if (originalInComments
)
360 prl(createComment(mjInput
.describeOpCode(op
), C_OC
));
361 if (genPrintForEachAddress
) {
362 prl("PRINT(\"a" + mjInput
.getCounter() + "\");");
363 if (genPauseAfterEachAddress
)
364 prl("@Read_Line_Proc(VAR debug_disposable_string, Standard_Input_Port);");
368 prl(createToEStack(createLocal(mjInput
.get())));
375 prl(createStartVar("tempa"));
376 prl("tempa :="+createLocal(op
- load_0
)+";");
377 prl(createToEStack("tempa"));
382 prl(createFromEStack(createLocal(mjInput
.get())));
389 prl(createStartVar("tempa"));
390 prl(createFromEStack("tempa"));
391 prl(createLocal(op
- store_0
)+" := tempa;");
397 prl(createToEStack(createStatic(mjInput
.get2())));
401 prl(createFromEStack(createStatic(mjInput
.get2())));
406 int f
= mjInput
.get2();
407 prl(createStartVar("tempa"));
408 prl(createTopEStack());
409 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
414 int f
= mjInput
.get2();
415 prl(createStartVar("tempa", "tempb"));
416 prl(createTopTwoEStack());
417 prl(createObject("tempb") + "[" + (f
+ 1) + "]:=tempa;");
423 prl(createToEStack(mjInput
.get4()));
428 prl(createToEStack(-1));
438 prl(createToEStack(op
- const_0
));
443 prl(createStartVar("tempa", "tempb", "tempres"));
444 prl(createTopTwoEStack());
445 prl("tempres := tempb + tempa;");
446 prl(createToEStack("tempres"));
451 prl(createStartVar("tempa", "tempb", "tempres"));
452 prl(createTopTwoEStack());
453 prl("tempres := tempb - tempa;");
454 prl(createToEStack("tempres"));
459 prl(createStartVar("tempa", "tempb", "tempres"));
460 prl(createTopTwoEStack());
461 prl("tempres := tempb * tempa;");
462 prl(createToEStack("tempres"));
467 prl(createStartVar("tempa", "tempb", "tempres"));
468 prl(createTopTwoEStack());
469 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
470 prl("tempres := tempb DIV tempa;");
471 prl(createToEStack("tempres"));
476 prl(createStartVar("tempa", "tempb", "tempres"));
477 prl(createTopTwoEStack());
478 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
479 prl("tempres := tempb MOD tempa;");
480 prl(createToEStack("tempres"));
486 prl(createStartVar("tempa"));
487 prl(createTopEStack());
488 prl(createToEStack("-tempa"));
494 prl(createStartVar("tempa", "tempb"));
495 prl(createTopTwoEStack());
496 prl("VAR <tempres :=tempb, i:=1 >:");
497 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
498 prl(createToEStack("tempres"));
504 prl(createStartVar("tempa", "tempb"));
505 prl(createTopTwoEStack());
506 prl("VAR <tempres :=tempb, i:=1 >:");
507 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
508 prl(createToEStack("tempres"));
515 int b1
= mjInput
.get(), b2
= mjInput
.get();
516 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
521 int size
= mjInput
.get2();
522 // TODO maybe objects and arrays should be in the same list?
523 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
525 prl(createToEStack("LENGTH(mjvm_objects)"));
529 mjInput
.get();// 0 - bytes, 1 - words; ignore for now
530 // TODO take into consideration 0/1
531 prl(createStartVar("tempa"));
532 prl(createTopEStack());
533 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
534 prl(createToEStack("LENGTH(mjvm_arrays)"));
541 prl(createStartVar("tempa", "tempb"));
542 prl(createTopTwoEStack());
543 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
549 prl(createStartVar("tempa", "tempb", "tempres"));
550 prl(createFromEStack("tempres"));
551 prl(createTopTwoEStack());
552 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
557 prl(createStartVar("tempa", "tempb"));
558 prl(createTopEStack());
559 prl("tempb := LENGTH("+ createArray("tempa") + ");");
560 prl(createToEStack("tempb"));
566 prl(createStartVar("tempa", "tempb"));
567 prl(createTopEStack());
568 prl(createToEStack("tempa"));
569 prl(createToEStack("tempa"));
574 prl(createStartVar("tempa", "tempb"));
575 prl(createTopTwoEStack());
576 prl(createToEStack("tempb"));
577 prl(createToEStack("tempa"));
578 prl(createToEStack("tempb"));
579 prl(createToEStack("tempa"));
585 prl(createPopEStack());
590 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
601 prl(createStartVar("tempa", "tempb"));
602 prl(createTopTwoEStack());
603 prl("IF tempb " + mjInput
.getRelationFor(op
)
604 + " tempa THEN mjvm_flag_jump := 1"
605 + " ELSE mjvm_flag_jump := 0"
608 prl("IF mjvm_flag_jump = 1 THEN CALL a"
609 + (mjInput
.getCounter() + mjInput
.get2())
610 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
613 prl(createTopTwoEStack());
614 prl("IF tempb " + mjInput
.getRelationFor(op
)
615 + " tempa THEN CALL a"
616 + (mjInput
.getCounter() + mjInput
.get2())
617 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
624 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
629 // we let the actions return
630 // there is nothing to clean up
631 prl("SKIP\n END\n b" + mjInput
.getCounter() + " ==");
635 int parameters
= mjInput
.get();
637 int locals
= mjInput
.get();
638 prl(createToMStack("mjvm_locals"));
639 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
640 for (int i
= parameters
- 1; i
>= 0; i
--)
641 prl(createFromEStack(createLocal(i
)));
645 prl(createFromMStack("mjvm_locals"));
651 // TODO maybe we'll need a bufer for multi chars!
652 prl(createStartVar("tempa"));
653 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
654 prl("tempa := @String_To_List(tempa)[1];");
655 prl(createToEStack("tempa"));
660 prl(createStartVar("tempa"));
661 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
662 prl("tempa := @String_To_Num(tempa);");
663 prl(createToEStack("tempa"));
670 prl(createStartVar("tempa", "tempb"));
671 prl(createTopTwoEStack());
673 prl(createComment("print spacing and transformation",C_SPEC
));
674 prl("PRINFLUSH(@Format(tempa, @List_To_String(< tempb >)));");
676 prl("Print_MJ_CHAR(tempb,tempa);");
681 prl(createStartVar("tempa", "tempb"));
683 prl(createTopTwoEStack());
685 prl(createComment("print spacing",C_SPEC
));
686 prl("PRINFLUSH(@Format(tempa,tempb));");
689 prl("Print_MJ(tempb,tempa);");
695 prl("ERROR(\"Runtime error: trap(" + mjInput
.get() + ")\");");
700 prl(createComment("unknown op error: " + op
, C_ERR
));
701 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
705 boolean wasJump
= mjInput
.isJumpCode(op
);
711 prl("CALL a" + mjInput
.getCounter() + "\n END");
713 prl("SKIP\n END\nENDACTIONS;\n");
714 pr(createStandardEnd());
717 public void convertFile(File f
) {
719 convertStream(new FileInputStream(f
));
720 } catch (Exception ex
) {
721 ex
.printStackTrace();
725 public void printHelp() {
732 public void printLongHelp() {
735 System
.out
.println();
737 System
.out
.println();
738 printHelpDirectives();
739 System
.out
.println();
740 printHelpGenerating();
741 System
.out
.println();
745 public void printHelpOutput() {
746 System
.out
.println("Output options:");
747 System
.out
.println(" --screen print output to screen");
748 System
.out
.println(" -o --oc[+-] include original code in comments");
749 System
.out
.println(" -v verbose, print warning messages");
750 System
.out
.println(" -q quiet; don't print even the error messages");
751 System
.out
.println(" -d print detailed debug messages");
754 public void printHelpGenerating() {
755 System
.out
.println("Options for generating extra code for tracking code execution");
756 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
757 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
758 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
759 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
760 System
.out
.println(" --genAll short for applying all code generation");
763 public void printHelpDirectives(){
764 System
.out
.println("Alternatives for code generation (* are the defaults):");
765 System
.out
.print(genPopPush?
'*':' ');
766 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
767 System
.out
.print(!genPopPush?
'*':' ');
768 System
.out
.println(" --genHeadTail generate TAIL/HEAD instead of POP/PUSH ");
769 System
.out
.println();
770 System
.out
.print(genInlinePrint?
'*':' ');
771 System
.out
.println(" --genInlinePrint generate prints directly instead of procedure calls");
772 System
.out
.print(!genInlinePrint?
'*':' ');
773 System
.out
.println(" --genProcedurePrint generate prints as custom procedure calls");
774 System
.out
.println();
775 System
.out
.print(genLocalVars?
'*':' ');
776 System
.out
.println(" --genLocalVars generate local VAR block for temp variables");
777 System
.out
.print(!genLocalVars?
'*':' ');
778 System
.out
.println(" --genGlobalVars do NOT generate local VAR block for temp variables");
781 public void printHelpHelp() {
782 System
.out
.println("Help and info options");
783 System
.out
.println(" -h basic help");
784 System
.out
.println(" --help print more detailed help");
785 System
.out
.println(" --version or -version print version and exit");
788 public void printUsage(){
789 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
792 public void printVersion() {
793 System
.out
.println("MicroJava bytecode to WSL converter. v " + getVersion()
794 + ", by Doni Pracner");
797 public String
makeDefaultOutName(String inname
){
799 if (inname
.endsWith(".obj"))
800 rez
= rez
.substring(0, rez
.length() - 4);
804 public void run(String
[] args
) {
805 if (args
.length
== 0) {
809 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
810 if (args
[i
].compareTo("-h") == 0) {
813 } else if (args
[i
].compareTo("--help") == 0) {
816 } else if (args
[i
].compareTo("--version") == 0
817 || args
[i
].compareTo("-version") == 0) {
820 } else if (args
[i
].compareTo("-o") == 0
821 || args
[i
].startsWith("--oc")) {
822 if (args
[i
].length() == 2)
823 originalInComments
= true;
824 else if (args
[i
].length() == 5)
825 originalInComments
= args
[i
].charAt(4) == '+';
827 originalInComments
= true;
828 } else if (args
[i
].compareTo("--screen") == 0) {
829 out
= new PrintWriter(System
.out
);
830 } else if (args
[i
].compareTo("-d") == 0) {
831 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
832 } else if (args
[i
].compareTo("-v") == 0) {
833 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
834 } else if (args
[i
].compareTo("-q") == 0) {
835 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
836 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
837 genPrintEStackOnChange
= true;
838 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
839 genPauseAfterEachAddress
= true;
840 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
841 genPrintForEachAddress
= true;
842 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
843 genPrintForEachAddress
= true;
844 genPauseAfterEachAddress
= true;
845 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
846 genPrintEStackOnChange
= true;
847 genPrintForEachAddress
= true;
848 genPauseAfterEachAddress
= true;
849 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
851 } else if (args
[i
].compareToIgnoreCase("--genInlinePrint") == 0) {
852 genInlinePrint
= true;
853 } else if (args
[i
].compareToIgnoreCase("--genHeadTail") == 0) {
855 } else if (args
[i
].compareToIgnoreCase("--genProcedurePrint") == 0) {
856 genInlinePrint
= false;
857 } else if (args
[i
].compareToIgnoreCase("--genLocalVars") == 0) {
859 } else if (args
[i
].compareToIgnoreCase("--genGlobalVars") == 0) {
860 genLocalVars
= false;
862 System
.err
.println("unknown option: "+args
[i
]);
867 if (i
>= args
.length
) {
868 System
.err
.println("no filename supplied");
872 Path p
= FileSystems
.getDefault().getPath(args
[i
]);
873 if (!Files
.exists(p
)){
874 System
.err
.println("input file does not exist");
878 if (i
+ 1 < args
.length
) {
880 out
= new PrintWriter(args
[i
+ 1]);
881 } catch (Exception e
) {
882 System
.err
.println("error in opening out file:");
887 // if not set to screen, or a file, make a default filename
889 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
890 } catch (Exception e
) {
891 System
.err
.println("error in opening out file:");
895 Calendar now
= Calendar
.getInstance();
897 convertStream(Files
.newInputStream(p
));
898 } catch (Exception e
) {
899 // TODO Auto-generated catch block
902 long mili
= Calendar
.getInstance().getTimeInMillis()
903 - now
.getTimeInMillis();
904 System
.out
.println("conversion time:" + mili
+ " ms");
905 messages
.printMessageCounters();
910 public static void main(String
[] args
) {
911 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner