Sub topic 3
Static and Dynamic Scope, Access Links, and Displays
Assume you know functions, recursion, activation records, and basic stack operations. This chapter explains how a procedure finds a variable when several active procedures use the same name.
Static scope
Static scope, also called lexical scope, is determined by the program text. A reference to a variable is resolved by searching the current block and then its lexically enclosing blocks. The call history does not change this decision.
Consider this pseudocode:
x = 1
procedure Outer:
x = 2
procedure Inner:
print(x)
Inner()
procedure Caller:
x = 3
Outer()
Caller()With static scope, Inner is declared inside Outer, so its x refers to the x declared in Outer. The output is 2.
Dynamic scope
Dynamic scope resolves a variable by searching the active call chain. The search starts in the current procedure, then moves to the procedure that called it, and continues toward older activation records.
For the example above, Inner is called by Outer, and Outer is called by Caller. Since Outer has a local x, both static and dynamic scope produce 2.
To show the difference, suppose Outer does not declare x:
x = 1
procedure Outer:
procedure Inner:
print(x)
Inner()
procedure Caller:
x = 3
Outer()
Caller()Static scope finds the global x, so the output is 1. Dynamic scope searches the call chain and finds Caller's x, so the output is 3.
| Rule | Search path | Result in the second example |
|---|---|---|
| Static scope | Lexical nesting in the source | `1` |
| Dynamic scope | Active callers at run time | `3` |
Access links
Under static scope, each activation record can contain an access link. An access link points to the activation record of the procedure's lexically enclosing procedure.
If Inner is nested inside Outer, the Inner frame's access link points to the current Outer frame. If Inner needs a variable two lexical levels outward, the runtime follows two access links.
Displays
A display is an array indexed by lexical nesting level. Entry D[k] points directly to the most recent activation record at level k.
Access links require repeated pointer traversal for a distant variable. A display gives direct access in approximately constant time. However, every procedure call and return must update the relevant display entry. Recursion also requires saving and restoring old entries.
Exercise
Under static scope, P is nested inside Q, and Q is nested inside R. Which frame should P's access link reference?
Show answer
The current activation record for Q, because Q is P's lexically enclosing procedure.