gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
5 * This program converts file from compiled MicroJava bytecode to WSL language
6 * which is a part of the FermaT Transformation system. MicroJava is a subset
7 * used in Compiler Construction courses by Hanspeter Moessenboeck, not
10 * @author Doni Pracner, http://perun.dmi.rs/pracner http://quemaster.com
13 public static String versionN
= "0.1.4";
15 public static final int M_ERR
= 2, M_WAR
= 1, M_DEB
= 0;
17 private int printLevel
= M_ERR
;
19 private int[] messageCounters
= new int[M_ERR
+1];
21 private void message(String mes
, int level
){
22 if (level
>=printLevel
)
23 System
.out
.println(mes
);
24 messageCounters
[level
]++;
27 private void printMessageCounters(){
28 printMessageCounters(System
.out
);
31 private void printMessageCounters(PrintStream out
){
32 out
.println("total errors:"+messageCounters
[M_ERR
]+" warnings:"+messageCounters
[M_WAR
]);
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 public String
getStandardStart(){
112 return getStandardStart(10);
115 public String
getStandardStart(int numWords
){
116 StringBuilder ret
= new StringBuilder(
117 "C:\" This file automatically converted from microjava bytecode\";\n"
118 +"C:\" with mjc2wsl v "+versionN
+"\";\n");
120 ret
.append("VAR < tempa := 0, tempb := 0, tempres :=0,\n\t");
121 ret
.append("mjvm_locals := ARRAY(1,0), ");
122 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0), ");
123 ret
.append("\n mjvm_estack := < >, mjvm_mstack := < >, ");
124 ret
.append("\n mjvm_fp := 0, mjvm_sp := 0,");
125 ret
.append("\n t_e_m_p := 0 > :");
127 return ret
.toString();
130 public String
getStandardEnd(){
131 return "SKIP\nENDVAR";
134 private boolean originalInComments
= false;
136 private HashMap
<Integer
,String
> opMap
= null;
138 private String opCodeFile
= "mj-bytecodes.properties";
140 private HashMap
<Integer
,String
> getOpMap() {
142 opMap
= new HashMap
<Integer
, String
> (60, 0.98f
);
144 BufferedReader in
= new BufferedReader(
145 new InputStreamReader(getClass().getResourceAsStream(opCodeFile
)));
146 String str
= in
.readLine();
147 while (str
!= null) {
148 String
[] ss
= str
.split("=");
149 opMap
.put(Integer
.parseInt(ss
[0]),ss
[1]);
153 }catch (Exception ex
) {
154 ex
.printStackTrace();
160 public String
getOpString(int op
) {
161 return getOpMap().get(op
);
164 public String
describeOpCode(int op
) {
165 return op
+ " (" + getOpString(op
) + ")";
168 private InputStream mainIn
;
169 private PrintWriter out
= null;
170 private int counter
= -1;
172 private void pr(int i
){
176 private void pr(char i
){
180 private void pr(String i
){
184 private void prl(String i
){
193 res
= res
<< 24 >>> 24;
194 } catch (IOException ex
) {
195 ex
.printStackTrace();
202 return (get() * 256 + get()) << 16 >> 16;
206 return (get2() << 16) + (get2() << 16 >>> 16);
209 private String
loc(int i
){
210 //arrays start at 1 in WSL, so we need an offset
211 return "mjvm_locals[" + (i
+1)+"]";
214 private String
genStatic(int i
){
215 return "mjvm_statics[" + (i
+1)+"]";
219 * Creates a WSL comment with care to quote chars.
221 public static String
createComment(String str
){
222 return createComment(str
, C_REG
);
226 * Creates a WSL comment with care to quote chars, of the
227 * given type. Types are given as char constants. They can be
228 * default comments, comments that contain the original code
229 * in them, or additional comments regarding the translation
232 public static String
createComment(String str
, char type
) {
233 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
238 private String
cmdToEStack(int i
) {
239 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
240 if (genPrintEStackOnChange
) res
+="PRINT(\"eStack\",mjvm_estack);";
244 private String
cmdToEStack(String i
) {
245 String res
= "mjvm_estack := <" + i
+ " > ++ mjvm_estack;";
246 if (genPrintEStackOnChange
) res
+="PRINT(\"eStack\",mjvm_estack);";
250 private String
cmdFromEStack(String st
) {
251 String res
= st
+ " := HEAD(mjvm_estack); mjvm_estack := TAIL(mjvm_estack);";
252 if (genPrintEStackOnChange
) res
+="PRINT(\"eStack\",mjvm_estack);";
256 private String
cmdPopEStack() {
257 String res
= "mjvm_estack := TAIL(mjvm_estack);";
258 if (genPrintEStackOnChange
) res
+="PRINT(\"eStack\",mjvm_estack);";
263 private String
getTopTwo(){
264 return cmdFromEStack("tempa") + "\n" + cmdFromEStack("tempb");
267 private String
getTop() {
268 return cmdFromEStack("tempa");
273 private String
cmdToMStack(int i
) {
274 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
277 private String
cmdToMStack(String i
) {
278 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
281 private String
cmdFromMStack(String st
) {
282 return st
+ " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
285 private String
getRelationFor(int opcode
) throws Exception
{
287 case jeq
: return "=";
288 case jne
: return "<>";
289 case jlt
: return "<";
290 case jle
: return "<=";
291 case jgt
: return ">";
292 case jge
: return ">=";
294 throw new Exception("Wrong opcode for a relation");
297 private boolean isJumpCode(int opcode
) {
298 return (opcode
>=jmp
) && (opcode
<=jge
);
301 public void convertStream(InputStream ins
) throws Exception
{
304 byte m
= (byte) get();
305 byte j
= (byte) get();
306 if (m
!='M' || j
!='J')
307 throw new Exception("Wrong start of bytecode file");
308 int codesize
= get4();
309 int numberOfWords
= get4();
310 int mainAdr
= get4();
312 prl(getStandardStart(numberOfWords
));
313 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a"+(14+mainAdr
)+" END");
316 if (originalInComments
)
317 prl(createComment(describeOpCode(op
), C_OC
));
318 prl("a" + counter
+ " == ");
319 if (genPrintForEachAddress
) {
320 prl("PRINT(\"a"+counter
+"\");");
321 if (genPauseAfterEachAddress
)
322 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
326 prl(cmdToEStack(loc(get())));
333 prl(cmdToEStack(loc(op
- load_0
)));
337 prl(cmdFromEStack(loc(get())));
344 prl(cmdFromEStack(loc(op
- store_0
)));
349 prl(cmdToEStack(genStatic(get2())));
353 prl(cmdFromEStack(genStatic(get2())));
356 //TODO getfield, putfield
359 prl(createComment("fields are not processed properly", C_ERR
));
360 message("fields are not processed properly", M_ERR
);
366 prl(cmdToEStack(get4()));
376 prl(cmdToEStack(op
- const_0
));
382 prl("tempres := tempb + tempa;");
383 prl(cmdToEStack("tempres"));
388 prl("tempres := tempb - tempa;");
389 prl(cmdToEStack("tempres"));
394 prl("tempres := tempb * tempa;");
395 prl(cmdToEStack("tempres"));
400 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
401 prl("tempres := tempb DIV tempa;");
402 prl(cmdToEStack("tempres"));
407 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
408 prl("tempres := tempb MOD tempa;");
409 prl(cmdToEStack("tempres"));
415 prl(cmdToEStack("-tempa"));
421 int b1
= get(), b2
= get();
422 prl(loc(b1
)+" := " +loc(b1
)+" + "+b2
);
427 get();//needs a short, but a byte will be taken bellow as well
429 prl(createComment("memory allocation not processed properly", C_ERR
));
430 message("memory allocation not processed properly", M_ERR
);
434 //TODO aload, asstore, baload, bastore
444 prl("CALL a" + (counter
+ get2()) + ";");
455 prl("IF tempb "+ getRelationFor(op
)
456 +" tempa THEN CALL a" + (counter
+ get2())
457 +" ELSE CALL a" + (counter
+1)
463 prl("CALL a" + (counter
+ get2()) + ";");
468 prl("IF EMPTY?(mjvm_mstack) THEN CALL Z FI");
469 //else we let things return
470 prl("END b"+counter
+" ==");
474 int parameters
= get();
477 prl(cmdToMStack("mjvm_locals"));
478 prl("mjvm_locals := ARRAY("+locals
+",0);");
479 for (int i
= parameters
-1; i
>= 0; i
--)
480 prl(cmdFromEStack(loc(i
)));
484 prl(cmdFromMStack("mjvm_locals"));
490 //TODO make it a char for read
491 message("char is read like a number", M_WAR
);
492 prl(createComment("char is read like a number",C_SPEC
));
495 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
496 prl(cmdToEStack("tempa"));
502 // TODO need to make it a char on print
503 message("chars will be printed as number codes", M_WAR
);
504 prl(createComment("char will be printed as a number code",C_SPEC
));
507 // TODO printing numbers needs different lengths of spacing
509 pr(createComment("print spacing",C_SPEC
));
510 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
511 prl("PRINFLUSH(tempb);");
516 prl("ERROR(\"Runtime error: trap("+get()+")\");");
522 prl(createComment("unknown op error: " + op
, C_ERR
));
523 message("unknown op error: "+ op
, M_ERR
);
527 boolean wasJump
= isJumpCode(op
);
533 prl("CALL a" + counter
+ " END");
535 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
536 prl(getStandardEnd());
540 public void convertFile(File f
) {
542 convertStream(new FileInputStream(f
));
543 } catch (Exception ex
) {
544 ex
.printStackTrace();
548 public void printHelp() {
549 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
550 + ", by Doni Pracner");
551 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
552 System
.out
.println("options:\n\t--screen print output to screen");
553 System
.out
.println("\t-o --oc[+-] include original code in comments");
554 System
.out
.println("\t-v verbose, print warning messages");
555 System
.out
.println("\t-q don't print even the error messages");
556 System
.out
.println("\t-d print detailed debug messages");
559 public String
makeDefaultOutName(String inname
){
561 if (inname
.endsWith(".obj"))
562 rez
= rez
.substring(0, rez
.length() - 4);
566 public void run(String
[] args
) {
567 if (args
.length
== 0) {
571 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
572 if (args
[i
].compareTo("-h") == 0) {
575 } else if (args
[i
].compareTo("-o") == 0
576 || args
[i
].startsWith("--oc")) {
577 if (args
[i
].length() == 2)
578 originalInComments
= true;
579 else if (args
[i
].length() == 5)
580 originalInComments
= args
[i
].charAt(4) == '+';
582 originalInComments
= true;
583 } else if (args
[i
].compareTo("--screen") == 0) {
584 out
= new PrintWriter(System
.out
);
585 } else if (args
[i
].compareTo("-d") == 0) {
586 printLevel
= M_DEB
;//print debug info
587 } else if (args
[i
].compareTo("-v") == 0) {
588 printLevel
= M_WAR
;//print warnings
589 } else if (args
[i
].compareTo("-q") == 0) {
590 printLevel
= M_ERR
+1;//no printing
591 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
592 genPrintEStackOnChange
= true;
593 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
594 genPauseAfterEachAddress
= true;
595 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
596 genPrintForEachAddress
= true;
597 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
598 genPrintForEachAddress
= true;
599 genPauseAfterEachAddress
= true;
600 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
601 genPrintEStackOnChange
= true;
602 genPrintForEachAddress
= true;
603 genPauseAfterEachAddress
= true;
607 if (i
>= args
.length
) {
608 System
.out
.println("no filename supplied");
611 File f
= new File(args
[i
]);
613 if (i
+ 1 < args
.length
) {
615 out
= new PrintWriter(args
[i
+ 1]);
616 } catch (Exception e
) {
617 System
.err
.println("error in opening out file:");
622 // if not set to screen, or a file, make a default filename
624 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
625 } catch (Exception e
) {
626 System
.err
.println("error in opening out file:");
631 Calendar now
= Calendar
.getInstance();
633 long mili
= Calendar
.getInstance().getTimeInMillis()
634 - now
.getTimeInMillis();
635 System
.out
.println("conversion time:" + mili
+ " ms");
636 printMessageCounters();
639 System
.out
.println("file does not exist");
643 public static void main(String
[] args
) {
644 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner