Java Reference
In-Depth Information
super(line,"/",lhs,rhs);
}
publicJExpressionanalyze(Contextcontext){
returnthis;
}
publicvoidcodegen(CLEmitteroutput){
}
}
To parse expressions involving division operator, we modify the
multiplicativeExpres
-sion()
method in
Parser.java
as follows:
privateJExpressionmultiplicativeExpression(){
intline=scanner.token().line();
booleanmore=true;
JExpressionlhs=unaryExpression();
while(more){
if(have(STAR)){
lhs=newJMultiplyOp(line,lhs,
unaryExpression());
}
elseif(have(DIV)){
lhs=newJDivideOp(line,lhs,
unaryExpression());
}
else{
more=false;
}
}
returnlhs;
}
Semantic Analysis and Code Generation
Since
int
is the only numeric type supported in j--, analyzing the division operator is
trivial. It involves analyzing its two operands, making sure each type is
int
, and setting the
resulting expression's type to
int
. We thus implement
analyze()
in the
JDivideOp
AST
as follows:
publicJExpressionanalyze(Contextcontext){
lhs=(JExpression)lhs.analyze(context);
rhs=(JExpression)rhs.analyze(context);
lhs.type().mustMatchExpected(line(),Type.INT);
rhs.type().mustMatchExpected(line(),Type.INT);
type=Type.INT;
returnthis;
}
Generating code for the division operator is also trivial. It involves generating (through
delegation) code for its operands and emitting the JVM (
IDIV
) instruction for the (integer)
division of two numbers. Hence the following implementation for
codegen()
in
JDivideOp
.
publicvoidcodegen(CLEmitteroutput){
lhs.codegen(output);
rhs.codegen(output);
output.addNoArgInstruction(IDIV);
}
Search WWH ::
Custom Search