We’re now ready to actually generate working code. Your task, should you accept it, is to change your interpreter to a compiler for arithmetic expressions. Generate code for the following “features”:
- Numbers (PUSH)
- Addition / subtraction (DADD, DSUB)
- Multiplication / division (DMUL, DDIV)
- Variable assignment (DSTORE)
- Variable access (DLOAD)
- Edit: variable assignments do NOT have to work like expressions, i.e. you don’t have to support “x = y = 5”!
A common problem with code generation is that you have to distinguish between compile time and run time. These are two separate phases, which is different from the way most interpreters work. Compile time is the first phase, in which you parse statements and generate code. You can use the JVM debugger to check this phase for errors, have a look at the symbol table and the results of the parser. When running the generated code, you cannot simply attach a debugger to it. This means that in the case of a wrong result, you have to manually check the bytecode to see what’s wrong. You do not see that stack, you have no variable names and there are no explicit control structures. You can use the Navigator view in Eclipse to open the .class files in your bin folder and see the bytecode. To make sure the bytecode is working, manually interpret it in your head. Keep track of the values on the stack by writing them on a sheet of paper. Check out the BCEL manual for help on the bytecode!
And if anybody happens to know a good bytecode debugger, please let everyone know on the mailing list…