Java Reference
In-Depth Information
//position1:
if(n<=0){
return1;
}else{
returnn*factorial(n-1);
}
}
publicstaticvoidmain(String[]args){
//position2:
intx=n;
System.out.println(n+"!="+factorial(x));
}
staticintn=5;
}
The symbol table for this program, and its relationship to the AST, is illustrated in Figure
4.1.
In its entirety, the symbol table takes the form of a tree that corresponds to the shape
of the AST. A
context
|that is, a node in this tree|captures the region of scope corre-
sponding to the AST node that points to it. For example, in Figure 4.1,
1. The
context
pointer
from
the
AST's
JCompilationUnit
node
points
to
the
JCompilationUnitContext
that is at the root of the symbol table.
2. The context pointer from the AST's
JClassDeclaration
points to a
ClassContext
,
3. The context pointer from the AST's two
JMethodDeclarations
each point to a
MethodContext
4. The context pointer from the AST's two
JBlock
s each point to a
LocalContext
.
On the other hand, from any particular location in the program, looking back toward
the root
CompilationUnitContext
, the symbol table looks like a stack of contexts. Each
(
surroundingContext
) link back toward the
CompilationUnitContext
points to the con-
text representing the surrounding lexical scope.
For example,
1. The context for
Position2
pointer in Figure 4.1 points to a
LocalContext
, which
declares the local variable
x
in the body of the
main()
method of the
Factorial
program.
2. Its
surroundingContext
pointer points to a
MethodContext
in which the formal
parameter,
args
is declared.
3. Its
surroundingContext
pointer points to a
ClassContext
in which nothing is de-
clared.
4. Its
surroundingContext
pointer points to a
CompilationUnitContext
at the base
of the stack, which contains the declared types for the entire program.
During analysis, when the compiler encounters a variable, it looks up that variable in the
symbol table by name, beginning at the
LocalContext
most recently created in the symbol
table, for example, that pointed to by the pointer labeled \context for
Position1
." Type
names are looked up in the
CompilationUnitContext
. To make this easier, each context
maintains three pointers to surrounding contexts, as illustrated in Figure 4.2.
Search WWH ::
Custom Search