I have looked for suggested question that answer mine but did not find any related ones.
I am studying compiler design and have come across the feature that a language supports nested lexical scopes. It means the outer variables are visible to inner functions defined within other functions. However, to do this the information at what stack frame and what offset the variable in question is found is needed. How can a compiler emit this information in the symbol table if we have recursion depth that depends on the user input?
Thanks!
Example: Scope A contains scope B which contains scope C. In scope C, there's a reference to variable va
declared in scope A.
When compiling scope C, the compiler knows that va
was declared in A. And although it doesn't know where A's stack frame will be at runtime, it does know that A is "two scopes out" from C. So it thinks of va
as "two scopes out, at offset 1" (say). The object code it generates for the reference to va
is "go 2 steps down the scope chain, then access offset 1".
So at runtime, each stack frame has both a pointer to its 'parent' frame on the stack (so it knows how to set the stack pointer when it returns), and also a pointer to the frame that is 'next out' on the scope chain (so it can resolve references to non-local variables). Setting up these pointers is part of the process of creating a new stack frame.
(Or at least, that's the mental model you should start with. There are optimizations that avoid traversing the scope chain.)