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.5";
33 private TransMessages messages
= new TransMessages();
35 private boolean genPauseAfterEachAddress
=false,
36 genPrintForEachAddress
= false,
37 genPrintEStackOnChange
= false;
39 /** Constant used for marking a regular comment from the original file */
40 public static final char C_REG
= ' ';
42 * Constant used for marking when original code is inserted in the file,
43 * next to the translations
45 public static final char C_OC
= '#';
46 /** Constant used for marking special messages from the translator */
47 public static final char C_SPEC
= '&';
48 /** Constant used for marking error messages from the translator */
49 public static final char C_ERR
= '!';
51 /** instruction code in MicroJava bytecode. */
52 public static final int
111 private boolean originalInComments
= false;
113 private HashMap
<Integer
,String
> opMap
= null;
115 private String opCodeFile
= "mj-bytecodes.properties";
117 private HashMap
<Integer
, String
> getOpMap() {
119 opMap
= new HashMap
<Integer
, String
>(60, 0.98f
);
121 BufferedReader in
= new BufferedReader(new InputStreamReader(
122 getClass().getResourceAsStream(opCodeFile
)));
123 String str
= in
.readLine();
124 while (str
!= null) {
125 String
[] ss
= str
.split("=");
126 opMap
.put(Integer
.parseInt(ss
[0]), ss
[1]);
130 } catch (Exception ex
) {
131 ex
.printStackTrace();
137 public String
getOpString(int op
) {
138 return getOpMap().get(op
);
141 public String
describeOpCode(int op
) {
142 return op
+ " (" + getOpString(op
) + ")";
145 private InputStream mainIn
;
146 private PrintWriter out
= null;
147 private int counter
= -1;
149 private void pr(int i
){
153 private void pr(char i
){
157 private void pr(String i
){
161 private void prl(String i
){
170 res
= res
<< 24 >>> 24;
171 } catch (IOException ex
) {
172 ex
.printStackTrace();
179 return (get() * 256 + get()) << 16 >> 16;
183 return (get2() << 16) + (get2() << 16 >>> 16);
186 public String
createStandardStart(){
187 return createStandardStart(10);
190 public String
createStandardStart(int numWords
){
191 StringBuilder ret
= new StringBuilder(
192 "C:\" This file automatically converted from microjava bytecode\";\n"
193 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
195 ret
.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
196 ret
.append("mjvm_locals := ARRAY(1,0), ");
197 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0), ");
198 ret
.append("\n\tmjvm_arrays := < >, ");
199 ret
.append("\n\tmjvm_objects := < >, ");
200 ret
.append("\n mjvm_estack := < >, mjvm_mstack := < > > : ");
202 return ret
.toString();
205 public String
createStandardEnd(){
206 return "SKIP\nENDVAR";
209 private String
createLocal(int i
) {
210 // arrays start at 1 in WSL, so we need an offset
211 return "mjvm_locals[" + (i
+ 1) + "]";
214 private String
createStatic(int i
) {
215 return "mjvm_statics[" + (i
+ 1) + "]";
218 private String
createArray(int i
) {
219 return "mjvm_arrays[" + i
+ "]";
222 private String
createArray(String i
) {
223 return "mjvm_arrays[" + i
+ "]";
226 private String
createObject(String i
) {
227 return "mjvm_objects[" + i
+ "]";
231 * Creates a WSL comment with care to quote chars.
233 public static String
createComment(String str
){
234 return createComment(str
, C_REG
);
238 * Creates a WSL comment with care to quote chars, of the
239 * given type. Types are given as char constants. They can be
240 * default comments, comments that contain the original code
241 * in them, or additional comments regarding the translation
244 public static String
createComment(String str
, char type
) {
245 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
250 private String
createToEStack(int i
) {
251 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
252 if (genPrintEStackOnChange
)
253 res
+= "PRINT(\"eStack\",mjvm_estack);";
257 private String
createToEStack(String i
) {
258 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
259 if (genPrintEStackOnChange
)
260 res
+= "PRINT(\"eStack\",mjvm_estack);";
264 private String
createFromEStack(String st
) {
266 + " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
267 if (genPrintEStackOnChange
)
268 res
+= "PRINT(\"eStack\",mjvm_estack);";
272 private String
createPopEStack() {
273 String res
= "mjvm_estack := TAIL(mjvm_estack);";
274 if (genPrintEStackOnChange
)
275 res
+= "PRINT(\"eStack\",mjvm_estack);";
279 private String
createTopTwoEStack() {
280 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
283 private String
createTopEStack() {
284 return createFromEStack("tempa");
289 private String
createToMStack(int i
) {
290 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
293 private String
createToMStack(String i
) {
294 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
297 private String
createFromMStack(String st
) {
298 return st
+ " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
301 private String
getRelationFor(int opcode
) throws Exception
{
303 case jeq
: return "=";
304 case jne
: return "<>";
305 case jlt
: return "<";
306 case jle
: return "<=";
307 case jgt
: return ">";
308 case jge
: return ">=";
310 throw new Exception("Wrong opcode for a relation");
313 private boolean isJumpCode(int opcode
) {
314 return (opcode
>= jmp
) && (opcode
<= jge
);
317 public void convertStream(InputStream ins
) throws Exception
{
320 byte m
= (byte) get();
321 byte j
= (byte) get();
322 if (m
!='M' || j
!='J')
323 throw new Exception("Wrong start of bytecode file");
324 int codesize
= get4();
325 int numberOfWords
= get4();
326 int mainAdr
= get4();
328 prl(createStandardStart(numberOfWords
));
329 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a" + (14 + mainAdr
)
333 if (originalInComments
)
334 prl(createComment(describeOpCode(op
), C_OC
));
335 prl("a" + counter
+ " == ");
336 if (genPrintForEachAddress
) {
337 prl("PRINT(\"a" + counter
+ "\");");
338 if (genPauseAfterEachAddress
)
339 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
343 prl(createToEStack(createLocal(get())));
350 prl(createToEStack(createLocal(op
- load_0
)));
354 prl(createFromEStack(createLocal(get())));
361 prl(createFromEStack(createLocal(op
- store_0
)));
366 prl(createToEStack(createStatic(get2())));
370 prl(createFromEStack(createStatic(get2())));
376 prl(createTopEStack());
377 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
382 // we need to use a temparray as a pointer, WSL
383 // otherwise tries to access it as a list of lists and fails
384 prl(createTopTwoEStack());
385 prl("VAR < tempArray := " + createObject("tempb") + " > :");
386 prl("tempArray[" + (f
+ 1) + "]:=tempa ENDVAR;");
391 prl(createToEStack(get4()));
401 prl(createToEStack(op
- const_0
));
406 prl(createTopTwoEStack());
407 prl("tempres := tempb + tempa;");
408 prl(createToEStack("tempres"));
412 prl(createTopTwoEStack());
413 prl("tempres := tempb - tempa;");
414 prl(createToEStack("tempres"));
418 prl(createTopTwoEStack());
419 prl("tempres := tempb * tempa;");
420 prl(createToEStack("tempres"));
424 prl(createTopTwoEStack());
425 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
426 prl("tempres := tempb DIV tempa;");
427 prl(createToEStack("tempres"));
431 prl(createTopTwoEStack());
432 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
433 prl("tempres := tempb MOD tempa;");
434 prl(createToEStack("tempres"));
439 prl(createTopEStack());
440 prl(createToEStack("-tempa"));
445 prl(createTopTwoEStack());
446 prl("VAR <tempres :=tempb, i:=1 >:");
447 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
448 prl(createToEStack("tempres"));
453 prl(createTopTwoEStack());
454 prl("VAR <tempres :=tempb, i:=1 >:");
455 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
456 prl(createToEStack("tempres"));
462 int b1
= get(), b2
= get();
463 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
469 // TODO maybe objects and arrays should be in the same list?
470 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
472 prl(createToEStack("LENGTH(mjvm_objects)"));
476 get();// 0 - bytes, 1 - words; ignore for now
477 // TODO take into consideration 0/1
478 prl(createTopEStack());
479 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
480 prl(createToEStack("LENGTH(mjvm_arrays)"));
486 prl(createTopTwoEStack());
487 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
492 prl(createFromEStack("tempres"));
493 prl(createTopTwoEStack());
494 // we need to use a temparray as a pointer, WSL
495 // otherwise tries to access it as a list of lists and fails
496 prl("VAR < tempArray := " + createArray("tempb") + " > :");
497 prl("tempArray[tempa+1]:=tempres ENDVAR;");
501 prl(createTopEStack());
502 prl("tempb := LENGTH("+ createArray("tempa") + ");");
503 prl(createToEStack("tempb"));
508 prl(createTopEStack());
509 prl(createToEStack("tempa"));
510 prl(createToEStack("tempa"));
514 prl(createTopTwoEStack());
515 prl(createToEStack("tempb"));
516 prl(createToEStack("tempa"));
517 prl(createToEStack("tempb"));
518 prl(createToEStack("tempa"));
523 prl(createPopEStack());
528 prl("CALL a" + (counter
+ get2()) + ";");
538 prl(createTopTwoEStack());
539 prl("IF tempb " + getRelationFor(op
) + " tempa THEN CALL a"
540 + (counter
+ get2()) + " ELSE CALL a" + (counter
+ 1)
546 prl("CALL a" + (counter
+ get2()) + ";");
551 // we let the actions return
552 // there is nothing to clean up
553 prl("SKIP END b" + counter
+ " ==");
557 int parameters
= get();
560 prl(createToMStack("mjvm_locals"));
561 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
562 for (int i
= parameters
- 1; i
>= 0; i
--)
563 prl(createFromEStack(createLocal(i
)));
567 prl(createFromMStack("mjvm_locals"));
573 // TODO make it a char for read
574 messages
.message("char is read like a number", TransMessages
.M_WAR
);
575 prl(createComment("char is read like a number", C_SPEC
));
578 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
579 prl(createToEStack("tempa"));
585 // TODO need to make it a char on print
586 messages
.message("chars will be printed as number codes", TransMessages
.M_WAR
);
587 prl(createComment("char will be printed as a number code",
591 // TODO printing numbers needs different lengths of spacing
592 prl(createTopTwoEStack());
593 pr(createComment("print spacing", C_SPEC
));
594 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
595 prl("PRINFLUSH(tempb);");
600 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
605 prl(createComment("unknown op error: " + op
, C_ERR
));
606 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
610 boolean wasJump
= isJumpCode(op
);
616 prl("CALL a" + counter
+ " END");
618 prl("\nSKIP END\nENDACTIONS;\n");
619 prl(createStandardEnd());
622 public void convertFile(File f
) {
624 convertStream(new FileInputStream(f
));
625 } catch (Exception ex
) {
626 ex
.printStackTrace();
630 public void printHelp() {
637 public void printLongHelp() {
640 System
.out
.println();
642 System
.out
.println();
643 printHelpGenerating();
644 System
.out
.println();
648 public void printHelpOutput() {
649 System
.out
.println("Output options:");
650 System
.out
.println(" --screen print output to screen");
651 System
.out
.println(" -o --oc[+-] include original code in comments");
652 System
.out
.println(" -v verbose, print warning messages");
653 System
.out
.println(" -q quiet; don't print even the error messages");
654 System
.out
.println(" -d print detailed debug messages");
657 public void printHelpGenerating() {
658 System
.out
.println("Options for generating extra code for tracking code execution");
659 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
660 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
661 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
662 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
663 System
.out
.println(" --genAll short for applying all code generation");
666 public void printHelpHelp() {
667 System
.out
.println("Help and info options");
668 System
.out
.println(" -h basic help");
669 System
.out
.println(" --help print more detailed help");
670 System
.out
.println(" --version or -version print version and exit");
673 public void printUsage(){
674 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
677 public void printVersion() {
678 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
679 + ", by Doni Pracner");
682 public String
makeDefaultOutName(String inname
){
684 if (inname
.endsWith(".obj"))
685 rez
= rez
.substring(0, rez
.length() - 4);
689 public void run(String
[] args
) {
690 if (args
.length
== 0) {
694 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
695 if (args
[i
].compareTo("-h") == 0) {
698 } else if (args
[i
].compareTo("--help") == 0) {
701 } else if (args
[i
].compareTo("--version") == 0
702 || args
[i
].compareTo("-version") == 0) {
705 } else if (args
[i
].compareTo("-o") == 0
706 || args
[i
].startsWith("--oc")) {
707 if (args
[i
].length() == 2)
708 originalInComments
= true;
709 else if (args
[i
].length() == 5)
710 originalInComments
= args
[i
].charAt(4) == '+';
712 originalInComments
= true;
713 } else if (args
[i
].compareTo("--screen") == 0) {
714 out
= new PrintWriter(System
.out
);
715 } else if (args
[i
].compareTo("-d") == 0) {
716 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
717 } else if (args
[i
].compareTo("-v") == 0) {
718 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
719 } else if (args
[i
].compareTo("-q") == 0) {
720 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
721 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
722 genPrintEStackOnChange
= true;
723 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
724 genPauseAfterEachAddress
= true;
725 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
726 genPrintForEachAddress
= true;
727 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
728 genPrintForEachAddress
= true;
729 genPauseAfterEachAddress
= true;
730 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
731 genPrintEStackOnChange
= true;
732 genPrintForEachAddress
= true;
733 genPauseAfterEachAddress
= true;
738 if (i
>= args
.length
) {
739 System
.out
.println("no filename supplied");
742 File f
= new File(args
[i
]);
744 if (i
+ 1 < args
.length
) {
746 out
= new PrintWriter(args
[i
+ 1]);
747 } catch (Exception e
) {
748 System
.err
.println("error in opening out file:");
753 // if not set to screen, or a file, make a default filename
755 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
756 } catch (Exception e
) {
757 System
.err
.println("error in opening out file:");
762 Calendar now
= Calendar
.getInstance();
764 long mili
= Calendar
.getInstance().getTimeInMillis()
765 - now
.getTimeInMillis();
766 System
.out
.println("conversion time:" + mili
+ " ms");
767 messages
.printMessageCounters();
770 System
.out
.println("file does not exist");
774 public static void main(String
[] args
) {
775 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner