Java Reference
In-Depth Information
Switching
control
cases
CaseItem
labelList
stmts
more
Expr
LabelList
caseLabel
isDefault
more
caseExp
CaseItem
. . .
StmtList
LabelList
Expr
Figure 9.20: Abstract Syntax Tree for a Switch Statement
Finally, some programming languages forbid gotos into a conditional or
iterative statement from outside. Thatis,evenifthescopeofalabelisan
entire subprogram, a goto into a loop body, or from a then part to an else
part, is forbidden. Such restrictions can be enforced by marking each label in
declaredLabels
as either
active
or
inactive
. Gotos are allowed only to active labels,
and a label within a conditional or iterative statement is active only while the
AST that contains the label is being processed. Thus, a label
L
within a while
loop becomes activewhen the loop body's AST is checked and is inactive when
statements outside the loop body are checked.
Java, C, C
contain a
switch statement
that allows the selection of
one of a number of statements based on the value of a control expression.
ML, Ada, and a number of older languages contain a
case statement
that is
equivalent. We shall focus on translating switch statements, but our discussion
applies equally to case statements.
The AST for a switch statement rooted at Switchingis shown in Figure 9.20
(fields not needed for semantic analysis are omitted for clarity). In the AST,
control
represents an integer-valued expression;
cases
is a CaseItem,repre-
senting the cases in the switch. Each CaseItemhas three fields.
labelList
is a
LabelList that represents one or more case labels.
stmts
is an AST node repre-
senting the statements following a case constant in the switch.
more
is either
null or another CaseItem, representing the remaining cases in the switch.
A LabelList contains an integer field
caseLabel
,anAST
caseExp
, a Boolean
field
isDe f ault
,andC
++
(representing the default case label), and
more
, a field that is