Java Reference
In-Depth Information
either null or another LabelList (representing the remainder of the list). The
caseExp AST represents a constant expression that labels a case within the
switch; when it is evaluated, caseLabel will hold its value.
A number of steps are needed to check the semantic correctness of a
switch statement. The control expression and all the statements in the case
body must be type-checked. The control expression must be an integer type
(enumerations, if available, are also allowed). Each case label must be a
constant expression assignable to the type of the control expression. No two
case labels may have the same value. At most, one default label may appear
within the switch body.
The semantic visitors used to enforce these rules are shown in Figure 9.21.
Utility methods used by the semantic visitors are defined in Figure 9.22.
Method
(defined for bothCaseItemand LabelList) walks anAST
for a switch and gathers all labels into an integer list.
gather
L
abels
uplicates
takes a sorted label list and compares adjacent list values to find duplicate la-
bels. Method
check
F
or
D
(defined for both CaseItemand LabelList) walks
an AST for a switch statement, counting how many default cases have been
defined (more than one is illegal). The semantic visitor for LabelList uses the
visitor class ConstExprVisitor introduced in Section 9.1.3. Visitors from this
class determine whether an expression AST represents a constant value. If so,
the value is placed in field exprValue . Otherwise, this field is set to null.
Reachability analysis for switch statements is defined in Figure 9.23. A
switch statement can terminate normally in a number of ways. Although
uncommon, an empty switch body trivially terminates normally. If the last
switch group (case labels followed by a statement list) terminates normally,
so does the switch (since execution ”falls through” to the succeeding state-
ment). If any of the statements within a switch body contain a reachable break
statement, then the entire switch can terminate normally.
We fir s t ma rk t he who l e switch as not terminating normally. This will
be updated to true if cases is null, if a reachable break is encountered while
checking the switch body, or if the stmts AST of the last CaseItemin the AST
is marked as terminating normally.
As an example of our semantic analysis techniques, consider the following
switch statement:
count
D
efaults
switch(p) {
case 2:
case 3:
case 5:
case 7:
isPrime = true; break;
case 4:
case 6:
case 8:
Search WWH ::




Custom Search