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.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 /** Constant used for marking a regular comment from the original file */
58 public static final char C_REG
= ' ';
60 * Constant used for marking when original code is inserted in the file,
61 * next to the translations
63 public static final char C_OC
= '#';
64 /** Constant used for marking special messages from the translator */
65 public static final char C_SPEC
= '&';
66 /** Constant used for marking error messages from the translator */
67 public static final char C_ERR
= '!';
69 /** instruction code in MicroJava bytecode. */
70 public static final int
129 private boolean originalInComments
= false;
131 private Properties versionData
;
133 private String
getVersion() {
134 if (versionData
== null) {
135 versionData
= new Properties();
137 versionData
.load(getClass().getResourceAsStream(versionFile
));
138 } catch (IOException e
) {
142 String ver
= versionData
.getProperty("version");
149 MicroJavaInput mjInput
= new MicroJavaInput();
151 private PrintWriter out
= null;
154 private void pr(int i
){
158 private void pr(char i
){
162 private void pr(String i
){
166 private void prl(String i
){
170 public String
createStandardStart(){
171 return createStandardStart(10);
174 public String
createStandardStart(int numWords
){
175 StringBuilder ret
= new StringBuilder(
176 "C:\" This file automatically converted from microjava bytecode\";\n"
177 +"C:\" with mjc2wsl v "+getVersion()+"\";\n");
179 ret
.append("\nBEGIN");
180 ret
.append("\nVAR <\n\t");
181 ret
.append("mjvm_locals := ARRAY(1,0),");
182 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
183 ret
.append("\n\tmjvm_arrays := < >,");
184 ret
.append("\n\tmjvm_flag_jump := 0,");
185 ret
.append("\n\tmjvm_objects := < >,");
186 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
188 return ret
.toString();
191 public String
createAsciiString(){
192 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
193 ret
.append("\nascii := \"????????????????????????????????\"++\n");
194 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
196 return ret
.toString();
199 public String
createStandardEnd(){
200 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
201 ret
.append("\nWHERE\n");
203 ret
.append("\nFUNCT CHR(num) ==:\n");
204 ret
.append("\t@List_To_String(< num >)\n");
207 if (!genInlinePrint
) {
208 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
209 ret
.append(createComment("print spacing", C_SPEC
));
210 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
211 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
212 ret
.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
214 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
215 ret
.append(createComment("print spacing", C_SPEC
));
216 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
217 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
218 ret
.append("\tFI;\n\tPRINFLUSH(CHR(val))\n");
223 return ret
.toString();
226 private String
createStartVar(String
... vars
){
227 StringBuilder ret
= new StringBuilder("VAR < ");
228 ret
.append(vars
[0] + " := 0");
229 for (int i
=1; i
<vars
.length
; i
++)
230 ret
.append(", "+ vars
[i
] +" := 0");
233 return ret
.toString();
236 private String
createEndVar(){
240 private String
createLocal(int i
) {
241 // arrays start at 1 in WSL, so we need an offset
242 return "mjvm_locals[" + (i
+ 1) + "]";
245 private String
createStatic(int i
) {
246 return "mjvm_statics[" + (i
+ 1) + "]";
249 private String
createArray(int i
) {
250 return "mjvm_arrays[" + i
+ "]";
253 private String
createArray(String i
) {
254 return "mjvm_arrays[" + i
+ "]";
257 private String
createObject(String i
) {
258 return "mjvm_objects[" + i
+ "]";
262 * Creates a WSL comment with care to quote chars.
264 public static String
createComment(String str
){
265 return createComment(str
, C_REG
);
269 * Creates a WSL comment with care to quote chars, of the
270 * given type. Types are given as char constants. They can be
271 * default comments, comments that contain the original code
272 * in them, or additional comments regarding the translation
275 public static String
createComment(String str
, char type
) {
276 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
279 // generalised stack operations
281 private String
createToStack(String stack
, String var
){
283 return "PUSH("+stack
+"," + var
+ ");";
285 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
288 private String
createFromStack(String stack
, String var
){
290 return "POP("+ var
+ ", "+stack
+");";
292 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
296 private String
createToEStack(int i
) {
297 return createToEStack(i
+"");
300 private String
createToEStack(String i
) {
301 String res
= createToStack("mjvm_estack", i
);
302 if (genPrintEStackOnChange
)
303 res
+= "PRINT(\"eStack\",mjvm_estack);";
307 private String
createFromEStack(String st
) {
308 String res
= createFromStack("mjvm_estack",st
);
309 if (genPrintEStackOnChange
)
310 res
+= "PRINT(\"eStack\",mjvm_estack);";
314 private String
createPopEStack() {
315 String res
= "mjvm_estack := TAIL(mjvm_estack);";
316 if (genPrintEStackOnChange
)
317 res
+= "PRINT(\"eStack\",mjvm_estack);";
321 private String
createTopTwoEStack() {
322 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
325 private String
createTopEStack() {
326 return createFromEStack("tempa");
331 private String
createToMStack(int i
) {
332 return createToMStack(i
+"");
335 private String
createToMStack(String i
) {
336 return createToStack("mjvm_mstack", i
);
339 private String
createFromMStack(String st
) {
340 return createFromStack("mjvm_mstack", st
);
343 public void convertStream(InputStream ins
) throws Exception
{
344 mjInput
.setStream(ins
);
346 mjInput
.processHeader(this);
348 prl(createStandardStart(mjInput
.getNumberOfWords(this)));
349 prl("SKIP;\n ACTIONS a" + (14 + mjInput
.getMainAdr(this)) + " :");
350 int op
= mjInput
.get();
352 prl(" a" + mjInput
.getCounter() + " ==");
353 if (originalInComments
)
354 prl(createComment(mjInput
.describeOpCode(op
), C_OC
));
355 if (genPrintForEachAddress
) {
356 prl("PRINT(\"a" + mjInput
.getCounter() + "\");");
357 if (genPauseAfterEachAddress
)
358 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
362 prl(createToEStack(createLocal(mjInput
.get())));
369 prl(createStartVar("tempa"));
370 prl("tempa :="+createLocal(op
- load_0
)+";");
371 prl(createToEStack("tempa"));
376 prl(createFromEStack(createLocal(mjInput
.get())));
383 prl(createStartVar("tempa"));
384 prl(createFromEStack("tempa"));
385 prl(createLocal(op
- store_0
)+" := tempa;");
391 prl(createToEStack(createStatic(mjInput
.get2())));
395 prl(createFromEStack(createStatic(mjInput
.get2())));
400 int f
= mjInput
.get2();
401 prl(createStartVar("tempa"));
402 prl(createTopEStack());
403 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
408 int f
= mjInput
.get2();
409 prl(createStartVar("tempa", "tempb"));
410 prl(createTopTwoEStack());
411 prl(createObject("tempb") + "[" + (f
+ 1) + "]:=tempa;");
417 prl(createToEStack(mjInput
.get4()));
422 prl(createToEStack(-1));
432 prl(createToEStack(op
- const_0
));
437 prl(createStartVar("tempa", "tempb", "tempres"));
438 prl(createTopTwoEStack());
439 prl("tempres := tempb + tempa;");
440 prl(createToEStack("tempres"));
445 prl(createStartVar("tempa", "tempb", "tempres"));
446 prl(createTopTwoEStack());
447 prl("tempres := tempb - tempa;");
448 prl(createToEStack("tempres"));
453 prl(createStartVar("tempa", "tempb", "tempres"));
454 prl(createTopTwoEStack());
455 prl("tempres := tempb * tempa;");
456 prl(createToEStack("tempres"));
461 prl(createStartVar("tempa", "tempb", "tempres"));
462 prl(createTopTwoEStack());
463 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
464 prl("tempres := tempb DIV tempa;");
465 prl(createToEStack("tempres"));
470 prl(createStartVar("tempa", "tempb", "tempres"));
471 prl(createTopTwoEStack());
472 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
473 prl("tempres := tempb MOD tempa;");
474 prl(createToEStack("tempres"));
480 prl(createStartVar("tempa"));
481 prl(createTopEStack());
482 prl(createToEStack("-tempa"));
488 prl(createStartVar("tempa", "tempb"));
489 prl(createTopTwoEStack());
490 prl("VAR <tempres :=tempb, i:=1 >:");
491 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
492 prl(createToEStack("tempres"));
498 prl(createStartVar("tempa", "tempb"));
499 prl(createTopTwoEStack());
500 prl("VAR <tempres :=tempb, i:=1 >:");
501 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
502 prl(createToEStack("tempres"));
509 int b1
= mjInput
.get(), b2
= mjInput
.get();
510 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
515 int size
= mjInput
.get2();
516 // TODO maybe objects and arrays should be in the same list?
517 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
519 prl(createToEStack("LENGTH(mjvm_objects)"));
523 mjInput
.get();// 0 - bytes, 1 - words; ignore for now
524 // TODO take into consideration 0/1
525 prl(createStartVar("tempa"));
526 prl(createTopEStack());
527 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
528 prl(createToEStack("LENGTH(mjvm_arrays)"));
535 prl(createStartVar("tempa", "tempb"));
536 prl(createTopTwoEStack());
537 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
543 prl(createStartVar("tempa", "tempb", "tempres"));
544 prl(createFromEStack("tempres"));
545 prl(createTopTwoEStack());
546 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
551 prl(createStartVar("tempa", "tempb"));
552 prl(createTopEStack());
553 prl("tempb := LENGTH("+ createArray("tempa") + ");");
554 prl(createToEStack("tempb"));
560 prl(createStartVar("tempa", "tempb"));
561 prl(createTopEStack());
562 prl(createToEStack("tempa"));
563 prl(createToEStack("tempa"));
568 prl(createStartVar("tempa", "tempb"));
569 prl(createTopTwoEStack());
570 prl(createToEStack("tempb"));
571 prl(createToEStack("tempa"));
572 prl(createToEStack("tempb"));
573 prl(createToEStack("tempa"));
579 prl(createPopEStack());
584 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
594 prl(createStartVar("tempa", "tempb"));
595 prl(createTopTwoEStack());
596 prl("IF tempb " + mjInput
.getRelationFor(op
)
597 + " tempa THEN mjvm_flag_jump := 1"
598 + " ELSE mjvm_flag_jump := 0"
601 prl("IF mjvm_flag_jump = 1 THEN CALL a"
602 + (mjInput
.getCounter() + mjInput
.get2())
603 + " ELSE CALL a" + (mjInput
.getCounter() + 1)
610 prl("CALL a" + (mjInput
.getCounter() + mjInput
.get2()) + ";");
615 // we let the actions return
616 // there is nothing to clean up
617 prl("SKIP\n END\n b" + mjInput
.getCounter() + " ==");
621 int parameters
= mjInput
.get();
623 int locals
= mjInput
.get();
624 prl(createToMStack("mjvm_locals"));
625 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
626 for (int i
= parameters
- 1; i
>= 0; i
--)
627 prl(createFromEStack(createLocal(i
)));
631 prl(createFromMStack("mjvm_locals"));
637 // TODO make it a char for read
638 messages
.message("char is read like a number", TransMessages
.M_WAR
);
639 prl(createComment("char is read like a number", C_SPEC
));
642 prl(createStartVar("tempa"));
643 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
644 prl(createToEStack("tempa"));
651 prl(createStartVar("tempa", "tempb"));
652 prl(createTopTwoEStack());
654 prl(createComment("print spacing and transformation",C_SPEC
));
655 prl("PRINFLUSH(SUBSTR(\" \", 0, MIN(10, MAX(0,tempa-1))), @List_To_String(< tempb >));");
657 prl("Print_MJ_CHAR(tempb,tempa);");
662 // TODO printing numbers needs different lengths of spacing
663 prl(createStartVar("tempa", "tempb"));
665 prl(createTopTwoEStack());
667 prl(createComment("print spacing",C_SPEC
));
668 prl("PRINFLUSH(SUBSTR(\" \", 0, MIN(10, MAX(0, tempa-SLENGTH(@String(tempb))))), tempb);");
671 prl("Print_MJ(tempb,tempa);");
677 prl("ERROR(\"Runtime error: trap(" + mjInput
.get() + ")\");");
682 prl(createComment("unknown op error: " + op
, C_ERR
));
683 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
687 boolean wasJump
= mjInput
.isJumpCode(op
);
693 prl("CALL a" + mjInput
.getCounter() + "\n END");
695 prl("SKIP\n END\nENDACTIONS;\n");
696 pr(createStandardEnd());
699 public void convertFile(File f
) {
701 convertStream(new FileInputStream(f
));
702 } catch (Exception ex
) {
703 ex
.printStackTrace();
707 public void printHelp() {
714 public void printLongHelp() {
717 System
.out
.println();
719 System
.out
.println();
720 printHelpDirectives();
721 System
.out
.println();
722 printHelpGenerating();
723 System
.out
.println();
727 public void printHelpOutput() {
728 System
.out
.println("Output options:");
729 System
.out
.println(" --screen print output to screen");
730 System
.out
.println(" -o --oc[+-] include original code in comments");
731 System
.out
.println(" -v verbose, print warning messages");
732 System
.out
.println(" -q quiet; don't print even the error messages");
733 System
.out
.println(" -d print detailed debug messages");
736 public void printHelpGenerating() {
737 System
.out
.println("Options for generating extra code for tracking code execution");
738 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
739 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
740 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
741 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
742 System
.out
.println(" --genAll short for applying all code generation");
745 public void printHelpDirectives(){
746 System
.out
.println("Alternatives for code generation:");
747 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
748 System
.out
.println(" --genHeadTail generate TAIL/HEAD instead of POP/PUSH ");
749 System
.out
.println();
750 System
.out
.println(" --genInlinePrint generate prints directly instead of procedure calls");
751 System
.out
.println(" --genProcedurePrint generate prints as custom procedure calls");
754 public void printHelpHelp() {
755 System
.out
.println("Help and info options");
756 System
.out
.println(" -h basic help");
757 System
.out
.println(" --help print more detailed help");
758 System
.out
.println(" --version or -version print version and exit");
761 public void printUsage(){
762 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
765 public void printVersion() {
766 System
.out
.println("MicroJava bytecode to WSL converter. v " + getVersion()
767 + ", by Doni Pracner");
770 public String
makeDefaultOutName(String inname
){
772 if (inname
.endsWith(".obj"))
773 rez
= rez
.substring(0, rez
.length() - 4);
777 public void run(String
[] args
) {
778 if (args
.length
== 0) {
782 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
783 if (args
[i
].compareTo("-h") == 0) {
786 } else if (args
[i
].compareTo("--help") == 0) {
789 } else if (args
[i
].compareTo("--version") == 0
790 || args
[i
].compareTo("-version") == 0) {
793 } else if (args
[i
].compareTo("-o") == 0
794 || args
[i
].startsWith("--oc")) {
795 if (args
[i
].length() == 2)
796 originalInComments
= true;
797 else if (args
[i
].length() == 5)
798 originalInComments
= args
[i
].charAt(4) == '+';
800 originalInComments
= true;
801 } else if (args
[i
].compareTo("--screen") == 0) {
802 out
= new PrintWriter(System
.out
);
803 } else if (args
[i
].compareTo("-d") == 0) {
804 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
805 } else if (args
[i
].compareTo("-v") == 0) {
806 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
807 } else if (args
[i
].compareTo("-q") == 0) {
808 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
809 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
810 genPrintEStackOnChange
= true;
811 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
812 genPauseAfterEachAddress
= true;
813 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
814 genPrintForEachAddress
= true;
815 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
816 genPrintForEachAddress
= true;
817 genPauseAfterEachAddress
= true;
818 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
819 genPrintEStackOnChange
= true;
820 genPrintForEachAddress
= true;
821 genPauseAfterEachAddress
= true;
822 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
824 } else if (args
[i
].compareToIgnoreCase("--genInlinePrint") == 0) {
825 genInlinePrint
= true;
826 } else if (args
[i
].compareToIgnoreCase("--genHeadTail") == 0) {
828 } else if (args
[i
].compareToIgnoreCase("--genProcedurePrint") == 0) {
829 genInlinePrint
= false;
834 if (i
>= args
.length
) {
835 System
.out
.println("no filename supplied");
839 Path p
= FileSystems
.getDefault().getPath(args
[i
]);
840 if (!Files
.exists(p
)){
841 System
.out
.println("input file does not exist");
845 if (i
+ 1 < args
.length
) {
847 out
= new PrintWriter(args
[i
+ 1]);
848 } catch (Exception e
) {
849 System
.err
.println("error in opening out file:");
854 // if not set to screen, or a file, make a default filename
856 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
857 } catch (Exception e
) {
858 System
.err
.println("error in opening out file:");
862 Calendar now
= Calendar
.getInstance();
864 convertStream(Files
.newInputStream(p
));
865 } catch (Exception e
) {
866 // TODO Auto-generated catch block
869 long mili
= Calendar
.getInstance().getTimeInMillis()
870 - now
.getTimeInMillis();
871 System
.out
.println("conversion time:" + mili
+ " ms");
872 messages
.printMessageCounters();
877 public static void main(String
[] args
) {
878 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner