R – Why are lexical scopes prefered by the compilers

compiler-constructionlexical-scopescope

How does lexical scope help the compilers? Does it help in compilation or optimization?

Best Solution

I do think that lexical scope helps the compiler and optimization. It depends what you mean by help though.

Lexical or static scope allow the compiler to proof availability of a variable when referenced locally, that means within its lexical context. It has to be in the scope of the method referencing the variable.

To do such in dynamic scope environments, all calling contexts have to be taken into consideration, as a function knows all variables its calling context knows as well. To make sure a variable is available for reference, a recursive backtrack of all calling contexts would be necessary at compile time.

As this is very complicated, it would be omitted at compile time, throwing exceptions at runtime.

See here: In dynamic scoping, by contrast, you search in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. "Dynamic" refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from.