Java Reference
In-Depth Information
the condition can be resolved at compile-time is explored in Exercise 1.) Thus,
the if and then parts are both marked as reachable. An if statement termi-
nates normally if either its then part or its else part terminates normally. Since
null statements terminate trivially, an if-then statement (with a null else part)
always terminates normally. This analysis is detailed in Figure 9.3, Marker 6 .
Since we assume all components of an if statement are reachable, any
exceptionthrowninasubtreeofanIfTesting node can ”escape” from the
if. We create a method
(Figure 9.4, Marker 9 ) that visits all
subtrees of an AST node and returns the union of the throwsSet found in each
subtree. Throws analysis for an if is simply a call to
gather
T
hrows
gather
T
hrows
(Figure 9.4,
Marker 10 ).
As an example, consider the following statement:
if (b) a=1; else a=2;
Semantic analysis first checks the condition expression, b,whichmustproduce
a Boolean value. Then, the then and else parts are checked; these must be valid
statements. Since assignment statements always complete normally, so does
the if statement.
The modularity of our AST formulation is apparent here. The semantic
checks applied to the control expression b are the same as the checks used for
all expressions. Similarly, the semantic checks applied to the then and else
statements are those applied to all statements. Nested if statements cause no
di
culties; the same semantic checks are applied each time an IfTestingnode
is encountered.
9.1.3 While, Do, and Repeat Loops
The AST corresponding to a while statement is shown in Figure 9.5. A
WhileLooping node has two subtrees corresponding to the condition control-
ling the loop and the loop body. The semantic rules for a while statement are
identical to those of an if statement—the condition must be a valid Boolean-
valued expression and the loop body must be semantically valid. Semantic
analysis is implemented by calls to
visit
C
hildren
and
check
B
oolean
(Fig-
ure 9.1, Marker 3 ).
The reachability visitor for while loops is shown in Figure 9.6. Because do-
forever loops are common, this analysis must consider the special case where
the control expression of the loop is a constant. If the control expression is false,
then the statement list comprising the loop body is marked as unreachable
(Marker 23 ). If the control expression is true, the while loop is marked as
abnormally terminating because it is an infinite loop (Marker 22 ). It may be
that the loop body contains a reachable break statement.
If this is the case,
 
Search WWH ::




Custom Search