ChapterÂ 2.Â Lexical Scope
In ChapterÂ 1, we defined âscopeâ as the set of rules that govern how the engine can look up a variable by its identifier name and find it, either in the current scope, or in any of the nested scopes itâs contained within.
There are two predominant models for how scope works. The first of these is by far the most common, used by the vast majority of programming languages. Itâs called lexical scope, and we will examine it in depth. The other model, which is still used by some languages (such as Bash scripting, some modes in Perl, etc) is called dynamic scope.
As we discussed in ChapterÂ 1, the first traditional phase of a standard language compiler is called lexing (a.k.a., tokenizing). If you recall, the lexing process examines a string of source code characters and assigns semantic meaning to the tokens as a result of some stateful parsing.
It is this concept that provides the foundation to understand what lexical scope is and where the name comes from.
To define it somewhat circularly, lexical scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by you, at write time, and thus is (mostly) set in stone by the time the lexer processes your code.
We will see in a little bit that there are some ways to ...