Professional Documents
Culture Documents
Unit II Jntukrjgh
Unit II Jntukrjgh
Unit II Jntukrjgh
TECH)
UNIT -II
Names, Scopes and Binding
Name is Abstraction
A name is exactly what you think it is .Most names are identifiers
symbols (like '+') can also be names . A binding is an association between two things, such
as a name and the thing it names .The scope of a binding is the part of the program
(textually)in which the binding is active.
Names enable programmers to refer to variables, constants, operations, and types using
identifier names
Names are control abstractions and data abstractions for program fragments and data
structures
Control abstraction:
Subroutines (procedures and functions) allow programmers to focus
on manageable subset of program text
Subroutine interface hides implementation details
Data abstraction:
Object-oriented classes hide data representation details behind a set
of operations
Binding
A binding is an association between a name and an entity/a value
Depending on the binding time, there are static binding and dynamic binding
Binding time is the time at which an implementation decision is made to create a binding
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Binding Time
Language design time
the design of specific program constructs (syntax), primitive types, and meaning
(semantics)
Language implementation time
fixation of implementation constants such as numeric precision, run-time memory
sizes, max identifier name length, number and types of built-in exceptions, etc.
Program writing time
the programmer's choice of algorithms and data structures
Compile time
the time of translation of high-level constructs to machine code and choice of
memory layout for data objects
Link time
the time at which multiple object codes (machine code files) and libraries are
combined into one executable
Load time
when the operating system loads the executable in memory
Run time
when a program executes
Object and Binding Lifetimes
Creation of object
Beginning of the object lifetime
Creation of binding
Beginning of the binding lifetime
Use of bindings
The object is manipulated via its binding
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Deactivation/reactivation of bindings
Binding may be out-of-scope, so invisible
Destruction of bindings
End of the binding lifetime
Destruction of objects
End of the object lifetime
Binding lifetime: time between creation and destruction of binding to object
a pointer variable is set to the address of an object
a formal argument is bound to an actual argument
Object lifetime: time between creation and destruction of an object
Deal location Errors in Bindings
Bindings are temporarily invisible when code is executed where the binding (name
object) is out of scope
Memory leak: object never destroyed (binding to object may have been destroyed,
rendering access impossible)
Dangling reference: object destroyed before binding is destroyed
Garbage collection prevents these allocation/deallocation problems
Implementation decisions (continued):
run time
value/variable bindings, sizes of strings
subsumes
program start-up time
module entry time
elaboration time (point a which a declaration is first "seen")
procedure entry time
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
block entry time
statement execution time
The terms STATIC and DYNAMIC are generally used to refer to things bound before run time
and at run time, respectively
static is a coarse term; so is "dynamic"
IT IS DIFFICULT TO OVERSTATE THE IMPORTANCE OF BINDING TIMES IN
PROGRAMMING LANGUAGES
In general, early binding times are associated with greater efficiency
Later binding times are associated with greater flexibility Compiled
languages tend to have early binding times
Interpreted languages tend to have later binding times
Scope Rules - control bindings
Fundamental to all programming languages is the ability to name data, i.e., to refer to data using
symbolic identifiers rather than addresses
Not all data is named! For example, dynamic storage in C or Pascal is referenced by pointers, not
names
Lifetime and Storage Management
Key events
creation of objects
creation of bindings
references to variables (which use bindings)
(temporary) deactivation of bindings
reactivation of bindings
destruction of bindings
destruction of objects
The period of time from creation to destruction is called the LIFETIME of a binding
If object outlives binding it's garbage
If binding outlives object it's a dangling reference
The textual region of the program in which the binding is active is its scope
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
In addition to talking about the scope of a binding , we sometimes use the word scope as a
noun all by itself, without an indirect object
Storage Allocation mechanisms
Static
Stack
Heap
Static allocation for
code
globals
static variables
explicit constants (including strings, sets, etc)
Object Storage
Objects (program data and code) have to be stored in memory during their lifetime
Static objects have an absolute storage address that is retained throughout the execution of
the program
Global variables and data
Subroutine code and class method code
Stack objects are allocated in last-in first-out order, usually in conjunction with subroutine
calls and returns
Actual arguments passed by value to a subroutine
Local variables of a subroutine
Heap objects may be allocated and deallocated at arbitrary times, but require an expensive
storage management algorithm
Lisp lists
Java class instances are always stored on the heap
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Storage Allocation Static
Program code is statically allocated in most implementations of imperative languages
Statically allocated variables are history sensitive
Global variables keep state during entire program lifetime
Static local variables in C functions keep state across function invocations
Static data members are shared by objects and keep state during program lifetime
Advantage of statically allocated object is the fast access due to absolute addressing of the
object
Problem: static allocation of local variables cannot be used for recursive
subroutines: each new function instantiation needs fresh locals
Each instance of a subroutine that is active has a subroutine frame (sometimes called
activation record) on the run-time stack
Compiler generates subroutine calling sequence to setup frame, call the routine,
and to destroy the frame afterwards
Method invocation works the same way, but in addition methods are typically
dynamically bound
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Subroutine frame layouts vary between languages, implementations, and machine platforms
Central stack for
parameters
local variables
temporaries
Why a stack?
allocate space for recursive routines(not necessary in FORTRAN no recursion)
reuse space(in all programming languages)
Contents of a stack frame
local variables
arguments and returns
temporaries
bookkeeping (saved registers, line number static link, etc.)
Local variables and arguments are assigned fixed OFFSETS from the stack pointer or frame
pointer at compile time
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Maintenance of stack is responsibility of calling sequence and subroutine prolog and epilog.space
is saved by putting as much in the prolog and epilog as possible
time may be saved by putting stuff in the caller instead or combining what's known in both
places(interprocedural optimization)
Storage Allocation Heap
Implicit heap allocation
Done automatically
Java class instances are placed on the heap
Scripting languages and functional languages make extensive use of the heap for
storing objects
Some procedural languages allow array declarations with run-time dependent array
size
Resizable character strings
Explicit heap allocation
Statements and/or functions for allocation and deallocation
Malloc/free, new/delete
Heap for dynamic allocation
Sco
Scope is the textual region of a program in which a name-to-object binding is active
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Statically scoped language: the scope of bindings is determined at compile time
Used by almost all but a few programming languages
More intuitive to user compared to dynamic scoping
Dynamically scoped language: the scope of bindings is determined at run time
Used in Lisp (early versions), APL, Snobol, and Perl (selectively)
Static Scoping
The bindings between names and objects can be determined by examination of the
program text
Scope rules of a program language define the scope of variables and subroutines
A variable always refers to its nearest enclosing binding closest nested scope rule
Look for a declaration in the current innermost scope
If there is none, look for a declaration in the immediately surrounding
scope, etc.
Static Scope Implementation with Static Links
Scope rules are designed so that we can only refer to variables that are alive: the variable
must have been stored in the frame of a subroutine
If a variable is not in the local scope, we are sure there is a frame for the surrounding scope
somewhere below on the stack:
The current subroutine can only be called when it was visible
The current subroutine is visible only when the surrounding scope is active
Each frame on the stack contains a static link pointing to the frame of the static parent
Example Static Links
Subroutines C and D are declared nested in B
B is static parent of C and D
B and E are nested in A
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
A is static parent of B and E
The fp points to the frame at the top of the stack to access locals
The static link in the frame points to the frame of the static parent
Static Chains
How do we access non-local objects?
The static links form a static chain, which is a linked list of static parent frames
When a subroutine at nesting level j has a reference to an object declared in a static parent
at the surrounding scope nested at level k, then j-k static links forms a static chain that is
traversed to get to the frame containing the object
The compiler generates code to make these traversals over frames to reach non-local
objects
Example Static Chains
Subroutine A is at nesting level 1 and C at nesting level 3
When C accesses an object of A, 2 static links are traversed to get to A's frame that
contains that object
Out of Scope
Non-local objects can be hidden by local name-to-object bindings and the scope is said to
have a hole in which the non-local binding is temporarily inactive but not destroyed
Some languages, notably Ada and C++ use qualifiers or scope resolution operators to
access non-local objects that are hidden
P1.X in Ada to access variable X of P1 and ::X to access global variable X in C++
Out of Scope Example
procedure P1;
var X:real;
procedure P2;
var X:integer
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
begin
... (* X of P1 is hidden *)
end;
begin
...end
P2 is nested in P1
P1 has a local variable X
P2 has a local variable X that hides X in P1
When P2 is called, no extra code is executed to inactivate the binding of X to P1
Dynamic Scoping
Scope rule: the "current" binding for a given name is the one encountered most recently during
execution
With dynamic scope:
Name-to-object bindings cannot be determined by a compiler in general
Easy for interpreter to look up name-to-object binding in a stack of declarations
Generally considered to be "a bad programming language feature"
Hard to keep track of active bindings when reading a program text
Most languages are now compiled, or a compiler/interpreter mix
Sometimes useful:
Unix environment variables have dynamic scope
Scope Rules
A scope is a program section of maximal size in which no bindings change, or at least in which no
re-declarations are permitted
In most languages with subroutines, we OPEN a new scope on subroutine entry:
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
create bindings for new local variables, deactivate bindings for global variables that are re-
declared (these variable are said to have a "hole" in their scope) make references to variables
On subroutine exit:
destroy bindings for local variables
reactivate bindings for global variables that were deactivated
Algol 68:
ELABORATION = process of creating bindings when entering a scope
Ada (re-popularized the term elaboration):
storage may be allocated, tasks started, even exceptions propagated as a result of the elaboration of
declarations.
With STATIC (LEXICAL) SCOPE RULES, a scope is defined in terms of the physical
(lexical) structure of the program
The determination of scopes can be made by the compiler
All bindings for identifiers can be resolved by examining the program
Typically, we choose the most recent, active binding made at compile time
Most compiled languages, C++ and Java included, employ static scope rules
The classical example of static scope rules is the most closely nested rule used in block
structured languages such as Algol 60 and Pascal
An identifier is known in the scope in which it is declared and in each enclosed scope,
unless it is re-declared in an enclosed scope
To resolve a reference to an identifier, we examine the local scope and statically enclosing
scopes until a binding is found
We will see classes - a relative of modules - later on, when discussing abstraction and
object-oriented languages
These have even more sophisticated (static) scope rules
Euclid is an example of a language with lexically-nested scopes in which all scopes are
closed
rules were designed to avoid ALIASES, which complicate optimization and correctness
arguments
Access to non-local variables STATIC LINKS
Each frame points to the frame of the (correct instance of) the routine inside which it was
declared
In the absence of formal subroutines, correct means closest to the top of the stack
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
You access a variable in a scope k levels out by following k static links and then using the
known offset within the frame thus found
The key idea in static scope rules is that bindings are defined by the physical (lexical)
structure of the program.
With dynamic scope rules, bindings depend on the current state of program execution
They cannot always be resolved by examining the program because they are dependent on
calling sequences
To resolve a reference, we use the most recent, active binding made at run time
Dynamic scope rules are usually encountered in interpreted languages
early LISP dialects assumed dynamic scope rules.
Such languages do not normally have type checking at compile time because type
determination isn't always possible when dynamic scope rules are in effect
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Binding of Referencing Environments
Accessing variables with dynamic scope:
(1) keep a stack (association list) of all active variables
When you need to find a variable, hunt down from top of stack
This is equivalent to searching the activation records on the dynamic chain
Accessing variables with dynamic scope:
(2) keep a central table with one slot for every variable name
If names cannot be created at run time, the table layout (and the location of every slot) can be fixed
at compile time
Otherwise, you'll need a hash function or something to do lookup Every
subroutine changes the table entries for its locals at entry and exit.
REFERENCING ENVIRONMENT of a statement at run time is the set of active bindings
A referencing environment corresponds to a collection of scopes that are examined (in
order) to find a binding
SCOPE RULES determine that collection and its order
BINDING RULES determine which instance of a scope should be used to resolve
references when calling a procedure that was passed as a parameter
they govern the binding of referencing environments to formal procedures
Overloading
some overloading happens in almost all languages
integer + v. real +
read and write in Pascal
function return in Pascal
some languages get into overloading in a big way
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
It's worth distinguishing between some closely related concepts
overloaded functions - two different things with the same name; in C++
overload norm
int norm (int a){return a>0 ? a : -a;)
complex norm (complex c ) { // ...
polymorphic functions -- one thing that works in more then one way
in Modula-2: function min (A : array of integer);
in Smalltalk
It's worth distinguishing between some closely related concepts (2)
generic functions (modules, etc.) - a syntactic template that can be instantiated in more than one
way at compile time
via macro processors in C++
built-in in C++
in Clu
in Ada
Deep vs. Shallow Binding
In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that
were in scope when the subroutine was created. In shallow binding, they are whichever variables
with the same names happen to be in scope when the subroutine is called. Perl always uses deep
binding of lexical variables However, dynamic variables (aka global, local, or package variables)
are effectively shallowly bound. Consider this just one more reason not to use them.
Overloading, Polymorphism, Generics
Same name (symbol) for more than one use
Inferred typing
Same name parameterized for multiple use.
Separate Compilation
Indira institute of technology &sciences:: markapur
www.jntuworld.com
www.jntuworld.com www.android.jntuworld.com www.jwjobs.net
PREPARED BY:- D.VENKATA REDDY (M.TECH)
Separately-compiled files in C (continued)
Extern on a variable or function means that it is declared in another source file
Function headers without bodies are extern by default
Extern declarations are interpreted as forward declarations if a later declaration overrides them
Indira institute of technology &sciences:: markapur
www.jntuworld.com