Next: Repeat
Up: Other Conditional Statements
Previous: Other Conditional Statements
The bytecode for the while statement can be structured as follows:
This can be compiled in the following way:
- Save the index of the next instruction that will be added, we need this
later for the goto instruction;
- Add the code for the condition, of which the first instruction is added
at the saved index;
- Add an ifeq instruction with no parameters;
- Add an empty instruct structure containing the index of the
ifeq instruction as its label;
- Add the code for the body of the while statement, which is inserted
before the label of the ifeq instruction;
- Add a goto instruction with the offset to the saved index as its
parameterlist. This offset is computed by subtracting the current index of the
goto instruction + 1 from the saved index. This instruction is also added
before the label of the ifeq instruction;
- Resolve the label of the ifeq instruction
by subtracting the index contained in the label from the index of the
structure holding the label. The resulting offset is constructed into a
parameterlist and added to the ifeq instruction (which is at the index in
the label). Remove the structure holding the label from the list.
By saving the index in the beginning, we saved the index of the first
instruction of the code for the condition of the while statement. This is
the index of the instruction to jump to when the code for the body of the
while statement has been executed, and the condition has to be checked again.
The ifeq instruction causes a jump to the first instruction of the code
following the while statement in case the condition evaluates to
false.
Next: Repeat
Up: Other Conditional Statements
Previous: Other Conditional Statements
mark@bottom.xs4all.nl