gitweb on Svarog
projekti pod git sistemom za održavanje verzija -- projects under
the git version control system
113bfef0c197ae7d515ee65c9ada0209f9d20486
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.6";
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\n");
197 ret
.append(createAsciiString());
199 ret
.append("\nBEGIN");
200 ret
.append("\nVAR <\n\t");
201 ret
.append("mjvm_locals := ARRAY(1,0),");
202 ret
.append("\n\tmjvm_statics := ARRAY("+numWords
+",0),");
203 ret
.append("\n\tmjvm_arrays := < >,");
204 ret
.append("\n\tmjvm_objects := < >,");
205 ret
.append("\n\tmjvm_estack := < >, mjvm_mstack := < > > :");
207 return ret
.toString();
210 public String
createAsciiString(){
211 StringBuilder ret
= new StringBuilder("C:\"char array for ascii code conversions\";");
212 ret
.append("\nascii := \"????????????????????????????????\"++\n");
213 ret
.append("\" !\"++Quote++\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n");
215 return ret
.toString();
218 public String
createStandardEnd(){
219 StringBuilder ret
= new StringBuilder("SKIP\nENDVAR\n");
220 ret
.append("\nWHERE\n");
222 ret
.append("\nFUNCT CHR(num) ==:\n");
223 ret
.append("\tSUBSTR(ascii,num,1)\n");
226 ret
.append("\nPROC Print_MJ(val, format VAR)==\n");
227 ret
.append(createComment("print spacing", C_SPEC
));
228 ret
.append("\n\tIF format>1 THEN\n\t\tFOR i:=2 TO ");
229 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
230 ret
.append("\tFI;\n\tPRINFLUSH(val)\nEND\n");
232 ret
.append("\nPROC Print_MJ_CHAR(val, format VAR)==\n");
233 ret
.append(createComment("print spacing", C_SPEC
));
234 ret
.append("\n\tIF val=10 OR val=13 THEN\n");
235 ret
.append("\t\tPRINT(\"\");\n");
236 ret
.append("\tELSE\n");
237 ret
.append("\t\tIF format>1 THEN\n\t\t\tFOR i:=2 TO ");
238 ret
.append("format STEP 1 DO PRINFLUSH(\" \") OD\n");
239 ret
.append("\t\tFI;\n\t\tPRINFLUSH(CHR(val))\n");
240 ret
.append("\tFI\n");
244 return ret
.toString();
247 private String
createStartVar(String
... vars
){
248 StringBuilder ret
= new StringBuilder("VAR < ");
249 ret
.append(vars
[0] + " := 0");
250 for (int i
=1; i
<vars
.length
; i
++)
251 ret
.append(", "+ vars
[i
] +" := 0");
254 return ret
.toString();
257 private String
createEndVar(){
261 private String
createLocal(int i
) {
262 // arrays start at 1 in WSL, so we need an offset
263 return "mjvm_locals[" + (i
+ 1) + "]";
266 private String
createStatic(int i
) {
267 return "mjvm_statics[" + (i
+ 1) + "]";
270 private String
createArray(int i
) {
271 return "mjvm_arrays[" + i
+ "]";
274 private String
createArray(String i
) {
275 return "mjvm_arrays[" + i
+ "]";
278 private String
createObject(String i
) {
279 return "mjvm_objects[" + i
+ "]";
283 * Creates a WSL comment with care to quote chars.
285 public static String
createComment(String str
){
286 return createComment(str
, C_REG
);
290 * Creates a WSL comment with care to quote chars, of the
291 * given type. Types are given as char constants. They can be
292 * default comments, comments that contain the original code
293 * in them, or additional comments regarding the translation
296 public static String
createComment(String str
, char type
) {
297 return "C:\"" + type
+ str
.replace("\"", "''") + "\";";
300 // generalised stack operations
302 private String
createToStack(String stack
, String var
){
304 return "PUSH("+stack
+"," + var
+ ");";
306 return stack
+ " := <" + var
+ " > ++ " + stack
+";";
309 private String
createFromStack(String stack
, String var
){
311 return "POP("+ var
+ ", "+stack
+");";
313 return var
+ ":= HEAD("+stack
+"); "+stack
+" := TAIL("+stack
+");";
317 private String
createToEStack(int i
) {
318 return createToEStack(i
+"");
321 private String
createToEStack(String i
) {
322 String res
= createToStack("mjvm_estack", i
);
323 if (genPrintEStackOnChange
)
324 res
+= "PRINT(\"eStack\",mjvm_estack);";
328 private String
createFromEStack(String st
) {
329 String res
= createFromStack("mjvm_estack",st
);
330 if (genPrintEStackOnChange
)
331 res
+= "PRINT(\"eStack\",mjvm_estack);";
335 private String
createPopEStack() {
336 String res
= "mjvm_estack := TAIL(mjvm_estack);";
337 if (genPrintEStackOnChange
)
338 res
+= "PRINT(\"eStack\",mjvm_estack);";
342 private String
createTopTwoEStack() {
343 return createFromEStack("tempa") + "\n" + createFromEStack("tempb");
346 private String
createTopEStack() {
347 return createFromEStack("tempa");
352 private String
createToMStack(int i
) {
353 return createToMStack(i
+"");
356 private String
createToMStack(String i
) {
357 return createToStack("mjvm_mstack", i
);
360 private String
createFromMStack(String st
) {
361 return createFromStack("mjvm_mstack", st
);
364 private String
getRelationFor(int opcode
) throws Exception
{
366 case jeq
: return "=";
367 case jne
: return "<>";
368 case jlt
: return "<";
369 case jle
: return "<=";
370 case jgt
: return ">";
371 case jge
: return ">=";
373 throw new Exception("Wrong opcode for a relation");
376 private boolean isJumpCode(int opcode
) {
377 return (opcode
>= jmp
) && (opcode
<= jge
);
380 public void convertStream(InputStream ins
) throws Exception
{
383 byte m
= (byte) get();
384 byte j
= (byte) get();
385 if (m
!='M' || j
!='J')
386 throw new Exception("Wrong start of bytecode file");
387 int codesize
= get4();
388 int numberOfWords
= get4();
389 int mainAdr
= get4();
391 prl(createStandardStart(numberOfWords
));
392 prl("SKIP;\n ACTIONS a" + (14 + mainAdr
) + " :");
395 prl(" a" + counter
+ " ==");
396 if (originalInComments
)
397 prl(createComment(describeOpCode(op
), C_OC
));
398 if (genPrintForEachAddress
) {
399 prl("PRINT(\"a" + counter
+ "\");");
400 if (genPauseAfterEachAddress
)
401 prl("debug_disposable_string := @Read_Line(Standard_Input_Port);");
405 prl(createToEStack(createLocal(get())));
412 prl(createStartVar("tempa"));
413 prl("tempa :="+createLocal(op
- load_0
)+";");
414 prl(createToEStack("tempa"));
419 prl(createFromEStack(createLocal(get())));
426 prl(createStartVar("tempa"));
427 prl(createFromEStack("tempa"));
428 prl(createLocal(op
- store_0
)+" := tempa;");
434 prl(createToEStack(createStatic(get2())));
438 prl(createFromEStack(createStatic(get2())));
444 prl(createTopEStack());
445 prl(createToEStack(createObject("tempa") + "[" + (f
+ 1) + "]"));
450 // we need to use a temparray as a pointer, WSL
451 // otherwise tries to access it as a list of lists and fails
452 prl(createTopTwoEStack());
453 prl("VAR < tempArray := " + createObject("tempb") + " > :");
454 prl("tempArray[" + (f
+ 1) + "]:=tempa ENDVAR;");
459 prl(createToEStack(get4()));
469 prl(createToEStack(op
- const_0
));
474 prl(createStartVar("tempa", "tempb", "tempres"));
475 prl(createTopTwoEStack());
476 prl("tempres := tempb + tempa;");
477 prl(createToEStack("tempres"));
482 prl(createStartVar("tempa", "tempb", "tempres"));
483 prl(createTopTwoEStack());
484 prl("tempres := tempb - tempa;");
485 prl(createToEStack("tempres"));
490 prl(createStartVar("tempa", "tempb", "tempres"));
491 prl(createTopTwoEStack());
492 prl("tempres := tempb * tempa;");
493 prl(createToEStack("tempres"));
498 prl(createStartVar("tempa", "tempb", "tempres"));
499 prl(createTopTwoEStack());
500 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
501 prl("tempres := tempb DIV tempa;");
502 prl(createToEStack("tempres"));
507 prl(createStartVar("tempa", "tempb", "tempres"));
508 prl(createTopTwoEStack());
509 prl("IF tempa = 0 THEN ERROR(\"division by zero\") FI;");
510 prl("tempres := tempb MOD tempa;");
511 prl(createToEStack("tempres"));
517 prl(createStartVar("tempa"));
518 prl(createTopEStack());
519 prl(createToEStack("-tempa"));
525 prl(createTopTwoEStack());
526 prl("VAR <tempres :=tempb, i:=1 >:");
527 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres * 2 OD;");
528 prl(createToEStack("tempres"));
533 prl(createTopTwoEStack());
534 prl("VAR <tempres :=tempb, i:=1 >:");
535 prl("\tFOR i:=1 TO tempa STEP 1 DO tempres := tempres DIV 2 OD;");
536 prl(createToEStack("tempres"));
542 int b1
= get(), b2
= get();
543 prl(createLocal(b1
) + " := " + createLocal(b1
) + " + " + b2
+ ";");
549 // TODO maybe objects and arrays should be in the same list?
550 prl("mjvm_objects := mjvm_objects ++ < ARRAY(" + size
552 prl(createToEStack("LENGTH(mjvm_objects)"));
556 get();// 0 - bytes, 1 - words; ignore for now
557 // TODO take into consideration 0/1
558 prl(createTopEStack());
559 prl("mjvm_arrays := mjvm_arrays ++ < ARRAY(tempa,0) >;");
560 prl(createToEStack("LENGTH(mjvm_arrays)"));
566 prl(createTopTwoEStack());
567 prl(createToEStack(createArray("tempb") + "[tempa+1]"));
572 prl(createFromEStack("tempres"));
573 prl(createTopTwoEStack());
574 // we need to use a temparray as a pointer, WSL
575 // otherwise tries to access it as a list of lists and fails
576 prl("VAR < tempArray := " + createArray("tempb") + " > :");
577 prl("tempArray[tempa+1]:=tempres ENDVAR;");
581 prl(createTopEStack());
582 prl("tempb := LENGTH("+ createArray("tempa") + ");");
583 prl(createToEStack("tempb"));
588 prl(createTopEStack());
589 prl(createToEStack("tempa"));
590 prl(createToEStack("tempa"));
594 prl(createTopTwoEStack());
595 prl(createToEStack("tempb"));
596 prl(createToEStack("tempa"));
597 prl(createToEStack("tempb"));
598 prl(createToEStack("tempa"));
603 prl(createPopEStack());
608 prl("CALL a" + (counter
+ get2()) + ";");
618 prl(createStartVar("tempa", "tempb"));
619 prl(createTopTwoEStack());
620 prl("IF tempb " + getRelationFor(op
) + " tempa THEN CALL a"
621 + (counter
+ get2()) + " ELSE CALL a" + (counter
+ 1)
629 prl("CALL a" + (counter
+ get2()) + ";");
634 // we let the actions return
635 // there is nothing to clean up
636 prl("SKIP\n END\n b" + counter
+ " ==");
640 int parameters
= get();
643 prl(createToMStack("mjvm_locals"));
644 prl("mjvm_locals := ARRAY(" + locals
+ ",0);");
645 for (int i
= parameters
- 1; i
>= 0; i
--)
646 prl(createFromEStack(createLocal(i
)));
650 prl(createFromMStack("mjvm_locals"));
656 // TODO make it a char for read
657 messages
.message("char is read like a number", TransMessages
.M_WAR
);
658 prl(createComment("char is read like a number", C_SPEC
));
661 prl(createStartVar("tempa"));
662 prl("tempa := @String_To_Num(@Read_Line(Standard_Input_Port));");
663 prl(createToEStack("tempa"));
670 prl(createStartVar("tempa", "tempb"));
671 prl(createTopTwoEStack());
672 prl("Print_MJ_CHAR(tempb,tempa);");
677 // TODO printing numbers needs different lengths of spacing
678 prl(createStartVar("tempa", "tempb"));
680 prl(createTopTwoEStack());
681 prl("Print_MJ(tempb,tempa);");
687 prl("ERROR(\"Runtime error: trap(" + get() + ")\");");
692 prl(createComment("unknown op error: " + op
, C_ERR
));
693 messages
.message("unknown op error: " + op
, TransMessages
.M_ERR
);
697 boolean wasJump
= isJumpCode(op
);
703 prl("CALL a" + counter
+ "\n END");
705 prl("SKIP\n END\nENDACTIONS;\n");
706 pr(createStandardEnd());
709 public void convertFile(File f
) {
711 convertStream(new FileInputStream(f
));
712 } catch (Exception ex
) {
713 ex
.printStackTrace();
717 public void printHelp() {
724 public void printLongHelp() {
727 System
.out
.println();
729 System
.out
.println();
730 printHelpDirectives();
731 System
.out
.println();
732 printHelpGenerating();
733 System
.out
.println();
737 public void printHelpOutput() {
738 System
.out
.println("Output options:");
739 System
.out
.println(" --screen print output to screen");
740 System
.out
.println(" -o --oc[+-] include original code in comments");
741 System
.out
.println(" -v verbose, print warning messages");
742 System
.out
.println(" -q quiet; don't print even the error messages");
743 System
.out
.println(" -d print detailed debug messages");
746 public void printHelpGenerating() {
747 System
.out
.println("Options for generating extra code for tracking code execution");
748 System
.out
.println(" --genEStackPrint generate print for all EStack changes");
749 System
.out
.println(" --genAddrPrint generate prints after every address of the original code ");
750 System
.out
.println(" --genAddrPause generate a pause after every address of the original code ");
751 System
.out
.println(" --genAddr short for --genAddrPrint and --genAddrPause");
752 System
.out
.println(" --genAll short for applying all code generation");
755 public void printHelpDirectives(){
756 System
.out
.println("Alternatives for code generation:");
757 System
.out
.println(" --genPopPush generate POP/PUSH instead of TAIL/HEAD");
760 public void printHelpHelp() {
761 System
.out
.println("Help and info options");
762 System
.out
.println(" -h basic help");
763 System
.out
.println(" --help print more detailed help");
764 System
.out
.println(" --version or -version print version and exit");
767 public void printUsage(){
768 System
.out
.println("usage:\n\t mjc2wsl {options} filename [outfile]");
771 public void printVersion() {
772 System
.out
.println("MicroJava bytecode to WSL converter. v " + versionN
773 + ", by Doni Pracner");
776 public String
makeDefaultOutName(String inname
){
778 if (inname
.endsWith(".obj"))
779 rez
= rez
.substring(0, rez
.length() - 4);
783 public void run(String
[] args
) {
784 if (args
.length
== 0) {
788 while (i
< args
.length
&& args
[i
].charAt(0) == '-') {
789 if (args
[i
].compareTo("-h") == 0) {
792 } else if (args
[i
].compareTo("--help") == 0) {
795 } else if (args
[i
].compareTo("--version") == 0
796 || args
[i
].compareTo("-version") == 0) {
799 } else if (args
[i
].compareTo("-o") == 0
800 || args
[i
].startsWith("--oc")) {
801 if (args
[i
].length() == 2)
802 originalInComments
= true;
803 else if (args
[i
].length() == 5)
804 originalInComments
= args
[i
].charAt(4) == '+';
806 originalInComments
= true;
807 } else if (args
[i
].compareTo("--screen") == 0) {
808 out
= new PrintWriter(System
.out
);
809 } else if (args
[i
].compareTo("-d") == 0) {
810 messages
.setPrintLevel(TransMessages
.M_DEB
);// print debug info
811 } else if (args
[i
].compareTo("-v") == 0) {
812 messages
.setPrintLevel(TransMessages
.M_WAR
);// print warnings
813 } else if (args
[i
].compareTo("-q") == 0) {
814 messages
.setPrintLevel(TransMessages
.M_QUIET
);// no printing
815 } else if (args
[i
].compareToIgnoreCase("--genEStackPrint") == 0) {
816 genPrintEStackOnChange
= true;
817 } else if (args
[i
].compareToIgnoreCase("--genAddrPause") == 0) {
818 genPauseAfterEachAddress
= true;
819 } else if (args
[i
].compareToIgnoreCase("--genAddrPrint") == 0) {
820 genPrintForEachAddress
= true;
821 } else if (args
[i
].compareToIgnoreCase("--genAddr") == 0) {
822 genPrintForEachAddress
= true;
823 genPauseAfterEachAddress
= true;
824 } else if (args
[i
].compareToIgnoreCase("--genAll") == 0) {
825 genPrintEStackOnChange
= true;
826 genPrintForEachAddress
= true;
827 genPauseAfterEachAddress
= true;
828 } else if (args
[i
].compareToIgnoreCase("--genPopPush") == 0) {
834 if (i
>= args
.length
) {
835 System
.out
.println("no filename supplied");
838 File f
= new File(args
[i
]);
840 if (i
+ 1 < args
.length
) {
842 out
= new PrintWriter(args
[i
+ 1]);
843 } catch (Exception e
) {
844 System
.err
.println("error in opening out file:");
849 // if not set to screen, or a file, make a default filename
851 out
= new PrintWriter(makeDefaultOutName(args
[i
]));
852 } catch (Exception e
) {
853 System
.err
.println("error in opening out file:");
858 Calendar now
= Calendar
.getInstance();
860 long mili
= Calendar
.getInstance().getTimeInMillis()
861 - now
.getTimeInMillis();
862 System
.out
.println("conversion time:" + mili
+ " ms");
863 messages
.printMessageCounters();
866 System
.out
.println("file does not exist");
870 public static void main(String
[] args
) {
871 new mjc2wsl().run(args
);
Svarog.pmf.uns.ac.rs/gitweb
maintanance
Doni Pracner