Java Reference
In-Depth Information
The Statement is always executed at least once, and the Test is at the bottom of the loop.
As an example, consider
do{
sum=sum+i;
i=i 1;
}while(i>0);
The Oracle Java compiler, javac would produce for this:
top: iloadsum'
iloadi'
iadd
istoresum'
iloadi'
iconst_1
isub
istorei'
iloadi'
ifgt top
Compiling the do-while statement is very much like compiling the while-statement.
Exercise 5.7. Add the classic for-statement to j--, adding it to your compiler and testing
it thoroughly. The classic for-statement may be reformulated as a while-statement, even in
Java. For example, the template
for(Initialization;Test;Increment)
Statement
may be expressed as
Initialization
while(Test){
Statement;
Increment;
}
We must take into account the fact that either Initialization, Test, or Increment may be
empty, and translate appropriately. This means that the for-statement may be translated
in either of two ways:
1. We can generate JVM code directly, following the patterns illustrated in this chapter.
2. We can first rewrite the AST, replacing the JForStatement node with the block above,
and then apply codegen() to that sub-tree. Notice how the enclosing block captures
the limited scope of any variables declared in Initialization.
Which way is better?
Exercise 5.8. Add the enhanced for-statement to j--, adding it to your compiler and
testing it thoroughly. The Java enhanced for-statement is used to iterate over collections.
Syntactically, it looks something like
for(TypeIdentifier:Expression)
Statement
How this can be interpreted depends on the type of Expression. If Expression's type is a
sub-type of Iterable , let I be the type of Expression.iterator() . Then our enhanced
for-statement may be expressed as the following classic for-statement:
 
Search WWH ::




Custom Search