Java Reference
In-Depth Information
<RPAREN>
simpleUnaryExpr=simpleUnaryExpression()
{expr=newJCastOp(line,type,simpleUnaryExpr);}|
expr=postfixExpression()
}
catch(ParseExceptione){
recoverFromError(newint[]{SEMI,EOF},e);
}
{returnexpr;}
}
We use the
LOOKAHEAD
function to decide between a cast expression involving a basic
type, a cast expression involving a reference type, and a postfix expression, which could
also begin with an
LPAREN
(
(x)
for example). Notice how we are spared the chore of writing
our own non-terminal-specific lookahead functions. Instead, we simply invoke the JavaCC
LOOKAHEAD
function by passing in tokens we want to look ahead. Thus, we do not have to
worry about backtracking either;
LOOKAHEAD
does it for us behind the scenes. Also notice
how, as in
LOOKAHEAD(<LPAREN>basicType()<RPAREN>)
, we can pass both terminals and
non-terminals to
LOOKAHEAD
.
Error Recovery
JavaCC offers two error recovery mechanisms, namely shallow and deep error recovery.
We employ the latter in our implementation of a JavaCC parser for j--. This involves
catching within the body of a non-terminal, the
ParseException
that is raised in the
event of a parsing error. The exception instance
e
along with skip-to tokens are passed to
our
recoverFromError()
error recovery function. The exception instance has information
about the erroneous token that was found and the token that was expected, and
skipTo
is
an array of tokens that we would like to skip to in order to recover from the error. Here is
the function:
privatevoidrecoverFromError(int[]skipTo,ParseExceptione){
//Getthepossibleexpectedtokens
StringBufferexpected=newStringBuffer();
for(inti=0;i<e.expectedTokenSequences.length;i++){
for(intj=0;j<e.expectedTokenSequences[i].length;
j++){
expected.append("\n");
expected.append(" ");
expected.append(tokenImage[
e.expectedTokenSequences[i][j]]);
expected.append("...");
}
}
//Printerrormessage
if(e.expectedTokenSequences.length==1){
reportParserError("\"%s\"foundwhere%ssought",
getToken(1),expected);
}
else{
reportParserError("\"%s\"foundwhereoneof%ssought",
getToken(1),expected);
}
//Recover
booleanloop=true;
do{
token=getNextToken();
for(inti=0;i<skipTo.length;i++){
Search WWH ::
Custom Search