Java Reference
In-Depth Information
4.5.3 Simple Variables
Simple variables are represented in the AST as JVariable nodes. A simple variable could
denote a local variable, a field or a type. Analysis of simple variables involves looking up
their names in the symbol table to find their types. If a variable is not found in the symbol
table, then we examine the Type for the surrounding class (in which the variable appears)
to see if it is a field. If it is a field, then the field selection is made explicit by rewriting the
tree as a JFieldSelection .
The code for analyze() in JVariable is as follows:
publicJExpressionanalyze(Contextcontext){
iDefn=context.lookup(name);
if(iDefn==null){
//Notalocal,butisitafield?
TypedefiningType=context.definingType();
Fieldfield=definingType.fieldFor(name);
if(field==null){
type=Type.ANY;
JAST.compilationUnit.reportSemanticError(line,
"Cannotfindname:"+name);
}else{
//Rewriteavariabledenotingafieldasan
//explicitfieldselection
type=field.type();
JExpressionnewTree=newJFieldSelection(line(),
field.isStatic()||
(context.methodContext()!=null&&
context.methodContext().isStatic())?
newJVariable(line(),
definingType.toString()):
newJThis(line),name);
return(JExpression)newTree.analyze(context);
}
}else{
if(!analyzeLhs&&iDefninstanceofLocalVariableDefn&&
!((LocalVariableDefn)iDefn).isInitialized()){
JAST.compilationUnit.reportSemanticError(line,
"Variable"+name+"mightnothavebeen
initialized");
}
type=iDefn.type();
}
returnthis;
}
For example, consider a simple case where a variable is declared locally, such as the variable
v in our Locals class. When analyzing the return statement,
returnt+v;
the analysis of v is pretty straightforward and is illustrated in Figure 4.10.
1. Its name is looked up in the symbol table and is found to be associated with the
LocalVariableDefn of a local variable with type Type.INT and oset 3.
2. The LocalVariableDefn is recorded in field iDefn for later use by code generation.
3. The type field is copied from the LocalVariableDefn .
 
Search WWH ::




Custom Search