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,2015, 2016 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
= "v0.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
| NullPointerException e
) {
142 //e.printStackTrace();
145 String ver
= versionData
.getProperty("version");
152 MicroJavaInput mjInput
= new MicroJavaInput();
154 private PrintWriter out
= null;
157 private void pr(int i
){
161 private void pr(char i
){
165 private void pr(String i
){
169 private void prl(String i
){
173 public String
createStandardStart(){
174 return createStandardStart(10);
177 public String
createStandardStart(int numWords
){
178 StringBuilder ret
= new StringBuilder(
179 "C:\" This file automatically converted from microjava bytecode\";\n"
180 +"C:\" with mjc2wsl "+getVersion()+"\";\n");
182 ret
.append("\nBEGIN");
183 ret
.append("\nVAR <\n\t");
185 ret
.append("\n\ttempa := 0, tempb :=0, tempres := 0,");
187 ret
.append("\n\tmjvm_flag_jump := 0,");
188 ret
.append("mjvm_locals := ARRAY(1,0),");
189 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
190 ret
.append("\n\tmjvm_arrays := < >,");
191 ret
.append("\n\tmjvm_objects := < >,");
192 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
194 return ret
.toString();
197 public String
createAsciiString(){
198 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
199 ret
.append("\nascii := \"????????????????????????????????\"++\n");
200 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
202 return ret
.toString();
205 public String
createStandardEnd(){
206 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
207 ret
.append("\nWHERE\n");
209 ret
.append("\nFUNCT CHR(num) ==:\n");
210 ret
.append("\t(@List_To_String(< num >))\n");
213 if (!genInlinePrint
) {
214 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
215 ret
.append("PRINFLUSH(@Format(format, val ))");
216 ret
.append("\nEND\n");
218 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
219 ret
.append("PRINFLUSH(@Format(format, CHR(val)))");
220 ret
.append("\nEND\n");
224 return ret
.toString();
227 private String
createStartVar(String
... vars
){
229 StringBuilder ret
= new StringBuilder("VAR < ");
230 ret
.append(vars
[0] + " := 0");
231 for (int i
= 1; i
< vars
.length
; i
++)
232 ret
.append(", " + vars
[i
] + " := 0");
235 return ret
.toString();
240 private String
createEndVar(){
247 private String
createLocal(int i
) {
248 // arrays start at 1 in WSL, so we need an offset
249 return "mjvm_locals[" + (i
+ 1) + "]";
252 private String
createStatic(int i
) {
253 return "mjvm_statics[" + (i
+ 1) + "]";
256 private String
createArray(int i
) {
257 return "mjvm_arrays[" + i
+ "]";
260 private String
createArray(String i
) {
261 return "mjvm_arrays[" + i
+ "]";
264 private String
createObject(String i
) {
265 return "mjvm_objects[" + i
+ "]";
269 * Creates a WSL comment with care to quote chars.
271 public static String
createComment(String str
){
272 return createComment(str
, C_REG
);
276 * Creates a WSL comment with care to quote chars, of the
277 * given type. Types are given as char constants. They can be
278 * default comments, comments that contain the original code
279 * in them, or additional comments regarding the translation
282 public static String
createComment(String str
, char type
) {
283 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
286 // generalised stack operations
288 private String
createToStack(String stack
, String var
){
290 return "PUSH("+stack
+"," + var
+ ");";
292 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
295 private String
createFromStack(String stack
, String var
){
297 return "POP("+ var
+ ", "+stack
+");";
299 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
303 private String
createToEStack(int i
) {
304 return createToEStack(i
+"");
307 private String
createToEStack(String i
) {
308 String res
= createToStack("mjvm_estack", i
);
309 if (genPrintEStackOnChange
)
310 res
+= "PRINT(\"eStack\",mjvm_estack);";
314 private String
createFromEStack(String st
) {
315 String res
= createFromStack("mjvm_estack",st
);
316 if (genPrintEStackOnChange
)
317 res
+= "PRINT(\"eStack\",mjvm_estack);";
321 private String
createPopEStack() {
322 String res
= "mjvm_estack := TAIL(mjvm_estack);";
323 if (genPrintEStackOnChange
)
324 res
+= "PRINT(\"eStack\",mjvm_estack);";
328 private String
createTopTwoEStack() {
329 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
332 private String
createTopEStack() {
333 return createFromEStack("tempa");
338 private String
createToMStack(int i
) {
339 return createToMStack(i
+"");
342 private String
createToMStack(String i
) {
343 return createToStack("mjvm_mstack", i
);
346 private String
createFromMStack(String st
) {
347 return createFromStack("mjvm_mstack", st
);
350 public void convertStream(InputStream ins
) throws Exception
{
351 mjInput
.setStream(ins
);
353 mjInput
.processHeader(this);
355 prl(createStandardStart(mjInput
.getNumberOfWords(this)));
356 prl("SKIP;\n ACTIONS a" + (14 + mjInput
.getMainAdr(this)) + " :");
357 int op
= mjInput
.get();
359 prl(" a" + mjInput
.getCounter() + " ==");
360 if (originalInComments
)
361 prl(createComment(mjInput
.describeOpCode(op
), C_OC
));
362 if (genPrintForEachAddress
) {
363 prl("PRINT(\"a" + mjInput
.getCounter() + "\");");
364 if (genPauseAfterEachAddress
)
365 prl("@Read_Line_Proc(VAR debug_disposable_string, Standard_Input_Port);");
369 prl(createToEStack(createLocal(mjInput
.get())));
376 prl(createStartVar("tempa"));
377 prl("tempa :="+createLocal(op
- load_0
)+";");
378 prl(createToEStack("tempa"));
383 prl(createFromEStack(createLocal(mjInput
.get())));
390 prl(createStartVar("tempa"));
391 prl(createFromEStack("tempa"));
392 prl(createLocal(op
- store_0
)+" := tempa;");
398 prl(createToEStack(createStatic(mjInput
.get2())));
402 prl(createFromEStack(createStatic(mjInput
.get2())));
407 int f
= mjInput
.get2();
408 prl(createStartVar("tempa"));
409 prl(createTopEStack());
410 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
415 int f
= mjInput
.get2();
416 prl(createStartVar("tempa", "tempb"));
417 prl(createTopTwoEStack());
418 prl(createObject("tempb") + "[" + (f
+ 1) + "]:=tempa;");
424 prl(createToEStack(mjInput
.get4()));
429 prl(createToEStack(-1));
439 prl(createToEStack(op
- const_0
));
444 prl(createStartVar("tempa", "tempb", "tempres"));
445 prl(createTopTwoEStack());
446 prl("tempres := tempb + tempa;");
447 prl(createToEStack("tempres"));
452 prl(createStartVar("tempa", "tempb", "tempres"));
453 prl(createTopTwoEStack());
454 prl("tempres := tempb - tempa;");
455 prl(createToEStack("tempres"));
460 prl(createStartVar("tempa", "tempb", "tempres"));
461 prl(createTopTwoEStack());
462 prl("tempres := tempb * tempa;");
463 prl(createToEStack("tempres"));
468 prl(createStartVar("tempa", "tempb", "tempres"));
469 prl(createTopTwoEStack());
470 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
471 prl("tempres := tempb DIV tempa;");
472 prl(createToEStack("tempres"));
477 prl(createStartVar("tempa", "tempb", "tempres"));
478 prl(createTopTwoEStack());
479 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
480 prl("tempres := tempb MOD tempa;");
481 prl(createToEStack("tempres"));
487 prl(createStartVar("tempa"));
488 prl(createTopEStack());
489 prl(createToEStack("-tempa"));
495 prl(createStartVar("tempa", "tempb"));
496 prl(createTopTwoEStack());
497 prl("VAR <tempres :=tempb, i:=1 >:");
498 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
499 prl(createToEStack("tempres"));
505 prl(createStartVar("tempa", "tempb"));
506 prl(createTopTwoEStack());
507 prl("VAR <tempres :=tempb, i:=1 >:");
508 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
509 prl(createToEStack("tempres"));
516 int b1
= mjInput
.get(), b2
= mjInput
.get();
517 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
522 int size
= mjInput
.get2();
523 // TODO maybe objects and arrays should be in the same list?
524 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
526 prl(createToEStack("LENGTH(mjvm_objects)"));
530 mjInput
.get();// 0 - bytes, 1 - words; ignore for now
531 // TODO take into consideration 0/1
532 prl(createStartVar("tempa"));
533 prl(createTopEStack());
534 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
535 prl(createToEStack("LENGTH(mjvm_arrays)"));
542 prl(createStartVar("tempa", "tempb"));
543 prl(createTopTwoEStack());
544 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
550 prl(createStartVar("tempa", "tempb", "tempres"));
551 prl(createFromEStack("tempres"));
552 prl(createTopTwoEStack());
553 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
558 prl(createStartVar("tempa", "tempb"));
559 prl(createTopEStack());
560 prl("tempb := LENGTH("+ createArray("tempa") + ");");
561 prl(createToEStack("tempb"));
567 prl(createStartVar("tempa", "tempb"));
568 prl(createTopEStack());
569 prl(createToEStack("tempa"));
570 prl(createToEStack("tempa"));
575 prl(createStartVar("tempa", "tempb"));
576 prl(createTopTwoEStack());
577 prl(createToEStack("tempb"));
578 prl(createToEStack("tempa"));
579 prl(createToEStack("tempb"));
580 prl(createToEStack("tempa"));
586 prl(createPopEStack());
591 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
602 prl(createStartVar("tempa", "tempb"));
603 prl(createTopTwoEStack());
604 prl("IF tempb " + mjInput
.getRelationFor(op
)
605 + " tempa THEN mjvm_flag_jump := 1"
606 + " ELSE mjvm_flag_jump := 0"
609 prl("IF mjvm_flag_jump = 1 THEN CALL a"
610 + (mjInput
.getCounter() + mjInput
.get2())
611 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
614 prl(createTopTwoEStack());
615 prl("IF tempb " + mjInput
.getRelationFor(op
)
616 + " tempa THEN CALL a"
617 + (mjInput
.getCounter() + mjInput
.get2())
618 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
625 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
630 // we let the actions return
631 // there is nothing to clean up
632 prl("SKIP\n END\n b" + mjInput
.getCounter() + " ==");
636 int parameters
= mjInput
.get();
638 int locals
= mjInput
.get();
639 prl(createToMStack("mjvm_locals"));
640 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
641 for (int i
= parameters
- 1; i
>= 0; i
--)
642 prl(createFromEStack(createLocal(i
)));
646 prl(createFromMStack("mjvm_locals"));
652 // TODO maybe we'll need a bufer for multi chars!
653 prl(createStartVar("tempa"));
654 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
655 prl("tempa := @String_To_List(tempa)[1];");
656 prl(createToEStack("tempa"));
661 prl(createStartVar("tempa"));
662 prl("@Read_Line_Proc(VAR tempa, Standard_Input_Port);");
663 prl("tempa := @String_To_Num(tempa);");
664 prl(createToEStack("tempa"));
671 prl(createStartVar("tempa", "tempb"));
672 prl(createTopTwoEStack());
674 prl(createComment("print spacing and transformation",C_SPEC
));
675 prl("PRINFLUSH(@Format(tempa, @List_To_String(< tempb >)));");
677 prl("Print_MJ_CHAR(tempb,tempa);");
682 prl(createStartVar("tempa", "tempb"));
684 prl(createTopTwoEStack());
686 prl(createComment("print spacing",C_SPEC
));
687 prl("PRINFLUSH(@Format(tempa,tempb));");
690 prl("Print_MJ(tempb,tempa);");
696 prl("ERROR(\"Runtime error: trap(" + mjInput
.get() + ")\");");
701 prl(createComment("unknown op error: " + op
, C_ERR
));
702 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
706 boolean wasJump
= mjInput
.isJumpCode(op
);
712 prl("CALL a" + mjInput
.getCounter() + "\n END");
714 prl("SKIP\n END\nENDACTIONS;\n");
715 pr(createStandardEnd());
718 public void convertFile(File f
) {
720 convertStream(new FileInputStream(f
));
721 } catch (Exception ex
) {
722 ex
.printStackTrace();
726 public void printHelp() {
733 public void printLongHelp() {
736 System
.out
.println();
738 System
.out
.println();
739 printHelpDirectives();
740 System
.out
.println();
741 printHelpGenerating();
742 System
.out
.println();
746 public void printHelpOutput() {
747 System
.out
.println("Output options:");
748 System
.out
.println(" --screen print output to screen");
749 System
.out
.println(" -o --oc[+-] include original code in comments");
750 System
.out
.println(" -v verbose, print warning messages");
751 System
.out
.println(" -q quiet; don't print even the error messages");
752 System
.out
.println(" -d print detailed debug messages");
755 public void printHelpGenerating() {
756 System
.out
.println("Options for generating extra code for tracking code execution");
757 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
758 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
759 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
760 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
761 System
.out
.println(" --genAll short for applying all code generation");
764 public void printHelpDirectives(){
765 System
.out
.println("Alternatives for code generation (* are the defaults):");
766 System
.out
.print(genPopPush?
'*':' ');
767 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
768 System
.out
.print(!genPopPush?
'*':' ');
769 System
.out
.println(" --genHeadTail generate TAIL/HEAD instead of POP/PUSH ");
770 System
.out
.println();
771 System
.out
.print(genInlinePrint?
'*':' ');
772 System
.out
.println(" --genInlinePrint generate prints directly instead of procedure calls");
773 System
.out
.print(!genInlinePrint?
'*':' ');
774 System
.out
.println(" --genProcedurePrint generate prints as custom procedure calls");
775 System
.out
.println();
776 System
.out
.print(genLocalVars?
'*':' ');
777 System
.out
.println(" --genLocalVars generate local VAR block for temp variables");
778 System
.out
.print(!genLocalVars?
'*':' ');
779 System
.out
.println(" --genGlobalVars do NOT generate local VAR block for temp variables");
782 public void printHelpHelp() {
783 System
.out
.println("Help and info options");
784 System
.out
.println(" -h basic help");
785 System
.out
.println(" --help print more detailed help");
786 System
.out
.println(" --version or -version print version and exit");
789 public void printUsage(){
790 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
793 public void printVersion() {
794 System
.out
.println("MicroJava bytecode to WSL converter " + getVersion()
795 + ", by Doni Pracner");
798 public String
makeDefaultOutName(String inname
){
800 if (inname
.endsWith(".obj"))
801 rez
= rez
.substring(0, rez
.length() - 4);
805 public void run(String
[] args
) {
806 if (args
.length
== 0) {
810 while (i
< args
.length
&& args
[i
].length() > 0 && args
[i
].charAt(0) == '-') {
811 if (args
[i
].compareTo("-h") == 0) {
814 } else if (args
[i
].compareTo("--help") == 0) {
817 } else if (args
[i
].compareTo("--version") == 0
818 || args
[i
].compareTo("-version") == 0) {
821 } else if (args
[i
].compareTo("-o") == 0
822 || args
[i
].startsWith("--oc")) {
823 if (args
[i
].length() == 2)
824 originalInComments
= true;
825 else if (args
[i
].length() == 5)
826 originalInComments
= args
[i
].charAt(4) == '+';
828 originalInComments
= true;
829 } else if (args
[i
].compareTo("--screen") == 0) {
830 out
= new PrintWriter(System
.out
);
831 } else if (args
[i
].compareTo("-d") == 0) {
832 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
833 } else if (args
[i
].compareTo("-v") == 0) {
834 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
835 } else if (args
[i
].compareTo("-q") == 0) {
836 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
837 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
838 genPrintEStackOnChange
= true;
839 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
840 genPauseAfterEachAddress
= true;
841 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
842 genPrintForEachAddress
= true;
843 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
844 genPrintForEachAddress
= true;
845 genPauseAfterEachAddress
= true;
846 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
847 genPrintEStackOnChange
= true;
848 genPrintForEachAddress
= true;
849 genPauseAfterEachAddress
= true;
850 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
852 } else if (args
[i
].compareToIgnoreCase("--genInlinePrint") == 0) {
853 genInlinePrint
= true;
854 } else if (args
[i
].compareToIgnoreCase("--genHeadTail") == 0) {
856 } else if (args
[i
].compareToIgnoreCase("--genProcedurePrint") == 0) {
857 genInlinePrint
= false;
858 } else if (args
[i
].compareToIgnoreCase("--genLocalVars") == 0) {
860 } else if (args
[i
].compareToIgnoreCase("--genGlobalVars") == 0) {
861 genLocalVars
= false;
863 System
.err
.println("unknown option: "+args
[i
]);
868 if (i
>= args
.length
) {
869 System
.err
.println("no filename supplied");
873 Path p
= FileSystems
.getDefault().getPath(args
[i
]);
874 if (!Files
.isRegularFile(p
)){
875 System
.err
.println("input file does not exist");
879 if (i
+ 1 < args
.length
) {
881 out
= new PrintWriter(args
[i
+ 1]);
882 } catch (Exception e
) {
883 System
.err
.println("error in opening out file:");
888 // if not set to screen, or a file, make a default filename
890 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
891 } catch (Exception e
) {
892 System
.err
.println("error in opening out file:");
896 Calendar now
= Calendar
.getInstance();
898 convertStream(Files
.newInputStream(p
));
899 } catch (Exception e
) {
900 // TODO Auto-generated catch block
903 long mili
= Calendar
.getInstance().getTimeInMillis()
904 - now
.getTimeInMillis();
905 System
.out
.println("conversion time:" + mili
+ " ms");
906 messages
.printMessageCounters();
911 public static void main(String
[] args
) {
912 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner