Static vs. Dynamic ScopeDynamic ScopeDynamic Scopeldots Dynamic Scope --- ProblemsDynamic Scope --- AdvantagesDynamic Scope --- Advantagesldots Dynamic Scope --- Advantagesldots Readings and References520—Spring 2005—34CSc 520Principles of ProgrammingLanguages34: Procedures — Dynamic ScopeChristian [email protected] of Computer ScienceUniversity of ArizonaCopyrightc 2005 Christian Collberg[1]520—Spring 2005—34Static vs. Dynamic ScopePascal is lexically scoped. We can look (textually, or atcompile-time) at a procedure and determine to whichobject an identifier refers.Some languages (Snobol, APL, Perl, some dialects ofLISP) aredynamically scoped. The binding between anidentifier and the object it refers to is not decided untilrun-time.[2]520—Spring 2005—34Dynamic ScopeThe current binding for an identifier is the one last seenduring execution and whose scope has yet to bedestroyed.Consider the example on the next slide.static scope: the program prints 1.dynamic scope: the program prints 2.Static scope rules match the use of an identifier with theclosest lexically enclosing declaration.Dynamic scope rules choose the most recent activedeclaration at runtime.[3]520—Spring 2005—34Dynamic Scope...var a : integer;procedure first();a := 1;procedure second();var a : integer;first();begina := 2;second();write(a);end[4]520—Spring 2005—34Dynamic Scope — Problemsvar max : integer;procedure scale(x : integer) : real;return x/max;procedure compute(y : integer);var max : integer;write(scale(y));Dynamic scope makes it is easy to accidentally redefinea variable.[5]520—Spring 2005—34Dynamic Scope — Advantagesprocedure A(base : integer)printInt(base, 245);procedure B(base : integer)A();procedure C(base : integer)B();begin C(16); endWe often have to pass around state so that deeplynested procedures can make use of it.DEBUG-flags is acommon example.[6]520—Spring 2005—34Dynamic Scope — Advantages...var base : integer := 10;procedure A()printInt(base, 245);procedure B()A();procedure C()B();beginvar lastbase := base;base := 16; C();base := last base;endWe can, of course, use global variables.[7]520—Spring 2005—34Dynamic Scope — Advantages...procedure A()printInt(base, 245);procedure B()A();procedure C()B();beginvar base : integer := 16;C();endDynamic scope makes it is easy customize the behaviorof procedures.[8]520—Spring 2005—34Readings and ReferencesRead Scott, pp. 115–116, 129–132, 139–144, 298,471–479Dynamic Variables, David R. Hanson and Todd A.Proebsting, PLDI
View Full Document