Java Reference
In-Depth Information
4.5.5 Typing Expressions and Enforcing the Type Rules
Much of the rest of analysis, as defined for the various kinds of AST nodes, is about comput-
ing and checking types and enforcing additional j-- rules. Indeed, when one reads through
any compiler, one finds lots of code whose only purpose is to enforce a litany of rules.
For most kinds of AST nodes, analysis involves analyzing the sub-trees and checking the
types.
Analyzing a Subtraction Operation
For example, analyzing a
JSubtractOp
is straightforward:
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;
}
Analyzing a
+
Operation Causes Tree Rewriting for Strings
On the other hand, analyzing a
JPlusOp
is complicated by the possibility that one of
the operands to the
+
is a string; in this case, we simply rewrite the
JPlusOp
as a
JStringConcatenationOp
and analyze that:
publicJExpressionanalyze(Contextcontext){
lhs=(JExpression)lhs.analyze(context);
rhs=(JExpression)rhs.analyze(context);
if(lhs.type()==Type.STRING||rhs.type()==Type.STRING){
return(newJStringConcatenationOp(line,lhs,rhs))
.analyze(context);
}elseif(lhs.type()==Type.INT&&rhs.type()==Type.INT){
type=Type.INT;
}else{
type=Type.ANY;
JAST.compilationUnit.reportSemanticError(line(),
"Invalidoperandtypesfor+");
}
returnthis;
}
And, analyzing a
JStringConcatenationOp
is easy because we know at least one of the
operands is a string, so the result has to be a string:
publicJExpressionanalyze(Contextcontext){
type=Type.STRING;
returnthis;
}
Analyzing a Literal
Analyzing a literal is trivial. We know its type. For example, the
analyze()
method for
JLiteralInt
follows:
publicJExpressionanalyze(Contextcontext){
type=Type.INT;
returnthis;
}
Search WWH ::
Custom Search