22
1 Chapter 5: Chapter 5: Names, Bindings Names, Bindings and Scopes and Scopes Lionel Williams Jr. and Victoria Lionel Williams Jr. and Victoria Yan Yan CSci 210, Advanced Software CSci 210, Advanced Software Paradigms Paradigms September 26, 2010 September 26, 2010

1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

Embed Size (px)

Citation preview

Page 1: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

1

Chapter 5: Chapter 5: Names, Names, Bindings and ScopesBindings and Scopes

Lionel Williams Jr. and Victoria YanLionel Williams Jr. and Victoria Yan

CSci 210, Advanced Software ParadigmsCSci 210, Advanced Software Paradigms

September 26, 2010September 26, 2010

Page 2: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

2

5.1 Introduction5.1 Introduction

Imperative programming languages are Imperative programming languages are abstractions of underlying von Neumann abstractions of underlying von Neumann computer architecturecomputer architecture Two primary components:Two primary components:

Memory (stores instructions and data)Memory (stores instructions and data) Processor (provides operations for modifying the contents Processor (provides operations for modifying the contents

of memory)of memory) Abstractions in a language for the memory cells of the Abstractions in a language for the memory cells of the

machine are variablesmachine are variables Characteristics of abstractions are very close to the Characteristics of abstractions are very close to the

characteristics of the cells (example: integer variable – characteristics of the cells (example: integer variable – represented in one or more bytes of memory) represented in one or more bytes of memory) OROR

Abstractions are far removed from the organization of the Abstractions are far removed from the organization of the hardware memory (example: 3-D array – requires software hardware memory (example: 3-D array – requires software mapping function to support abstraction)mapping function to support abstraction)

Page 3: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

3

5.2 Names5.2 Names

Name (interchangeable with the term, Name (interchangeable with the term, identifier) identifier) String of characters used to identify some entity in a String of characters used to identify some entity in a

programprogram Design issuesDesign issues

Are names case sensitive?Are names case sensitive? Are the special words of the language reserved words or Are the special words of the language reserved words or

keywords?keywords? Name formsName forms

A letter followed by a string of letters, digits, and A letter followed by a string of letters, digits, and underscore charactersunderscore characters

Many languages are case sensitiveMany languages are case sensitive Example: ABC != abc != AbCExample: ABC != abc != AbC

Problem of writeability rather than readabilityProblem of writeability rather than readability

Page 4: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

4

5.2 Names (cont.)5.2 Names (cont.)

Special wordsSpecial words Used to make programs more readable by naming Used to make programs more readable by naming

actions to be performedactions to be performed Used to separate the syntactic parts of statements and Used to separate the syntactic parts of statements and

programsprograms KeywordKeyword

Word of programming language that is special only in Word of programming language that is special only in certain contextscertain contexts

Reserved wordReserved word Special word of a programming language that cannot be Special word of a programming language that cannot be

used as a nameused as a name

Page 5: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

5

5.3 Variables5.3 Variables A program variable is an abstraction of a computer A program variable is an abstraction of a computer

memory cell (or collection of cells)memory cell (or collection of cells) A variable can be characterized as a sextuple of namesA variable can be characterized as a sextuple of names

1.1. NamesNames

2.2. AddressAddress

3.3. ValueValue

4.4. TypeType

5.5. LifetimeLifetime

6.6. ScopeScope Names (previously discussed)Names (previously discussed) AddressAddress

Machine memory address with which it is associatedMachine memory address with which it is associated Sometimes called “l-value”Sometimes called “l-value” Alias is when more than one variable can be used to access the Alias is when more than one variable can be used to access the

same memory locationsame memory location

Page 6: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

6

5.3 Variables (cont.)5.3 Variables (cont.) ValueValue

Contents of the memory cell(s) associated with the variableContents of the memory cell(s) associated with the variable Memory cell refers to abstract memory cellMemory cell refers to abstract memory cell Variable’s value called “r-value”Variable’s value called “r-value”

What is required when the variable is used on the right side on an What is required when the variable is used on the right side on an assignment statementassignment statement

To access the r-value, the l-value must be determined firstTo access the r-value, the l-value must be determined first

TypeType Determines the range of values that a variable can store and the Determines the range of values that a variable can store and the

set of operations that are defined for values of that typeset of operations that are defined for values of that type LifetimeLifetime

Discussed in Section 5.4Discussed in Section 5.4 ScopeScope

Discussed in Section 5.5Discussed in Section 5.5

Page 7: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

7

5.4 The Concept of Binding5.4 The Concept of Binding

BindingBinding An association between an attribute and an entity or An association between an attribute and an entity or

between an operation and a symbolbetween an operation and a symbol Can occur at language design time, language Can occur at language design time, language

implementation time, compile time, load time, link time, or implementation time, compile time, load time, link time, or run timerun time

Binding timeBinding time Time at which a binding takes placeTime at which a binding takes place

Binding of attributes to variablesBinding of attributes to variables Static if it first occurs before run time and remains Static if it first occurs before run time and remains

