Java Reference
In-Depth Information
class
ReachabilityVisitor
extends
NodeVisitor
/
This extends the class definition of Figure 9.3
/
procedure
(Switching
sn
)
sn
.
terminatesNormally
←
false
call
visit
visit
C
hildren
(
sn
)
if
sn
.
cases
=
null
then
sn
.
terminatesNormally
←
true
else
sn
.
terminatesNormally
←
sn
.
terminatesNormally
or
sn
.
cases
.
terminatesNormally
end
procedure
(CaseItem
cn
)
cn
.
stmts
.
isReachable
←
true
call
visit
visit
C
hildren
(
cn
)
if
cn
.
more
=
null
then
cn
.
terminatesNormally
←
cn
.
stmts
.
terminatesNormally
else
cn
.
terminatesNormally
←
cn
.
more
.
terminatesNormally
end
end
Figure 9.23: Reachability Analysis Visitors (Part 2)
case 9: isPrime = false; break;
default: isPrime = checkIfPrime(p);
}
Assume that p is declared as an integer variable. We check p and find it a
valid control expression. The label list is built by examining each CaseItem
and LabelList in the AST. We verify that each case label is a valid constant
expression that is assignable to p. The case statements are checked and found
to be valid. Since the last statement in the switch (the default) terminates
normally, so does the entire switch statement. The label list returned by
gather
.
No two adjacent elements in the sorted list are equal. Finally, we count the
number of default labels; a count of 1 is valid.
The semantic rules for switch statements inCandC
L
abels
is
{
2
,
3
,
5
,
7
,
4
,
6
,
8
,
9
}
. After sorting, we have
{
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
}
++
are almost identical
to those of Java. C
adds a requirement that ”fall throughs” from one leg of a
switch statement to another are illegal. That is, given:
switch(p) {
case 0:
isZero = true;
case 1:
print(p);
}
with a value of 0 for p,afterisZero is set, execution attempts to print p's value.
This construct is legal in C, C
++
, and Java, but not C
.Wecancheckforthis