Java Reference
In-Depth Information
the resulting code that should be executed, if any, based on the outcome
of that test.
while
statements
The AST structure shown in Figure 7.15(d) retains the two
essential elements of a while statement: the predicate expression and the
loop body.
Block of statements
Rules 6, 7, and 8 work together to synthesize a block
(sequence) of statements. As with the digits example of Figure 7.11, we
need only record the order of the statements. The result of Rule 6 is
therefore the structure shown in Figure 7.15(e).
plus
operations
The section of the grammar in Figure 7.14 that derives sym-
bols from E has rules that serve only to disambiguate the grammar. The
concrete syntax derived from E is shown in Figure 7.16(a). By eliminat-
ing structure unnecessary for translation, we arrive at the AST design
shown in Figure 7.16(b). A nodes such as plus that represents binary
(two-operand) operations becomes a parent with two children that sup-
ply the operands.
The arithmetic operations can thus be modeled after the assignment
structure in Figure 7.15(a), with the assignment operator replaced by the
given arithmetic operator. The result, shown in Figure 7.15(b), represents
the sum of its two children.
Next, semantic actions must be added into the parser to construct the AST
structures shown in Figure 7.15. When the parse is finished, theAST is returned
as its artifact at Marker
13
.Markers
14
,
15
,
16
,and
17
synthesize the
structures shown in Figure 7.15 for assign, if,andwhile statements. A block
of statements is generated at Marker
18
, assuming that Stmts does its job
properly and returns a list of siblings—one for each statement in the block.
The list is begun with the Stmt first reduced at Marker
20
.Thereafter,each
succeeding Stmt is added to the sibling list at Marker
19
.TherulesforE
work similarly, with the first operand of the sum reduced at Marker
22
.The
plus structure is generated at Marker
21
. Leaf nodes for variables and integer
constants are generated at Markers
23
and
24
.
Figure 7.18 shows a concrete syntax tree for a program written in the
language defined by the grammar in Figure 7.14. The semantic actions of
Figure 7.17 create the AST shown in Figure 7.19.