unchanged throughout program executionunchanged throughout program execution Dynamic if first occurs during run time or can change in Dynamic if first occurs during run time or can change in

the course of program executionthe course of program execution Example (Java)Example (Java)

count = count + 5;count = count + 5;

Page 8: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

8

Type bindingsType bindings1.1. How the type is specifiedHow the type is specified

2.2. When the binding takes placeWhen the binding takes place Static Type BindingStatic Type Binding

Explicit and implicit declarations create static bindings to Explicit and implicit declarations create static bindings to typestypes

Explicit declarationExplicit declaration Statement in a program that lists variable names and Statement in a program that lists variable names and

specifies that they are a particular typespecifies that they are a particular type Implicit declarationImplicit declaration

Means of associating variables with types through default Means of associating variables with types through default conventions rather than declaration statementsconventions rather than declaration statements

Advantages: ConvenientAdvantages: Convenient Disadvantages: Detrimental to readability (prevent compiler Disadvantages: Detrimental to readability (prevent compiler

from detecting typographical/programmer errors)from detecting typographical/programmer errors)

5.4 The Concept of Binding 5.4 The Concept of Binding (cont.)(cont.)

Page 9: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

9

5.4 The Concept of Binding 5.4 The Concept of Binding (cont.)(cont.)

Dynamic type bindingDynamic type binding Type of variable is not specified by a declaration statement Type of variable is not specified by a declaration statement

(nor can it be determined by the spelling of its name)(nor can it be determined by the spelling of its name) Variable is bound to a type when assigned a value in the Variable is bound to a type when assigned a value in the

assignment statementassignment statement Advantage: Provides more programming flexibilityAdvantage: Provides more programming flexibility

Example (JavaScipt)Example (JavaScipt)List = [ 10.2, 3.5]; List = [ 10.2, 3.5]; List = 47;List = 47;

Disadvantage: Less reliable programs, cost of Disadvantage: Less reliable programs, cost of implementing dynamic attribute considerable in execution implementing dynamic attribute considerable in execution time, languages that have dynamic type binding for time, languages that have dynamic type binding for variables are usually implemented using pure interpreters variables are usually implemented using pure interpreters rather than compilers (takes 10x longer)rather than compilers (takes 10x longer)

Page 10: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

10

5.4 The Concept of Binding 5.4 The Concept of Binding (cont.)(cont.)

Type inferenceType inference Most types of expressions can be determined without Most types of expressions can be determined without

requiring programmer to specify types of variablesrequiring programmer to specify types of variables

General syntax of ML function:General syntax of ML function:

Fun Fun fucntion_name(formal parameters) = expression;fucntion_name(formal parameters) = expression;

Fun Fun circum(r)=3.14159 * r * r;circum(r)=3.14159 * r * r;fun times10(x) = 10 * x;

funfun square(x) = x * x; square(x) = x * x;

square(2.75);

fun square(x) : real = x * x;fun square(x) : real) = x * x;fun square(x) = (x : real) * x;fun square(x) = x * ( real : x);

Page 11: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

11

5.4 The Concept of Binding 5.4 The Concept of Binding (cont.)(cont.)

Storage bindings and lifetimesStorage bindings and lifetimes AllocationAllocation

Process of a memory cell (to which a variable is bound) being Process of a memory cell (to which a variable is bound) being taken from a pool of available memorytaken from a pool of available memory

DeallocationDeallocation Process of placing a memory cell that has been unbound back Process of placing a memory cell that has been unbound back

from a variable into the pool of available memory from a variable into the pool of available memory LifetimeLifetime

Time during which the variable is bound to a specific memory Time during which the variable is bound to a specific memory location (begins when bound, ends when unbound)location (begins when bound, ends when unbound)

4 categories, based on lifetime4 categories, based on lifetime1.1. StaticStatic

2.2. Stack-dynamicStack-dynamic

3.3. Explicit heap-dynamicExplicit heap-dynamic

4.4. Implicit heap-dynamicImplicit heap-dynamic

Page 12: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

12

5.4 The Concept of Binding 5.4 The Concept of Binding (cont.)(cont.)

Static variablesStatic variables Bound to memory cells before program execution begins and Bound to memory cells before program execution begins and

remain bound to same memory cells until program execution remain bound to same memory cells until program execution terminatesterminates

Stack-dynamic variablesStack-dynamic variables Storage bindings are created when their declaration statements Storage bindings are created when their declaration statements

elaborated, but whose types are statically boundelaborated, but whose types are statically bound Explicit heap-dynamic variablesExplicit heap-dynamic variables

Nameless (abstract) memory cells that are allocated and Nameless (abstract) memory cells that are allocated and deallocated by explicit run-time instructions specified by deallocated by explicit run-time instructions specified by programmer. These variables can only be referenced through programmer. These variables can only be referenced through pointer or reference variables. pointer or reference variables.

Implicit heap-dynamic variablesImplicit heap-dynamic variables Bound to heap storage only when they are assigned values, all Bound to heap storage only when they are assigned values, all

