Sub topic 4
Static and dynamic scope, access links and display
This chapter assumes you know what an activation record is, how the control stack grows and shrinks on calls and returns, and what a nested procedure is. Those ideas come from the earlier chapters on activation records and frame layout.
Scope: which declaration does a name mean?
A program can declare the same name in several places. The scope rule decides which declaration a use of the name refers to.
- Static (lexical) scope: a non-local name refers to the declaration in the nearest enclosing block in the program text. The compiler can resolve it without running the program.
- Dynamic scope: a non-local name refers to the most recent binding still active on the call stack. The answer depends on who called whom at run time.
The same program gives different output under the two rules:
x = 1
def f():
return x
def g():
x = 2
return f()
print(g())Python uses static scope, so this prints 1. Here f is written at the top level, so its x is the global x. Under dynamic scope, the call chain is main -> g -> f. The most recent x on that chain is g's x = 2, so the result would be 2.
The next program simulates dynamic scope with an explicit stack of bindings. Each call pushes its local bindings, and a lookup searches from the top of the stack down.
env_stack = [{"x": 1}]
def lookup(name):
for frame in reversed(env_stack):
if name in frame:
return frame[name]
raise NameError(name)
def f():
return lookup("x")
def g():
env_stack.append({"x": 2})
result = f()
env_stack.pop()
return result
print(g())This prints 2.
Finding non-local variables at run time
With static scope and nested procedures, the compiler knows at compile time how many nesting levels separate a use from its declaration. The run-time system must still find the right activation record, because a procedure may have many live frames. Two mechanisms do this: access links and the display.
Define the nesting depth of a procedure as 1 for the outermost one, plus 1 for each level of lexical nesting inside it. Consider this program:
def main():
x = 10
def a():
y = 5
def b():
return x + y
return b()
return a()
print(main())It prints 15. The depths are main = 1, a = 2 and b = 3.
Access links
An access link is a pointer stored in each activation record. It points to the frame of the procedure that lexically encloses this one, which is not always the caller.
To reach a variable declared at depth d from code running at depth n, follow n - d access links, then add the variable's offset in that frame.
In the example above, b runs at depth 3:
yis declared at depth 2. Follow 1 link toa's frame.xis declared at depth 1. Follow 2 links, throughatomain.
Setting the access link on a call
Suppose procedure p at depth n_p is called from procedure q at depth n_q. The callee's access link must point to the frame of the procedure that lexically encloses p, which sits at depth n_p - 1. The rule is:
- If
n_p = n_q + 1,pis nested directly inside the caller. The access link is the caller's own frame. - Otherwise
n_p <= n_q. Start at the caller's frame and follown_q - n_p + 1access links. The frame you reach is the one forp's enclosing procedure.
Recursion shows why the link is not the caller. If a (depth 2) calls itself, n_q - n_p + 1 = 1. Starting from the calling a frame, one link leads to main. So every a frame points to main, however deep the recursion goes.
The display
A display is a global array d where d[i] points to the most recent live frame at nesting depth i. A variable declared at depth i is found at d[i] plus its offset, so access takes constant time.
When a procedure at depth j is called:
- It saves the old value of
d[j]in its own activation record. - It sets
d[j]to point to its new frame.
On return, it restores d[j] from the saved value.
| Property | Access links | Display |
|---|---|---|
| Cost of reading a non-local name | `n - d` pointer hops | One array lookup |
| Cost of a call | Compute the link by following hops | Save and update one display entry |
| Extra storage | One pointer per frame | One global array and one saved slot per frame |
| Best when | Nesting is shallow | Nesting is deep and non-local access is frequent |
Common errors
- Confusing the access link with the control link. The control link points to the caller's frame. The access link points to the lexical parent's frame. They coincide only when the callee is nested directly in the caller.
- Counting depth from 0 in one step and from 1 in another. Pick one convention. The number of hops is the difference of depths, so only consistency matters.
- Using access links to resolve names under dynamic scope. Dynamic scope needs no static chain. It searches the control stack, or uses a table of bindings per name that is saved and restored on calls.
- Forgetting that the access link is set by the callee's declaration site, not by the call site.
Exercise
Procedures P (depth 1), Q (depth 2, nested in P) and R (depth 3, nested in Q) are declared. P calls Q, Q calls R, and R calls Q. When R calls Q, how many access links must be followed from R's frame to find Q's access link? What does that link point to?
Show answer
Here np = 2 (Q) and nq = 3 (R). Since np <= nq, follow nq - np + 1 = 2 links from R's frame. The first link leads to Q's frame and the second to P's frame. The new Q frame's access link points to P's frame, which is correct because P lexically encloses Q.
Exercise
In the first program of this chapter, what does g() return under static scope and under dynamic scope?
Show answer
Static scope returns 1, because f's x is the global x. Dynamic scope returns 2, because the most recent active binding of x is g's local x = 2.