Lesson 5 of 9 · 27m
Environments, Scope, and Closures
The environment chain model behind lexical scope, mutable bindings, first-class functions, and the closure bugs everyone hits once.
Scope is where languages stop feeling like calculators. The mechanism is small: an environment maps names to values and points at a parent. The subtlety is in what you store, when you copy it, and when names resolve.
Environments form a chain
class Environment:
def __init__(self, parent=None):
self.parent = parent
self.values = {}
def get(self, name, span):
env = self
while env is not None:
if name in env.values:
return env.values[name]
env = env.parent
raise RuntimeErrorAt(span, f"undefined variable '{name}'")Entering a block or function creates a child environment. Lookup walks outward. Assignment must walk outward too; otherwise x = 2 inside a block silently creates a shadow instead of updating the outer x.
Declaration order is a language decision
print x;
let x = 3;Is that an error, nil, or undefined behavior? JavaScript's var, JavaScript's let, and Python all make different choices. Write the rule down before implementing it; retrofitting a rule breaks user programs. A sane small-language rule is that let creates the binding when executed, and reading before then is a runtime error.
Closures capture environments, not values
When functions are values, they remember where they were defined:
@dataclass(frozen=True)
class Function:
params: list[str]
body: list[Stmt]
closure: EnvironmentThe canonical test is a counter factory: two counters made by separate calls must advance independently, while repeated calls to the same counter must share its captured count. Copying values gives you counters that never advance; sharing one global environment makes independent counters collide.
Resolution can happen early
A simple interpreter walks the environment chain on every lookup. A more serious one resolves variables before evaluation: each Variable expression records a fixed depth, such as "two environments out." Static resolution catches typos earlier and makes closure behavior independent of whatever happens to be alive at call time.
Field notes
- Shadowing should be intentional. Users will write it accidentally; good diagnostics distinguish shadowing from mutation.
- Captured environments extend object lifetimes and can create reference cycles in host languages with refcounting.
- Decide whether parameters are mutable and whether they may shadow outer names. "It falls out of the implementation" is not an answer.
- A REPL is a persistent top-level environment. Decide whether redefinition replaces a binding or creates a new one.
Was this lesson helpful?