of their attributes are bound EVERY time they are assignedof their attributes are bound EVERY time they are assigned

Page 13: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

13

5.5 Scope5.5 Scope

Definition: Scope of a variable is the range of statements in which

the variable is visible. A variable is visible in a statement if it can be referenced

in that statement.

Different Types of Scoping Static Scoping Dynamic Scoping Global Scoping

Page 14: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

14

5.5 Scope (cont.)5.5 Scope (cont.)

Scope rules determine how references to variables declared outside the currently executing subprogram or blocks are associated with their declarations.

void sub( ) {int count;. . . while (…) {

int count;count++;. . . }

. . . }

Page 15: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

15

5.5 Scope (cont.)5.5 Scope (cont.)

Static ScopingStatic Scoping The scope of a variable is determined prior to execution The scope of a variable is determined prior to execution

of the program allowing the reader and compiler to of the program allowing the reader and compiler to determine the type of every variable.determine the type of every variable.

Dynamic ScopingDynamic Scoping The scope of a variable can only be determined at run The scope of a variable can only be determined at run

time since this scoping type is based on the calling time since this scoping type is based on the calling sequence of subprograms. sequence of subprograms.

Analyze subprograms to know the reference of a variable by determining the static parent and ancestors of the program unit.

Page 16: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

16

Ada Code example to illustrate Static and Dynamic Scoping

Procedure Big is nesting two procedures Sub1 and Sub2Procedure Big is nesting two procedures Sub1 and Sub2

procedure Big isprocedure Big is

X : Integer;X : Integer;

procedure Sub1 isprocedure Sub1 is

X : Integer;X : Integer;

begin ---- of Sub1begin ---- of Sub1

. . . . . .

end; of ---- of Sub1end; of ---- of Sub1

procedure Sub2 isprocedure Sub2 is

begin ---- of Sub2begin ---- of Sub2

. . . X . . . . . . X . . .

end; ---- of Sub2end; ---- of Sub2

begin ---- of Bigbegin ---- of Big

. . . . . .

end; ---- of Bigend; ---- of Big

Page 17: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

17

5.5 Scope (cont.)5.5 Scope (cont.)

Global scopingGlobal scoping The variable definition can occur outside the function. The variable definition can occur outside the function.

These definitions are global variables and can potentially These definitions are global variables and can potentially be visible in a given function.be visible in a given function.

Memory allocation differences between Memory allocation differences between Definitions and Declarations of variablesDefinitions and Declarations of variables Declarations

Variable types and attributes but NO allocation of storage Definitions

Variable types and attributes AND cause allocation of storage

Page 18: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

18

PHP code example to illustrate Global Scoping

$day = “Monday”;$month = “January”;

Function calendar( ) {$day = “Tuesday”;global $month;print “local day is $day <br />”;$gday = $GLOBALS[‘day’];print “global day is $gday <br />”;print “global month is $month <br />”;

}Calendar( );

local day is Tuesdayglobal day is MondayGlobal month is January

Page 19: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

19

5.7 Referencing Environments5.7 Referencing Environments

Referencing environmentReferencing environment Collection of all variables declared in its local scope plus the collection Collection of all variables declared in its local scope plus the collection

of variables of its ancestor scopes that are visible.of variables of its ancestor scopes that are visible.

procedure Example is A, B : Integer; . . . procedure Sub1 is X, Y : Integer; begin ---- of Sub1 . . . < ------ X and Y of Sub1, A and B of Example end; ---- of Sub1 procedure Sub2 is X : Integer; . . . procedure Sub3 is X : Integer begin ---- of Sub3 . . . < ------ X of Sub3, (X of Sub2 is hidden), A and B of Example end; ---- of Sub3

Page 20: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

20

5.8 Named Constants5.8 Named Constants

Named constantsNamed constants A variable that is bound to a value only onceA variable that is bound to a value only once Example: Pi = 3.14159Example: Pi = 3.14159

void example ( ) {int[ ] intList = new int[100];String[ ] strList = new String[100];for (index = 0; index < 100; index++) {. . . }

}

Average = sum / 100;

Page 21: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

21

5.8 Named Constants (cont.)5.8 Named Constants (cont.)

void example ( ) {final int len = 100;int[ ] intList = new int[len];String[ ] strList = new String[100];for (index = 0; index < len; index++) {. . . }

}

Average = sum / len;

Page 22: 1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010

22

QuestionsQuestions

What is the difference between static type binding What is the difference between static type binding and dynamic type binding?  Provide an application and dynamic type binding?  Provide an application for each.for each.

Give an example of a potential type inference error Give an example of a potential type inference error in ML and a possible "legal" definition alternative in ML and a possible "legal" definition alternative solution.solution.

Define a static variable and provide an advantage Define a static variable and provide an advantage and disadvantage to using it in a program.and disadvantage to using it in a program.

Give an example of a named constant and explain Give an example of a named constant and explain how it aids in program readability and reliability.how it aids in program readability and reliability.