Java Reference
In-Depth Information
Changes to Scanner
Here we only discuss the changes to the hand-written scanner. Scanners can also be gener-
ated; this is discussed in Chapter 2. Before changing
Scanner.java
, we must register
DIV
as
a new token, so we add the following to the
TokenKind
enumeration in the
TokenInfo.java
file.
enumTokenKind{
EOF("<EOF>"),
...,
STAR("*"),
DIV("/"),
...
}
The method that actually recognizes and returns tokens in the input is
getNextToken
()
. Currently,
getNextToken()
does not recognize
/
as an operator, and reports an error
when it encounters a single
/
in the source program. In order to recognize the operator, we
replace the
getNextToken()
code in
Scanner
.
if(ch=='/'){
nextCh();
if(ch=='/'){
//CharReadermapsallnewlinesto'\n'
while(ch!='\n'&&ch!=EOFCH){
nextCh();
}
}
else{
reportScannerError(
"Operator/isnotsupportedinj--.");
}
}
with the following.
if(ch=='/'){
nextCh();
if(ch=='/'){
//CharReadermapsallnewlinesto'\n'
while(ch!='\n'&&ch!=EOFCH){
nextCh();
}
}
else{
returnnewTokenInfo(DIV,line);
}
}
Changes to Parser
Here we only discuss the changes to the hand-written parser. Parsers can also be generated;
this is discussed in Chapter 3. We first need to define a new AST node to represent the
division expression. Because the operator is a multiplicative operator like
*
, we can model
the AST for the division expression based on the one (
JMultiplyOp
) for
*
. We call the new
AST node
JDivideOp
, and because division expression is a binary expression (one with two
operands), we define it in
JBinaryExpression.java
as follows:
classJDivideOpextendsJBinaryExpression{
publicJDivideOp(intline,JExpressionlhs,JExpressionrhs){
Search WWH ::
Custom Search