Java Reference
In-Depth Information
4.5.1 Top of the AST
Traversing the Top of the AST
At the top of the AST, analyze() simply recursively descends into each of the type (class)
declarations, delegating analysis to one class declaration at a time:
publicJASTanalyze(Contextcontext){
for(JASTtypeDeclaration:typeDeclarations){
typeDeclaration.analyze(this.context);
}
returnthis;
}
Each class declaration in turn iterates through its members, delegating analysis to each of
them. The only interesting thing is that, after all of the members have been analyzed, static
field initializations are separated from instance field initializations, in preparation for code
generation. This is discussed in the next section.
Rewriting Field Initializations as Assignments
In JFieldDeclaration , analyze( ) rewrites the field initializer as an explicit assignment
statement, analyzes that, and then stores it in the JFieldDeclaration 's initializations list.
publicJFieldDeclarationanalyze(Contextcontext){
for(JVariableDeclaratordecl:decls){
//Allinitializationsmustbeturnedintoassignment
//statementsandanalyzed
if(decl.initializer()!=null){
JAssignOpassignOp=
newJAssignOp(decl.line(),
newJVariable(decl.line(),
decl.name()),
decl.initializer());
assignOp.isStatementExpression=true;
initializations.add(
newJStatementExpression(decl.line(),
assignOp).analyze(context));
}
}
returnthis;
}
Afterward, returning up to JClassDeclaration , analyze() separates the assignment
statements into two lists: one for the static fields and one for the instance fields.
//Copydeclaredfieldsforpurposesofinitialization.
for(JMembermember:classBlock){
if(memberinstanceofJFieldDeclaration){
JFieldDeclarationfieldDecl=(JFieldDeclaration)member;
if(fieldDecl.mods().contains("static")){
staticFieldInitializations.add(fieldDecl);
}else{
instanceFieldInitializations.add(fieldDecl);
}
}
}
Later, codegen() will use these lists in deciding whether or not to generate both an instance
initializing method and a class initializing method.
For example, consider the static field, declared in the Factorial class:
staticintn=5;
 
Search WWH ::




Custom Search