22
1 Scope Rules Scope Rules (Section 3.3) (Section 3.3) CSCI 431 Programming Languages CSCI 431 Programming Languages Fall 2003 Fall 2003 A compilation of material A compilation of material developed by Felix Hernandez- developed by Felix Hernandez- Campos and Michael Scott Campos and Michael Scott

1 Scope Rules (Section 3.3) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael Scott

Embed Size (px)

Citation preview

11

Scope RulesScope Rules(Section 3.3)(Section 3.3)

CSCI 431 Programming LanguagesCSCI 431 Programming Languages

Fall 2003Fall 2003

A compilation of material developed by Felix A compilation of material developed by Felix Hernandez-Campos and Michael ScottHernandez-Campos and Michael Scott

22

Binding Time (Review)Binding Time (Review)

• A A bindingbinding is an association between two things is an association between two things– E.g. Name of an object and the objectE.g. Name of an object and the object

• Binding timeBinding time is the time at which a binding is is the time at which a binding is createdcreated

– Language design timeLanguage design time– Language implementationLanguage implementation– Program writing timeProgram writing time– Compile TimeCompile Time– Link TimeLink Time– Load TimeLoad Time– Run TimeRun Time

33

Binding Time ExampleBinding Time Example

• Java programJava program

• What is the binding time ofWhat is the binding time of– Value of argument x?Value of argument x?– Set of values of argument x?Set of values of argument x?– Type of argument x?Type of argument x?– Set of types of argument x?Set of types of argument x?– Properties of operator +?Properties of operator +?

publicpublic staticstatic intint increment( increment(intint x) { x) {returnreturn x + 1; x + 1;

}}

44

Binding Time ExampleBinding Time Example

• Perl programPerl program

• What is the binding time ofWhat is the binding time of– Value of argument @_?Value of argument @_?– Set of values of argument @_?Set of values of argument @_?– Type of argument @_?Type of argument @_?– Set of types of argument @_?Set of types of argument @_?– Properties of operator +?Properties of operator +?

subsub increment { increment {returnreturn shift @_ + 1; shift @_ + 1;

}}

55

ScopeScope

• ScopeScope is the textual region of a program in which a is the textual region of a program in which a binding is activebinding is active

• The word 'scope' used as a noun is a program section The word 'scope' used as a noun is a program section of maximal size in which no bindings change.of maximal size in which no bindings change.

– In most languages with subroutines, we OPEN a new In most languages with subroutines, we OPEN a new scope on subroutine entry.scope on subroutine entry.

• Algol 68 introduced the term Algol 68 introduced the term elaborationelaboration for the for the process of creating bindings when entering a scope. process of creating bindings when entering a scope. Elaboration time is a useful concept.Elaboration time is a useful concept.

66

Referencing EnvironmentReferencing Environment

• The referencing environment (of a statement or The referencing environment (of a statement or expression) is the set of active bindings. expression) is the set of active bindings.

• A referencing environment corresponds to a A referencing environment corresponds to a collection of scopes that are examined (in order) to collection of scopes that are examined (in order) to find a binding. find a binding.

77

Scope RulesScope Rules

• Programming languages implementProgramming languages implement– StaticStatic Scoping Scoping: active bindings are determined using the : active bindings are determined using the

text of the program. The determination of scopes can be text of the program. The determination of scopes can be made by the compiler.made by the compiler.

» Most recent scan of the program from top to bottomMost recent scan of the program from top to bottom» Closest nested subroutine ruleClosest nested subroutine rule» Most compiled languages employ static scope rulesMost compiled languages employ static scope rules

– DynamicDynamic Scoping Scoping: active bindings are determined by the : active bindings are determined by the flow of execution at run time (i.e., the call sequence).flow of execution at run time (i.e., the call sequence).

» The determination of scopes can NOT be made by the compiler.The determination of scopes can NOT be made by the compiler.» Dynamic scope rules are usually encountered in interpreted Dynamic scope rules are usually encountered in interpreted

languages; in particular, early LISP dialects assumed dynamic languages; in particular, early LISP dialects assumed dynamic scope rules. scope rules.

88

Static ScopeStatic Scope

