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
getTopTwo(){
257 return cmdFromEStack("tempa") + "\n" + cmdFromEStack("tempb");
260 private String
getTop() {
261 return cmdFromEStack("tempa");
266 private String
cmdToMStack(int i
) {
267 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
270 private String
cmdToMStack(String i
) {
271 return "mjvm_mstack := <" + i
+ " > ++ mjvm_mstack;";
274 private String
cmdFromMStack(String st
) {
275 return st
+ " := HEAD(mjvm_mstack); mjvm_mstack := TAIL(mjvm_mstack);";
278 private String
getRelationFor(int opcode
) throws Exception
{
280 case jeq
: return "=";
281 case jne
: return "<>";
282 case jlt
: return "<";
283 case jle
: return "<=";
284 case jgt
: return ">";
285 case jge
: return ">=";
287 throw new Exception("Wrong opcode for a relation");
290 private boolean isJumpCode(int opcode
) {
291 return (opcode
>=jmp
) && (opcode
<=jge
);
294 public void convertStream(InputStream ins
) throws Exception
{
297 byte m
= (byte) get();
298 byte j
= (byte) get();
299 if (m
!='M' || j
!='J')
300 throw new Exception("Wrong start of bytecode file");
301 int codesize
= get4();
302 int numberOfWords
= get4();
303 int mainAdr
= get4();
305 prl(getStandardStart(numberOfWords
));
306 prl("SKIP;\n ACTIONS A_S_start:\n A_S_start == CALL a"+(14+mainAdr
)+" END");
309 if (originalInComments
)
310 prl(createComment(describeOpCode(op
), C_OC
));
311 prl("a" + counter
+ " == ");
312 if (genPrintForEachAddress
) {
313 prl("PRINT(\"a"+counter
+"\");");
314 if (genPauseAfterEachAddress
)
315 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
319 prl(cmdToEStack(loc(get())));
326 prl(cmdToEStack(loc(op
- load_0
)));
330 prl(cmdFromEStack(loc(get())));
337 prl(cmdFromEStack(loc(op
- store_0
)));
342 prl(cmdToEStack(genStatic(get2())));
346 prl(cmdFromEStack(genStatic(get2())));
349 //TODO getfield, putfield
352 prl(createComment("fields are not processed properly", C_ERR
));
353 message("fields are not processed properly", M_ERR
);
359 prl(cmdToEStack(get4()));
369 prl(cmdToEStack(op
- const_0
));
375 prl("tempres := tempb + tempa;");
376 prl(cmdToEStack("tempres"));
381 prl("tempres := tempb - tempa;");
382 prl(cmdToEStack("tempres"));
387 prl("tempres := tempb * tempa;");
388 prl(cmdToEStack("tempres"));
393 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
394 prl("tempres := tempb DIV tempa;");
395 prl(cmdToEStack("tempres"));
400 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
401 prl("tempres := tempb MOD tempa;");
402 prl(cmdToEStack("tempres"));
406 //TODO neg, shl, shr, inc
409 get();//needs a short, but a byte will be taken bellow as well
411 prl(createComment("memory allocation not processed properly", C_ERR
));
412 message("memory allocation not processed properly", M_ERR
);
416 //TODO aload, asstore, baload, bastore
418 //TODO pop, dup, dup2
421 prl("CALL a" + (counter
+ get2()) + ";");
432 prl("IF tempb "+ getRelationFor(op
)
433 +" tempa THEN CALL a" + (counter
+ get2())
434 +" ELSE CALL a" + (counter
+1)
440 prl("CALL a" + (counter
+ get2()) + ";");
445 prl("IF EMPTY?(mjvm_mstack) THEN CALL Z FI");
446 //else we let things return
447 prl("END b"+counter
+" ==");
451 int parameters
= get();
454 prl(cmdToMStack("mjvm_locals"));
455 prl("mjvm_locals := ARRAY("+locals
+",0);");
456 for (int i
= parameters
-1; i
>= 0; i
--)
457 prl(cmdFromEStack(loc(i
)));
461 prl(cmdFromMStack("mjvm_locals"));
467 //TODO make it a char for read
468 message("char is read like a number", M_WAR
);
469 prl(createComment("char is read like a number",C_SPEC
));
472 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
473 prl(cmdToEStack("tempa"));
479 // TODO need to make it a char on print
480 message("chars will be printed as number codes", M_WAR
);
481 prl(createComment("char will be printed as a number code",C_SPEC
));
484 // TODO printing numbers needs different lengths of spacing
486 pr(createComment("print spacing",C_SPEC
));
487 prl("IF tempa>1 THEN FOR i:=2 TO tempa STEP 1 DO PRINFLUSH(\" \") OD FI;");
488 prl("PRINFLUSH(tempb);");
493 prl("ERROR(\"Runtime error: trap("+get()+")\");");
499 prl(createComment("unknown op error: " + op
, C_ERR
));
500 message("unknown op error: "+ op
, M_ERR
);
504 boolean wasJump
= isJumpCode(op
);
510 prl("CALL a" + counter
+ " END");
512 prl("CALL Z;\nSKIP END\nENDACTIONS;\n");
513 prl(getStandardEnd());
517 public void convertFile(File f
) {
519 convertStream(new FileInputStream(f
));
520 } catch (Exception ex
) {
521 ex
.printStackTrace();
525 public void printHelp() {
526 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
527 + ", by Doni Pracner");
528 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
529 System
.out
.println("options:\n\t--screen print output to screen");
530 System
.out
.println("\t-o --oc[+-] include original code in comments");
531 System
.out
.println("\t-v verbose, print warning messages");
532 System
.out
.println("\t-q don't print even the error messages");
533 System
.out
.println("\t-d print detailed debug messages");
536 public String
makeDefaultOutName(String inname
){
538 if (inname
.endsWith(".obj"))
539 rez
= rez
.substring(0, rez
.length() - 4);
543 public void run(String
[] args
) {
544 if (args
.length
== 0) {
548 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
549 if (args
[i
].compareTo("-h") == 0) {
552 } else if (args
[i
].compareTo("-o") == 0
553 || args
[i
].startsWith("--oc")) {
554 if (args
[i
].length() == 2)
555 originalInComments
= true;
556 else if (args
[i
].length() == 5)
557 originalInComments
= args
[i
].charAt(4) == '+';
559 originalInComments
= true;
560 } else if (args
[i
].compareTo("--screen") == 0) {
561 out
= new PrintWriter(System
.out
);
562 } else if (args
[i
].compareTo("-d") == 0) {
563 printLevel
= M_DEB
;//print debug info
564 } else if (args
[i
].compareTo("-v") == 0) {
565 printLevel
= M_WAR
;//print warnings
566 } else if (args
[i
].compareTo("-q") == 0) {
567 printLevel
= M_ERR
+1;//no printing
568 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
569 genPrintEStackOnChange
= true;
570 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
571 genPauseAfterEachAddress
= true;
572 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
573 genPrintForEachAddress
= true;
574 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
575 genPrintForEachAddress
= true;
576 genPauseAfterEachAddress
= true;
577 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
578 genPrintEStackOnChange
= true;
579 genPrintForEachAddress
= true;
580 genPauseAfterEachAddress
= true;
584 if (i
>= args
.length
) {
585 System
.out
.println("no filename supplied");
588 File f
= new File(args
[i
]);
590 if (i
+ 1 < args
.length
) {
592 out
= new PrintWriter(args
[i
+ 1]);
593 } catch (Exception e
) {
594 System
.err
.println("error in opening out file:");
599 // if not set to screen, or a file, make a default filename
601 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
602 } catch (Exception e
) {
603 System
.err
.println("error in opening out file:");
608 Calendar now
= Calendar
.getInstance();
610 long mili
= Calendar
.getInstance().getTimeInMillis()
611 - now
.getTimeInMillis();
612 System
.out
.println("conversion time:" + mili
+ " ms");
613 printMessageCounters();
616 System
.out
.println("file does not exist");
620 public static void main(String
[] args
) {
621 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner