I am taking a principles of programming languages course right now but I cannot for the life of me figure this out. This is not homework just a general concept question.
In our class we have talked about static chains and displays. I think that I understand why we need these. Otherwise when we have nested methods we cannot figure out what variable we are talking about when we have nested methods.
My prof has also talked about a symbol table. My question is what is the symbol table used for? How does it relate to the static chains?
I will give some background (please correct me if I am wrong).
(I am going to define a few things just to make explanations easier)
Suppose we have this code:
main(){
int i;
int j;
int k;
a(){
int i;
int j;
innerA(){
int i = 5;
print(i);
print(j);
print(k);
}
}
b(){
...
}
...
}
And this stack:
| innerA |
| a |
| b |
| main |
-----------
Quick description of static chains as a refresher.
Static chains are used to find which variable should be used when variables are redefined inside an inner function. In the stack shown above each frame will have a pointer to the method that contains it. So:
| innerA | \\ pointer to a
| a | \\ pointer to main
| b | \\ pointer to main
| main | \\ pointer to global variables
-----------
(Assuming static scoping, for dynamic scoping I think that every stack frame will just point to the one below it)
I think that when we execute print(<something>)
inside the innerA
method this will happen:
currentStackframe = innerAStackFrame;
while(true){
if(<something> is declared in currentStackFrame)
print(<something>);
break;
else{
currentStackFrame = currentStackFrame.containedIn();
}
}
Quick refresher of symbol table
I am not really sure what a symbol table is for. But this is what it looks like:
Index is has value,
Value is reference.
__
| |
|--| --------------------------------------------------
| | --------------------> | link to next | name | type | scope level | other |
|--| --------------------------------------------------
| | |
|--| ---------------
| | |
|--| | --------------------------------------------------
| | -------> | link to next | name | type | scope level | other |
|--| --------------------------------------------------
| |
|--|
- link to next - if more than one thing has the same has hash value this is a link
- name - name of the element (examples: i, j, a, int)
- type - what the thing is (examples: variable, function, parameter)
- scope level - not 100% sure how this is defined. I think that:
- 0 would be built-ins
- 1 would be globals
- 2 would be main method
- 3 would be a and b
- 4 would be innerA
Just to restate my questions:
- What is the symbol table used for?
- How does it relate to the static chains?
- Why do we need static chains since the scope information is in the symbol table.