• The classical example of static scope rules is the The classical example of static scope rules is the most closely nested rule used in block structured most closely nested rule used in block structured languages such as Algol 60 and Pascal. languages such as Algol 60 and Pascal.

• An identifier is known in the scope in which it is An identifier is known in the scope in which it is declared and in each enclosed scope, unless it is declared and in each enclosed scope, unless it is redeclared in an enclosed scope. redeclared in an enclosed scope.

• To resolve a reference to an identifier, we examine To resolve a reference to an identifier, we examine the local scope and statically enclosing scopes until a the local scope and statically enclosing scopes until a binding is found.binding is found.

99

Nested SubroutinesNested SubroutinesClosest Nested Subroutine RuleClosest Nested Subroutine Rule

1010

Storage Management (revisited)Storage Management (revisited)

• Static allocation for:Static allocation for:– code, globals, "own" variables, explicit constants code, globals, "own" variables, explicit constants – scalars may be stored in the instructions themselvesscalars may be stored in the instructions themselves

• Central stack for:Central stack for:– parameters, local variables, temporaries, bookkeeping informationparameters, local variables, temporaries, bookkeeping information

• Why a stack?Why a stack?– allocate space for recursive routinesallocate space for recursive routines

» (not necessary in FORTRAN, etc)(not necessary in FORTRAN, etc)

– reuse spacereuse space» (useful in any language)(useful in any language)

• Heap for:Heap for:– dynamic allocationdynamic allocation

1111

Stack-based AllocationStack-based Allocation

1212

Static LinksStatic Links

• Local variables and arguments are assigned fixed Local variables and arguments are assigned fixed offsetsoffsets from the stack pointer or frame pointer at from the stack pointer or frame pointer at compile timecompile time

• Access to non-local variables via Access to non-local variables via static linksstatic links– Each frame points to the frame of the (correct instance Each frame points to the frame of the (correct instance

of) the routine inside which it was declared. of) the routine inside which it was declared. » In the absense of formal subroutines, "correct" means closest to In the absense of formal subroutines, "correct" means closest to

the top of the stack.the top of the stack.

– you access a variable in a scope k levels out by following you access a variable in a scope k levels out by following k static links and then using the known offset within the k static links and then using the known offset within the frame thus found.frame thus found.

1313

Nested SubroutinesNested SubroutinesDetermining ScopeDetermining Scope

StaticStaticLinksLinks

1414

An ExampleAn Example

    Procedure A2 { Procedure A2 {

int a = 0;int a = 0;

Procedure C {Procedure C {

Procedure D { Procedure D {

print a;print a;

}}

Call D;Call D;

}}

Procedure B { Procedure B {

char a = 'b';char a = 'b';

Call C;Call C;

}}

Call B;Call B;

}}

1515

Static Scope VariantsStatic Scope Variants

• The key idea in static scope rules is that bindings are The key idea in static scope rules is that bindings are defined by the physical (lexical) structure of the defined by the physical (lexical) structure of the program.program.

• A newer example of static scope rules is the A newer example of static scope rules is the import/export strategies of modular languages such import/export strategies of modular languages such as Modula-2. as Modula-2.

• The modules of Modula, Ada, etc. give you The modules of Modula, Ada, etc. give you closed closed scopesscopes (no identifier is automatically inherited from (no identifier is automatically inherited from enclosing scopes) enclosing scopes) without the limited lifetimewithout the limited lifetime. .

– ALGOL 60 blocks implement OPEN scopes (identifiers ALGOL 60 blocks implement OPEN scopes (identifiers which are not redeclared are automatically inherited from which are not redeclared are automatically inherited from the enclosing scope).the enclosing scope).

– Bindings to variables declared in a module are inactive Bindings to variables declared in a module are inactive outside the module, but not destroyed. outside the module, but not destroyed.

1616

Other Static Scope VariantsOther Static Scope Variants

• Euclid is an example of a language with lexically-Euclid is an example of a language with lexically-nested scopes in which all scopes are closed. nested scopes in which all scopes are closed.

