Java Reference
In-Depth Information
}
We will jump right into the try block to see what is going on.
If the current token is
<LCURLY>
, which marks the beginning of a block, the lower-
level non-terminal block is invoked to parse block-statement. The value returned by
block is assigned to the local variable statement.
If the token is
<IF>
, we get its line number and parse an
if
statement; we delegate
to the lower-level non-terminals
parExpression
and statement to parse the test ex-
pression, the consequent, and the (optional) alternate statements. Note the use of
the j and [] JavaCC constructs for alternation and option. Once we have successfully
parsed an
if
statement, we create an instance of the AST node for an
if
statement
and assign it to the local variable
statement
.
If the token is
<WHILE>
,
<RETURN>
, or
<SEMI>
, we parse a
while
,
return
, or an empty
statement.
Otherwise, it must be a statement expression, which we parse by simply delegating
to the lower-level non-terminal
statementExpression
. In each case we set the local
variable
statement
to the appropriate AST node instance.
Finally, we return the local variable
statement
and this completes the parsing of a j--
statement.
Lookahead
As in the case of a recursive descent parser, we cannot always decide which production rule
to use in parsing a non-terminal just by looking at the current token; we have to look ahead
at the next few symbols to decide. JavaCC offers a function called
LOOKAHEAD
that we can
use for this purpose. Here is an example in which we parse a simple unary expression in j--,
expressed by the BNF rule:
simpleUnaryExpression ::=
!
unaryExpression
j
(
basicType
)
unaryExpression //cast
j
(
referenceType
)
simpleUnaryExpression // cast
j postxExpression
privateJExpressionsimpleUnaryExpression():{
intline=0;
Typetype=null;
JExpressionexpr=null,unaryExpr=null,simpleUnaryExpr=null;
}
{
try{
<LNOT>{line=token.beginLine;}
unaryExpr=unaryExpression()
{expr=newJLogicalNotOp(line,unaryExpr);}|
LOOKAHEAD(<LPAREN>basicType()<RPAREN>)
<LPAREN>{line=token.beginLine;}
type=basicType()
<RPAREN>
unaryExpr=unaryExpression()
{expr=newJCastOp(line,type,unaryExpr);}|
LOOKAHEAD(<LPAREN>referenceType()<RPAREN>)
<LPAREN>{line=token.beginLine;}
type=referenceType()
Search WWH ::
Custom Search