Java Reference
In-Depth Information
x a[i] o.f C.sf
codegenLoadLhsLvalue() [none] aloada'
aloadi'
aloado' [none]
codegenLoadLhsRvalue() iloadx'
iaload
dup2
getfieldf
dup getstaticsf
codegenDuplicateRvalue()dup dup_x2 dup_x1 dup
codegenStore() istorex'iastore putfield
f
putstaticsf
Our compiler defines an interface JLhs , which declares four abstract methods for these
four sub-operations. Each of JVariable , JArrayExpression , and JFieldSelection im-
plements JLhs . Of course, one must also be able to generate code for the right-hand side
expression. But codegen() is sucient for that|indeed, that is its purpose.
For example, JPlusAssignOp 's codegen() makes use of all of these operations:
publicvoidcodegen(CLEmitteroutput){
((JLhs)lhs).codegenLoadLhsLvalue(output);
if(lhs.type().equals(Type.STRING)){
rhs.codegen(output);
}else{
((JLhs)lhs).codegenLoadLhsRvalue(output);
rhs.codegen(output);
output.addNoArgInstruction(IADD);
}
if(!isStatementExpression){
//Generatecodetoleavether-valueatopstack
((JLhs)lhs).codegenDuplicateRvalue(output);
}
((JLhs)lhs).codegenStore(output);
}
5.6 Generating Code for String Concatenation
The implementation of most unary and binary operators is straightforward; there is a JVM
instruction for each j-- operation. A case for which this does not apply is string concatena-
tion.
In j--, as in Java, the binary + operator is overloaded. If both of its operands are integers,
it denotes addition. But if either operand is a string then the operator denotes string
concatenation and the result is a string. String concatenation is the only j-- operation
where the operand types don't have to match 9 .
The compiler's analysis phase determines whether or not string concatenation is implied.
When it is, the concatenation is made explicit; that is, the operation's AST is rewritten,
replacing JAddOp with a JStringConcatenationOp . Also, when x is a string, analysis re-
places
x+=<expression>
by
x=x+<expression>
9 We leave the implementation of other implicit type conversions as an exercise.
 
Search WWH ::




Custom Search