• The Euclid rules were designed to avoid ALIASES, The Euclid rules were designed to avoid ALIASES, which complicate optimization and correctness which complicate optimization and correctness arguments. arguments.

• It forces you to document side effects by explicitly It forces you to document side effects by explicitly importing any external variables that are read or importing any external variables that are read or written. written.

• Euclid prevents you from passing a variable by Euclid prevents you from passing a variable by reference to a procedure that imports the same reference to a procedure that imports the same variable.variable.

1717

Evolution of Data Abstraction Evolution of Data Abstraction FacilitiesFacilities

subroutines, variables, arrayssubroutines, variables, arrays

Fortran, BasicFortran, Basic

subroutine nestingsubroutine nesting

Algol 60, Pascal, many othersAlgol 60, Pascal, many others

own (static) variablesown (static) variables

Algol 68, Fortran ("save"), C, othersAlgol 68, Fortran ("save"), C, others

module as managermodule as manager

Modula, C files (sorta)Modula, C files (sorta)

module as typemodule as type

Simula*, EuclidSimula*, Euclid

classes, with inheritanceclasses, with inheritance

Simula*, Smalltalk, C++, Eiffel, Java, othersSimula*, Smalltalk, C++, Eiffel, Java, others

*predates Modula; clearly a language ahead of its time*predates Modula; clearly a language ahead of its time

timetime

1818

Dynamic Scope RulesDynamic Scope Rules

• Bindings cannot always be resolved by examining Bindings cannot always be resolved by examining the program because they are dependent on calling the program because they are dependent on calling sequences.sequences.

• Dynamic scope rules are usually encountered in Dynamic scope rules are usually encountered in interpreted languages.interpreted languages.

• Such languages do not normally have type checking Such languages do not normally have type checking at compile time because type determination isn't at compile time because type determination isn't always possible when dynamic scope rules are in always possible when dynamic scope rules are in effect.effect.

1919

Dynamic ScopeDynamic Scope

• Bindings between names and objects depend on the Bindings between names and objects depend on the flow of control at run timeflow of control at run time

– The The currentcurrent binding is the one found most recently binding is the one found most recently during during executionexecution

• ExampleExample– If the scoping is If the scoping is staticstatic, the , the

output of the program is output of the program is 11– If the scoping is If the scoping is dynamicdynamic, ,

output is output is 11 or or 22 depending on depending on the value read at line 8 (>0 or the value read at line 8 (>0 or <=0 respectively)<=0 respectively)

2020

Why Dynamic ScopeWhy Dynamic Scope

• Perhaps the most common use of dynamic scope Perhaps the most common use of dynamic scope rules is to provide implicit parameters to rules is to provide implicit parameters to subroutines. subroutines.

• This is generally considered bad programming This is generally considered bad programming practice nowadays.practice nowadays.

Ex: Ex: -Given a function print_integer() capable of -Given a function print_integer() capable of printing in several bases.printing in several bases.-Want to use decimal notation most times-Want to use decimal notation most times-set variable print_base to 10 early in execution-set variable print_base to 10 early in execution-to change base:-to change base:beginbegin --nested block--nested block

print_base : integer := 16print_base : integer := 16print_integer(n)print_integer(n)

2121

Accessing Variables with Dynamic Accessing Variables with Dynamic ScopeScope

• Two approaches:Two approaches:– Keep a stack (*association list*) of all active variables.Keep a stack (*association list*) of all active variables.

» When you need to find a variable, hunt down from top When you need to find a variable, hunt down from top of stack.of stack.

» This is equivalent to searching the activation records This is equivalent to searching the activation records on the dynamic chain.on the dynamic chain.

– Keep a central table with one slot for every variable name. Keep a central table with one slot for every variable name.

» If names cannot be created at run time, the table layout If names cannot be created at run time, the table layout (and the location of every slot) can be fixed at compile (and the location of every slot) can be fixed at compile time. Otherwise, you'll need a hash function or time. Otherwise, you'll need a hash function or something to do lookup. something to do lookup.

» Every subroutine changes the table entries for its locals Every subroutine changes the table entries for its locals at entry and exit.at entry and exit.

2222

Implementation of Dynamic ScopingImplementation of Dynamic Scoping