next up previous contents
Next: If Then Else Up: Statements Previous: write and writeln

Control Statements

 

Compiling the various control statements requires doing labeling, so you can jump to these labels. The problem with the bytecode is that you do not have any labels. All the jump instructions of the JVM jump to some offset instead of to a label. This means you have to come up with your own labeling in the compiler.

To do labeling I added a jmp_label field to the instruct structure that holds an instruction and its parameterlist. If you set a label, you add an instruct structure to the list with the label set. The label contains the index of the instruction that jumps to it. In all the instruct structures with no label, the value of the jmp_label field is set to the value -1. Every instruction that is added to the code[] list of a method is now inserted before the first instruct structure in the list with its label set instead of being added to the end of the list. When a label is set, the instruct structure containing the label is also inserted before the first label in the list. This way the first label in the list is allways the label for the last jump instruction added that has an unknown offset.

The list of instructions can now be seen as consisting of two parts: The first part is the list of instructions of the method and the second part is the list of the labels. Every instruction (or label) that is added to the list is added to the end of the list of instructions and before the list of labels, as can be seen in the following figure:

If the index of the instruction to jump to is known, i.e. all the instructions are inserted before the label, the offset is computed by subtracting the index contained in the label (the index of the instruction to jump from) from the index of the instruct structure that is labeled (the index of the instruction to jump to). This offset is added as parameter to the instruction to jump from. After this is done, the label can be set to -1 or the whole instruct structure can be removed from the list if it did not contain an instruction.

I only implemented if statements in the compiler, just to see how the labeling works. These will be discussed in the next subsection. After that I will present ideas on how to compile other conditional statements.





next up previous contents
Next: If Then Else Up: Statements Previous: write and writeln



mark@bottom.xs4all.nl