Dynamic and lexical scoping

— Tech

Almost all contemporary languages use lexical scoping to resolve variable names to their values,1Actually to their bindings, not their values, but we’re going to get into that. but it didn’t start out this way. Early Lisp famously used dynamic scoping instead, and it remains in use in Bash, Emacs Lisp, and various other deranged languages. What is it? Why was it used? Why did it go away? And when is it still helpful? Read on to get the answer to these riveting questions.

Basics

The basic mental model that textbooks will give you is this:

In both dynamic and lexical scoping, when encountering a reference to variable foo, you look in the current environment for a definition, then in the parent environment if you don’t find it, and so on until reaching the global environment. If you’ve found it somewhere, that’s the value you need to use; if not, it’s an undefined reference error.

The difference is in what you consider to be the parent environment.

For lexical scoping, the parent environment is the syntactically enclosing environment. For instance, in this code:

let a = 0;
function f() {
    let b = 1;
    function g() { let c = 2; return a + b + c; }
    return g;
}
f()();  // returns 3

Inside the body of g, the environment contains c; the parent environment is the activation of f, which contains b, and the parent of that is the global environment, which contains a.

For dynamic scoping, the parent environment is the caller’s function activation, or the global scope, if called from there. You can’t look at a function body in the program text and say what the parent environment is, you have to be inside a call to that function to do so. The parent environment inside g is the body of whatever function called g, which may be different on different calls to g.

The most basic example of the difference is (program 1):

let a = 0;
function f() { return a; }
function h() { let a = 1; return f(); }
h();  // 0

But in Perl:

our $y = 0;
sub f2 { return $y }
sub h2 { local $y = 1; return f2() }
h2();  # 1

Lexical scoping is familiar and feels natural to most of us. But why use dynamic scoping? Think of the case where a is a contextual parameter, for instance the variable the HTTP client library reads to get the request timeout. It’s pretty useful to be able to specify something like that for all the HTTP requests ultimately made for all the functions I’m going to call, no matter how far down the call stack the HTTP request is. React’s Context is a good example of this, although it implements dynamic scoping over the component tree rather than the call stack.

Anyway this is all correct, but after looking at some tricky examples, I think it’s worth looking at the interaction of lexical vs dynamic scope with mutability and with early versus late resolution.

Things that are not dynamic scoping

Mutability

A couple of things slightly complicate the mental model above. The first thing that can trip someone up is this program (program 2). Compare program 1 above:

let a = 0;
function f() { return a; }
function h() { a = 1; return f(); }
h();  // 1, whether scoping is lexical (as here in JS), or dynamic

Why? In the first section I vaguely said we were searching (either up the call stack or up the lexical environment) for a “definition”, but that’s not very precise. In a mutable language you end up with two constructs: the binding, which associates a variable name with a storage location, and a value, which is the contents of that location.

let a = 0 defines a binding of a to a new storage location, which it sets to the value 0. a = 1 changes the value in that storage location, but does not update the binding. let a = 1, on the other hand, creates a new binding, and sets the value there to 1; the original storage location is still set to 0, and in another part of the program, a may still be bound to the first storage location, which still holds 0.

The whole question of lexical versus dynamic scoping is thus to resolve which binding is applicable for a particular name at a particular point in the program, not directly which value the binding (and hence name) resolves to.

Going back to program 2, there is only ever one binding of a defined. Under both lexical and dynamic scoping, a within the body of h is resolved to the global environment’s a; there’s only one binding in scope, which f uses.

This doesn’t come up in presentations that focus on immutable languages, and is not helped by the fact that some languages (like Python) use the same syntax for declaring a new variable and for assigning a value to an existing binding. (It uses global and nonlocal to let you specify what the assignment statement means: new binding or assignment.)

So mutability doesn’t actually interact with scoping rules in a very deep way, but it does tend to make analysis more confusing at a surface level.

Late resolution

Here’s another example, in JavaScript sloppy mode:

var b = 0;
function f(s) { eval(s); return b; }
f("");           // 0
f("var b = 1");  // 1

But in JavaScript strict mode:

"use strict";
var b = 0;
function f(s) { eval(s); return b; }
f("");           // 0
f("var b = 1");  // 0

Here the question basically hinges on when we check for the applicable binding: either statically, at program analysis time, or when actually running the reference.

If the language is lexically scoped, we already know that there are just two environments (and hence at most two bindings) in play in the body of f: the body of f, and the global environment. But does the choice of environment happen when analyzing the program code, or dynamically? Most languages do the former, including JS in strict mode, where the program above returns 0 in both calls to f.

This is called early versus late resolution. Dynamic or lexical scoping both give you a list of environments to search in; late or early resolution tells you when you must choose from this list. This distinction really only makes sense for lexically scoped variables, as dynamically scoped variables don’t have a chain of environments to pick from until runtime, so late resolution is essentially forced.

Things that are, basically, dynamic scoping

There are some reasons to use dynamically scoped variables today, but the reason they were used as the default mode in early Lisp was primarily implementation convenience.

I think there are three main reasons no major language uses dynamic scoping by default these days:

  1. Using dynamic scoping by default for all names is very confusing, because a local variable may have effects at a vast distance, a fact that was realized quite early on,
  2. Dynamic scoping, being dynamic, is harder to statically analyze and generate fast machine code for (but not very hard to generate code for if speed isn’t a concern),
  3. It’s pretty easy to emulate dynamic scoping where it’s useful in a language that only has lexical scoping, but the reverse is much trickier.

The first of these points has well-known examples (it’s why Lisp, which was initially all dynamically scoped, ended up inverting that choice and made specially declared names dynamically scoped). The second is, I think, true for systems languages but not an especially enormous disadvantage for interpreted languages that don’t care about maximal performance.

Most languages that offer dynamic variables at a language level (for instance Common Lisp, Clojure and Perl) make them opt-in, with lexical scoping the default. Others, like Python and Racket, offer them at the library level. A short amount of code can implement a basic version (although care should be taken with threading or async/await) using a global and a try/finally block:

let a = 0;
function f() { return a; }

function withA(v, thunk) {
  const old = a; a = v;
  try { return thunk(); } finally { a = old; }
}

withA(1, f);  // 1
f(); // 0

This is a passable emulation of dynamic scoping (if you ignore the difficulty that, if thunk awaits, a will be left in the wrong state, which is why e.g. contextvars is useful). We’re still mutating a global, but the try/finally construct makes the value follow the call stack.

This is essentially how dynamic binding is implemented in some language implementations. And as I mentioned in the beginning, this can be pretty helpful to pass parameters at a distance, without threading them through many layers of function calls.

Conclusion

We’ve examined three axes:

  1. Scoping (lexical vs dynamic) decides which environment chain to walk,
  2. Mutability changes a binding’s value instead of creating a new binding, which can look like dynamic scoping,
  3. Early versus late resolution means that the specific scope in the chain that is used to find the binding may change.

Lexical scoping, mutability and early resolution (for locals) are the most common choices made by contemporary languages, sometimes in configurable ways. For language designers, letting the user define some variables as dynamically scoped can be helpful, but think through semantic interactions with other features. For other users, I hope this clarifies your semantic model of the languages you may have used that make various choices along these axes.

Bibliography

  1. Actually to their bindings, not their values, but we’re going to get into that. ↩

Comments