Java Reference
In-Depth Information
ForLooping
initializer
increment
loopBody
condition
. . .
StmtList
Expr
Stmt or Expr
Stmt or Expr
Figure 9.9: Abstract Syntax Tree for a For Loop
As was the case with while loops, the for loop's AST contains subtrees
corresponding to the loop's termination condition ( condition )anditsbody
( loopBody ). In addition, it contains ASTs corresponding to the loop's initializa-
tion ( initializer ) and its end-of-loop increment ( increment ).
There are a few di
erences that must be properly handled. Unlike the
while loop, the for loop's termination condition is optional. (This allows do-
forever loops of the form for (;;)
ff
, and Java, an index
local to the for loop may be declared, so a new symbol table name scope must
be opened, and later closed, during semantic analysis.
The semantic analysis visitor is defined in Figure 9.1 at Marker 5 .Anew
name scope is opened in case a loop index is declared in the initializer AST.
Next, all subtrees are semantically analyzed using
{
...
}
). In C
++
,C
visit
C
hildren
.If condition
is non-null, a call to
verifies that condition is Boolean-valued.
Finally, the name scope associated with the for loop is closed.
Reachability analysis, as defined in Figure 9.8, is very similar to that per-
formed for while loops. A null termination condition or a constant control
expression equal to true represent a non-terminating loop. In these cases, the
for loop is marked as not terminating normally (though a break within the
loop body may change this when the loop body is analyzed). A termination
condition that is a constant expression equal to false causes the loop body
to be marked as unreachable. If the control expression is non-null and non-
constant, the loop is marked as terminating normally. The throws analysis
visitor for for loops is shown in Figure 9.4 at Marker 13 . Again, it is just a call
to
check
B
oolean
gather
.
As an example, consider the following for loop:
T
hrows
for (int i=0; i < 10; i++)
a[i] = 0;
First a new name scope is created for the loop. When the declaration of i in
the initializer AST is processed, it is placed in this new scope (since all new
declarations are placed in the innermost open scope). Thus, the references to
 
Search WWH ::




Custom Search