Java Reference
In-Depth Information
For this, we need special machinery. Not only must we differentiate between the two
kinds (basic type and reference type) of casts, but we must also distinguish a cast from a
postfix expression that is a parenthesized expression, for example
(x)
.
Consider the
Parser
code for parsing a simple unary expression:
privateJExpressionsimpleUnaryExpression(){
intline=scanner.token().line();
if(have(LNOT)){
returnnewJLogicalNotOp(line,unaryExpression());
}elseif(seeCast()){
mustBe(LPAREN);
booleanisBasicType=seeBasicType();
Typetype=type();
mustBe(RPAREN);
JExpressionexpr=isBasicType
?unaryExpression()
:simpleUnaryExpression();
returnnewJCastOp(line,type,expr);
}else{
returnpostfixExpression();
}
}
Here we use the predicate
seeCast()
to distinguish casts from parenthesized expressions,
and
seeBasicType()
to distinguish between casts to basic types from casts to reference
types. Now, consider the two predicates.
First, the simpler
seeBasicType()
.
privatebooleanseeBasicType(){
if(see(BOOLEAN)||see(CHAR)||see(INT)){
returntrue;
}else{
returnfalse;
}
}
The predicate simply looks at the next token to see whether or not it denotes a basic
type. The method
simpleUnaryExpression()
can use this because it has factored out the
opening parenthesis, which is common to both kinds of casts.
Now consider the more dicult
seeCast()
.
privatebooleanseeCast(){
scanner.recordPosition();
if(!have(LPAREN)){
scanner.returnToPosition();
returnfalse;
}
if(seeBasicType()){
scanner.returnToPosition();
returntrue;
}
if(!see(IDENTIFIER)){
scanner.returnToPosition();
returnfalse;
}else{
scanner.next();//ScantheIDENTIFIER
//Aqualifiedidentifierisok
while(have(DOT)){
if(!have(IDENTIFIER)){
scanner.returnToPosition();
returnfalse;
}
Search WWH ::
Custom Search