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 /** Constant used for marking a regular comment from the original file */
42 public static final char C_REG
= ' ';
44 * Constant used for marking when original code is inserted in the file,
45 * next to the translations
47 public static final char C_OC
= '#';
48 /** Constant used for marking special messages from the translator */
49 public static final char C_SPEC
= '&';
50 /** Constant used for marking error messages from the translator */
51 public static final char C_ERR
= '!';
53 /** instruction code in MicroJava bytecode. */
54 public static final int
113 private boolean originalInComments
= false;
115 private HashMap
<Integer
,String
> opMap
= null;
117 private String opCodeFile
= "mj-bytecodes.properties";
119 private HashMap
<Integer
, String
> getOpMap() {
121 opMap
= new HashMap
<Integer
, String
>(60, 0.98f
);
123 BufferedReader in
= new BufferedReader(new InputStreamReader(
124 getClass().getResourceAsStream(opCodeFile
)));
125 String str
= in
.readLine();
126 while (str
!= null) {
127 String
[] ss
= str
.split("=");
128 opMap
.put(Integer
.parseInt(ss
[0]), ss
[1]);
132 } catch (Exception ex
) {
133 ex
.printStackTrace();
139 public String
getOpString(int op
) {
140 return getOpMap().get(op
);
143 public String
describeOpCode(int op
) {
144 return op
+ " (" + getOpString(op
) + ")";
147 private InputStream mainIn
;
148 private PrintWriter out
= null;
149 private int counter
= -1;
151 private void pr(int i
){
155 private void pr(char i
){
159 private void pr(String i
){
163 private void prl(String i
){
172 res
= res
<< 24 >>> 24;
173 } catch (IOException ex
) {
174 ex
.printStackTrace();
181 return (get() * 256 + get()) << 16 >> 16;
185 return (get2() << 16) + (get2() << 16 >>> 16);
188 public String
createStandardStart(){
189 return createStandardStart(10);
192 public String
createStandardStart(int numWords
){
193 StringBuilder ret
= new StringBuilder(
194 "C:\" This file automatically converted from microjava bytecode\";\n"
195 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
197 ret
.append("\nBEGIN");
198 ret
.append("\nVAR <\n\t");
199 ret
.append("mjvm_locals := ARRAY(1,0),");
200 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
201 ret
.append("\n\tmjvm_arrays := < >,");
202 ret
.append("\n\tmjvm_flag_jump := 0,");
203 ret
.append("\n\tmjvm_objects := < >,");
204 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
206 return ret
.toString();
209 public String
createAsciiString(){
210 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
211 ret
.append("\nascii := \"????????????????????????????????\"++\n");
212 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
214 return ret
.toString();
217 public String
createStandardEnd(){
218 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
219 ret
.append("\nWHERE\n");
221 ret
.append("\nFUNCT CHR(num) ==:\n");
222 ret
.append("\t@List_To_String(< num >)\n");
225 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
226 ret
.append(createComment("print spacing", C_SPEC
));
227 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
228 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
229 ret
.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
231 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
232 ret
.append(createComment("print spacing", C_SPEC
));
233 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
234 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
235 ret
.append("\tFI;\n\tPRINFLUSH(CHR(val))\n");
239 return ret
.toString();
242 private String
createStartVar(String
... vars
){
243 StringBuilder ret
= new StringBuilder("VAR < ");
244 ret
.append(vars
[0] + " := 0");
245 for (int i
=1; i
<vars
.length
; i
++)
246 ret
.append(", "+ vars
[i
] +" := 0");
249 return ret
.toString();
252 private String
createEndVar(){
256 private String
createLocal(int i
) {
257 // arrays start at 1 in WSL, so we need an offset
258 return "mjvm_locals[" + (i
+ 1) + "]";
261 private String
createStatic(int i
) {
262 return "mjvm_statics[" + (i
+ 1) + "]";
265 private String
createArray(int i
) {
266 return "mjvm_arrays[" + i
+ "]";
269 private String
createArray(String i
) {
270 return "mjvm_arrays[" + i
+ "]";
273 private String
createObject(String i
) {
274 return "mjvm_objects[" + i
+ "]";
278 * Creates a WSL comment with care to quote chars.
280 public static String
createComment(String str
){
281 return createComment(str
, C_REG
);
285 * Creates a WSL comment with care to quote chars, of the
286 * given type. Types are given as char constants. They can be
287 * default comments, comments that contain the original code
288 * in them, or additional comments regarding the translation
291 public static String
createComment(String str
, char type
) {
292 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
295 // generalised stack operations
297 private String
createToStack(String stack
, String var
){
299 return "PUSH("+stack
+"," + var
+ ");";
301 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
304 private String
createFromStack(String stack
, String var
){
306 return "POP("+ var
+ ", "+stack
+");";
308 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
312 private String
createToEStack(int i
) {
313 return createToEStack(i
+"");
316 private String
createToEStack(String i
) {
317 String res
= createToStack("mjvm_estack", i
);
318 if (genPrintEStackOnChange
)
319 res
+= "PRINT(\"eStack\",mjvm_estack);";
323 private String
createFromEStack(String st
) {
324 String res
= createFromStack("mjvm_estack",st
);
325 if (genPrintEStackOnChange
)
326 res
+= "PRINT(\"eStack\",mjvm_estack);";
330 private String
createPopEStack() {
331 String res
= "mjvm_estack := TAIL(mjvm_estack);";
332 if (genPrintEStackOnChange
)
333 res
+= "PRINT(\"eStack\",mjvm_estack);";
337 private String
createTopTwoEStack() {
338 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
341 private String
createTopEStack() {
342 return createFromEStack("tempa");
347 private String
createToMStack(int i
) {
348 return createToMStack(i
+"");
351 private String
createToMStack(String i
) {
352 return createToStack("mjvm_mstack", i
);
355 private String
createFromMStack(String st
) {
356 return createFromStack("mjvm_mstack", st
);
359 private String
getRelationFor(int opcode
) throws Exception
{
361 case jeq
: return "=";
362 case jne
: return "<>";
363 case jlt
: return "<";
364 case jle
: return "<=";
365 case jgt
: return ">";
366 case jge
: return ">=";
368 throw new Exception("Wrong opcode for a relation");
371 private boolean isJumpCode(int opcode
) {
372 return (opcode
>= jmp
) && (opcode
<= jge
);
375 public void convertStream(InputStream ins
) throws Exception
{
378 byte m
= (byte) get();
379 byte j
= (byte) get();
380 if (m
!='M' || j
!='J')
381 throw new Exception("Wrong start of bytecode file");
382 int codesize
= get4();
383 int numberOfWords
= get4();
384 int mainAdr
= get4();
386 prl(createStandardStart(numberOfWords
));
387 prl("SKIP;\n ACTIONS a" + (14 + mainAdr
) + " :");
390 prl(" a" + counter
+ " ==");
391 if (originalInComments
)
392 prl(createComment(describeOpCode(op
), C_OC
));
393 if (genPrintForEachAddress
) {
394 prl("PRINT(\"a" + counter
+ "\");");
395 if (genPauseAfterEachAddress
)
396 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
400 prl(createToEStack(createLocal(get())));
407 prl(createStartVar("tempa"));
408 prl("tempa :="+createLocal(op
- load_0
)+";");
409 prl(createToEStack("tempa"));
414 prl(createFromEStack(createLocal(get())));
421 prl(createStartVar("tempa"));
422 prl(createFromEStack("tempa"));
423 prl(createLocal(op
- store_0
)+" := tempa;");
429 prl(createToEStack(createStatic(get2())));
433 prl(createFromEStack(createStatic(get2())));
439 prl(createTopEStack());
440 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
445 // we need to use a temparray as a pointer, WSL
446 // otherwise tries to access it as a list of lists and fails
447 prl(createTopTwoEStack());
448 prl("VAR < tempArray := " + createObject("tempb") + " > :");
449 prl("tempArray[" + (f
+ 1) + "]:=tempa ENDVAR;");
454 prl(createToEStack(get4()));
464 prl(createToEStack(op
- const_0
));
469 prl(createStartVar("tempa", "tempb", "tempres"));
470 prl(createTopTwoEStack());
471 prl("tempres := tempb + tempa;");
472 prl(createToEStack("tempres"));
477 prl(createStartVar("tempa", "tempb", "tempres"));
478 prl(createTopTwoEStack());
479 prl("tempres := tempb - tempa;");
480 prl(createToEStack("tempres"));
485 prl(createStartVar("tempa", "tempb", "tempres"));
486 prl(createTopTwoEStack());
487 prl("tempres := tempb * tempa;");
488 prl(createToEStack("tempres"));
493 prl(createStartVar("tempa", "tempb", "tempres"));
494 prl(createTopTwoEStack());
495 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
496 prl("tempres := tempb DIV tempa;");
497 prl(createToEStack("tempres"));
502 prl(createStartVar("tempa", "tempb", "tempres"));
503 prl(createTopTwoEStack());
504 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
505 prl("tempres := tempb MOD tempa;");
506 prl(createToEStack("tempres"));
512 prl(createStartVar("tempa"));
513 prl(createTopEStack());
514 prl(createToEStack("-tempa"));
520 prl(createStartVar("tempa", "tempb"));
521 prl(createTopTwoEStack());
522 prl("VAR <tempres :=tempb, i:=1 >:");
523 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
524 prl(createToEStack("tempres"));
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 DIV 2 OD;");
534 prl(createToEStack("tempres"));
541 int b1
= get(), b2
= get();
542 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
548 // TODO maybe objects and arrays should be in the same list?
549 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
551 prl(createToEStack("LENGTH(mjvm_objects)"));
555 get();// 0 - bytes, 1 - words; ignore for now
556 // TODO take into consideration 0/1
557 prl(createStartVar("tempa"));
558 prl(createTopEStack());
559 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
560 prl(createToEStack("LENGTH(mjvm_arrays)"));
567 prl(createStartVar("tempa", "tempb"));
568 prl(createTopTwoEStack());
569 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
575 prl(createStartVar("tempa", "tempb", "tempres"));
576 prl(createFromEStack("tempres"));
577 prl(createTopTwoEStack());
578 prl("mjvm_arrays[tempb][tempa+1]:=tempres;");
583 prl(createStartVar("tempa", "tempb"));
584 prl(createTopEStack());
585 prl("tempb := LENGTH("+ createArray("tempa") + ");");
586 prl(createToEStack("tempb"));
592 prl(createStartVar("tempa", "tempb"));
593 prl(createTopEStack());
594 prl(createToEStack("tempa"));
595 prl(createToEStack("tempa"));
600 prl(createStartVar("tempa", "tempb"));
601 prl(createTopTwoEStack());
602 prl(createToEStack("tempb"));
603 prl(createToEStack("tempa"));
604 prl(createToEStack("tempb"));
605 prl(createToEStack("tempa"));
611 prl(createPopEStack());
616 prl("CALL a" + (counter
+ get2()) + ";");
626 prl(createStartVar("tempa", "tempb"));
627 prl(createTopTwoEStack());
628 prl("IF tempb " + getRelationFor(op
)
629 + " tempa THEN mjvm_flag_jump := 1"
630 + " ELSE mjvm_flag_jump := 0"
633 prl("IF mjvm_flag_jump = 1 THEN CALL a"
635 + " ELSE CALL a" + (counter
+ 1)
642 prl("CALL a" + (counter
+ get2()) + ";");
647 // we let the actions return
648 // there is nothing to clean up
649 prl("SKIP\n END\n b" + counter
+ " ==");
653 int parameters
= get();
656 prl(createToMStack("mjvm_locals"));
657 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
658 for (int i
= parameters
- 1; i
>= 0; i
--)
659 prl(createFromEStack(createLocal(i
)));
663 prl(createFromMStack("mjvm_locals"));
669 // TODO make it a char for read
670 messages
.message("char is read like a number", TransMessages
.M_WAR
);
671 prl(createComment("char is read like a number", C_SPEC
));
674 prl(createStartVar("tempa"));
675 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
676 prl(createToEStack("tempa"));
683 prl(createStartVar("tempa", "tempb"));
684 prl(createTopTwoEStack());
685 prl("Print_MJ_CHAR(tempb,tempa);");
690 // TODO printing numbers needs different lengths of spacing
691 prl(createStartVar("tempa", "tempb"));
693 prl(createTopTwoEStack());
694 prl("Print_MJ(tempb,tempa);");
700 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
705 prl(createComment("unknown op error: " + op
, C_ERR
));
706 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
710 boolean wasJump
= isJumpCode(op
);
716 prl("CALL a" + counter
+ "\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:");
770 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
773 public void printHelpHelp() {
774 System
.out
.println("Help and info options");
775 System
.out
.println(" -h basic help");
776 System
.out
.println(" --help print more detailed help");
777 System
.out
.println(" --version or -version print version and exit");
780 public void printUsage(){
781 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
784 public void printVersion() {
785 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
786 + ", by Doni Pracner");
789 public String
makeDefaultOutName(String inname
){
791 if (inname
.endsWith(".obj"))
792 rez
= rez
.substring(0, rez
.length() - 4);
796 public void run(String
[] args
) {
797 if (args
.length
== 0) {
801 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
802 if (args
[i
].compareTo("-h") == 0) {
805 } else if (args
[i
].compareTo("--help") == 0) {
808 } else if (args
[i
].compareTo("--version") == 0
809 || args
[i
].compareTo("-version") == 0) {
812 } else if (args
[i
].compareTo("-o") == 0
813 || args
[i
].startsWith("--oc")) {
814 if (args
[i
].length() == 2)
815 originalInComments
= true;
816 else if (args
[i
].length() == 5)
817 originalInComments
= args
[i
].charAt(4) == '+';
819 originalInComments
= true;
820 } else if (args
[i
].compareTo("--screen") == 0) {
821 out
= new PrintWriter(System
.out
);
822 } else if (args
[i
].compareTo("-d") == 0) {
823 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
824 } else if (args
[i
].compareTo("-v") == 0) {
825 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
826 } else if (args
[i
].compareTo("-q") == 0) {
827 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
828 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
829 genPrintEStackOnChange
= true;
830 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
831 genPauseAfterEachAddress
= true;
832 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
833 genPrintForEachAddress
= true;
834 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
835 genPrintForEachAddress
= true;
836 genPauseAfterEachAddress
= true;
837 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
838 genPrintEStackOnChange
= true;
839 genPrintForEachAddress
= true;
840 genPauseAfterEachAddress
= true;
841 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
847 if (i
>= args
.length
) {
848 System
.out
.println("no filename supplied");
851 File f
= new File(args
[i
]);
853 if (i
+ 1 < args
.length
) {
855 out
= new PrintWriter(args
[i
+ 1]);
856 } catch (Exception e
) {
857 System
.err
.println("error in opening out file:");
862 // if not set to screen, or a file, make a default filename
864 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
865 } catch (Exception e
) {
866 System
.err
.println("error in opening out file:");
871 Calendar now
= Calendar
.getInstance();
873 long mili
= Calendar
.getInstance().getTimeInMillis()
874 - now
.getTimeInMillis();
875 System
.out
.println("conversion time:" + mili
+ " ms");
876 messages
.printMessageCounters();
879 System
.out
.println("file does not exist");
883 public static void main(String
[] args
) {
884 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner