2 ms·
Lexical scoping means that a variable expression X refers to the innermost binding which is in the program text that encloses the references. Dynamic scoping m
by kazinator 9y ago
Lexical scoping means that a variable expression X refers to the innermost binding which is in the program text that encloses the references.
Dynamic scoping means that the expression X refers to the innermost binding of X in the entire activation chain ("call stack") leading up to that point (or possibly to a global, top-level X if there is no such binding).
Global means that X refers to a single instance in a top-level environment.
Dynamic scoping can be faked with global variables plus a hidden saving/restoring mechanism. That is to say, the local binding of a dynamic variable can be simulated by saving the current value in a hidden local location associated with the activation frame, then simply assigning to the global variable, and finally restoring the prior value (with unwind protection, so it is guaranteed). However, the ruse will be exposed under any sort of concurrency (threads, coroutines, continuations) which will make it apparent that there is only one instance of the variable. Under a true implementation of dynamic scoping, the local binding of the dynamic variable actually has a separate local location from the fall-back global one.
Note that the scoping classification of bindings is not sufficiently nuanced to capture what is possible. Words like "lexical" refers to visibility but "binding" is what happens at run-time: the establishment of the life of the thing that the name refers to, through to its termination. In Common Lisp parlance, the run-time lifetime of a binding is called its "extent".
If a language supports lexical closures, then lexical variables never "go away" while it is possible for a closure to be invoked which refers to their values. This situation is called "indefinite extent".
"Dynamic scope" is an informal term for "indefinite scope, dynamic extent". See here: https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node43.html https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node43.html [cltl2, 3 Scope and Extent]
This terminology lets us distinguish nuanced situations such as:
- C non-static local variables: lexical scope, dynamic extent (go away when block scope terminates).
- C static locals: lexical scope, indefinite extent
- Common Lisp blocks: lexical scope, dynamic extent