1 names, scopes and bindings. 2 names kinds of names kinds of names variables, functions, classes,...
Post on 20-Dec-2015
219 views
TRANSCRIPT
11
Names, Scopes and Names, Scopes and BindingsBindings
22
NamesNames Kinds of names Kinds of names
Variables, functions, classes, types, Variables, functions, classes, types, labels, blocks, operators, tasks, etc. labels, blocks, operators, tasks, etc.
Binding associates a names with an Binding associates a names with an objectobject
A Name is an abstraction of an objectA Name is an abstraction of an object Classes are type abstractionsClasses are type abstractions Variables are data abstractionsVariables are data abstractions Subroutines are control abstractionsSubroutines are control abstractions
Name Spaces Name Spaces separate lists of names, separate lists of names, structstruct ids in C ids in C
33
BindingBinding Binding TimesBinding Times
Language Design timeLanguage Design time KeywordsKeywords Built-in TypesBuilt-in Types
Compile TimeCompile Time Binding variables to locations in memoryBinding variables to locations in memory
Load TimeLoad Time Static linking Static linking
Run TimeRun Time Interpreted Languages e.g., SmalltalkInterpreted Languages e.g., Smalltalk Dynamic linkingDynamic linking PolymorphismPolymorphism
Late binding => flexibilityLate binding => flexibility Early binding => safetyEarly binding => safety
44
Object LifetimeObject Lifetime A short biography of an ObjectA short biography of an Object
Creation of Object – instantiation Creation of Object – instantiation Creation of Names – declaration Creation of Names – declaration Binding Name and ObjectBinding Name and Object Destruction of BindingsDestruction of Bindings Destruction of ObjectsDestruction of Objects
Storage Allocation MechanismsStorage Allocation Mechanisms Static objects – exist throughout execution of Static objects – exist throughout execution of
programprogram Constants, global values, static members in CConstants, global values, static members in C staticstatic keyword overloaded, multiple meanings keyword overloaded, multiple meanings
Heap objects – explicitly createdHeap objects – explicitly created Garbage collected or explicitly deleted Garbage collected or explicitly deleted
Stack objects – exist within a blockStack objects – exist within a block
55
Stack AllocationStack Allocation Function CallsFunction Calls
Compiler determines size of stack frameCompiler determines size of stack frame Prologue and EpilogPrologue and Epilog Parameters Parameters Local VariablesLocal Variables Temporary (compiler generated) variablesTemporary (compiler generated) variables Bookkeeping informationBookkeeping information
Stack frame pushed onto stack when function is called at Stack frame pushed onto stack when function is called at run-timerun-time
Stack frame popped off stack when function returnsStack frame popped off stack when function returns Stack allocation for declarations in block Stack allocation for declarations in block
statementsstatements Advantages of Stack AllocationAdvantages of Stack Allocation
Allocation is automatic Allocation is automatic Reentrant – allows for recursive callsReentrant – allows for recursive calls Space & Time efficientSpace & Time efficient Guarantees no side effectsGuarantees no side effects
66
Heap AllocationHeap Allocation Heap is random access memoryHeap is random access memory
Sequentially addressed memorySequentially addressed memory Requires Memory Management System Requires Memory Management System
Allocation must be explicit Allocation must be explicit mallocmalloc() – in C; () – in C; newnew in C++ & Java in C++ & Java Can be expensiveCan be expensive Deallocation can be explicit or Garbage Deallocation can be explicit or Garbage
CollectedCollected Susceptible to Problems Susceptible to Problems
Memory leaksMemory leaks Memory fragmentationMemory fragmentation Dangling referencesDangling references
77
Scope Scope Scope is the region over which a binding is Scope is the region over which a binding is
activeactive Examples:Examples:
Function Scope – labels Function Scope – labels Block (Local) Scope Block (Local) Scope File Scope in C & C++File Scope in C & C++ Package Scope in Java Package Scope in Java Class ScopeClass Scope
Static (Lexical) scope – Binding at compile Static (Lexical) scope – Binding at compile timetime
Dynamic scope – Binding at run-timeDynamic scope – Binding at run-time
88
Static ScopeStatic Scope Most common: Most common:
C, C++, Java, etc.C, C++, Java, etc. Binding determined by (lexical) structure Binding determined by (lexical) structure
of programof program void Foo (char x) {void Foo (char x) { char c = ‘a’;char c = ‘a’; Fum (x);Fum (x); }} void Fum(char y) {void Fum(char y) { c = y; c = y; Error Error }}
99
Nested SubroutinesNested Subroutines
Supported in Pascal, Ada, MLSupported in Pascal, Ada, ML Useful for “helper” functions Useful for “helper” functions functionfunction m m return Integer isreturn Integer is { {
x x is Integeris Integer;; functionfunction sub1 sub1 return Integer isreturn Integer is { {
x := 1x := 1 }} sub1();sub1(); returnreturn x; x;
}} Requires a static chain of pointers or a display to Requires a static chain of pointers or a display to
keep track of environments on the stackkeep track of environments on the stack
1010
Static ChainsStatic Chains
A() {A() {
B() {B() {
C() {}C() {}
D() {}D() {}
}}
E() {}E() {}
}} Nested Calls:Nested Calls:
A, E, B, D, CA, E, B, D, C
CC
DD
BB
EE
AA
1111
Dynamic ScopeDynamic Scope
Scope determined at run-timeScope determined at run-time APL, Snobol, PerlAPL, Snobol, Perl
A variable local to a calling function A variable local to a calling function will be available in the called will be available in the called function.function.
Requires dynamic chain of pointers Requires dynamic chain of pointers to keep track of calling environmentsto keep track of calling environments
1212
Static vs Dynamic ScopeStatic vs Dynamic Scope1.1. a : integer -- global declarationa : integer -- global declaration2.2. procedure firstprocedure first3.3. a := 1a := 14.4. procedure secondprocedure second5.5. a: integera: integer6.6. first()first()7.7. a := 2a := 28.8. if read_integer() > 0if read_integer() > 09.9. second()second()10.10. elseelse11.11. first()first()12.12. write_integer(a) write_integer(a) What is the result under Static Scope?What is the result under Static Scope? What is the result under Dynamic Scope?What is the result under Dynamic Scope?
1313
VisibilityVisibility
A Binding may be temporarily hidden A Binding may be temporarily hidden by a more local binding.by a more local binding.
Linkage – names must be exported Linkage – names must be exported to be visibleto be visible
Hidden declarations may be Hidden declarations may be referenced using a referenced using a qualified namequalified nameint x = 0;int x = 0;int y = Super.x; int y = Super.x;
1414
Name OverloadingName Overloading
Same name used for more than one Same name used for more than one distinct functiondistinct function
Built-in operatorsBuilt-in operators Example: 1.0 + 2.0 and 1 + 2Example: 1.0 + 2.0 and 1 + 2
Function (or operator) names Function (or operator) names resolved using actual argument resolved using actual argument typestypes Name Mangling in C++Name Mangling in C++
1515
Access ControlAccess Control Declaration is in scope and not Declaration is in scope and not
hidden, but access is controlledhidden, but access is controlled Applies to class membersApplies to class members
Private – only accessible in Private – only accessible in thisthis class class Public – access available throughout scopePublic – access available throughout scope Protected – accessible in this class and its Protected – accessible in this class and its
subclassessubclasses Package – accessible in all classes in Package – accessible in all classes in
packagepackage
1616
Type CheckingType Checking
1717
What’s in a TypeWhat’s in a Type
A type is (possibly infinite) set of values and A type is (possibly infinite) set of values and the set of valid operations on those valuesthe set of valid operations on those values
Integer – infinite set of discrete values and operators, Integer – infinite set of discrete values and operators, e.g., succ(), pred(), +, -, *, /, etc.e.g., succ(), pred(), +, -, *, /, etc.
A Type System is a set of formal rules that A Type System is a set of formal rules that defines a type, including rules for defines a type, including rules for Constructing a new instance of the typeConstructing a new instance of the type Determining type equivalence between valuesDetermining type equivalence between values Determining type compatibility between values Determining type compatibility between values Defining and applying operators Defining and applying operators
1818
Type DeclarationType Declaration Not all languages require explicit type Not all languages require explicit type
delcaration:delcaration: Type implicit in name Type implicit in name
Perl: $ => scalar, @ => arrayPerl: $ => scalar, @ => array Basic: $ => stringBasic: $ => string
Type inferred from contextType inferred from context x + 1.0;x + 1.0;
Type associated with values, rather than namesType associated with values, rather than names x := “abc”; x := 2.0; x + 1.0; x := “abc”; x := 2.0; x + 1.0;
Explicit declaration may not be necessary, Explicit declaration may not be necessary, but: but: Makes program easier to understand Makes program easier to understand Avoids common errors such as misspelling an Avoids common errors such as misspelling an
identifieridentifier
1919
Type Declaration (2)Type Declaration (2)
What does a type declaration do?What does a type declaration do?aa is arrayis array (1..10) (1..10) of Integerof Integer Defines set of valid operations on Defines set of valid operations on aa Defines set of valid operations on elements of Defines set of valid operations on elements of aa
Establishes size of Establishes size of aa in memory in memory Registers Registers aa in symbol table in symbol table Determines scope of Determines scope of aa May allocate storage and bind name to objectMay allocate storage and bind name to object
2020
*1*1stst, 2, 2nd nd & 3& 3rdrd Class values Class values
First class valuesFirst class values Can be passed as parametersCan be passed as parameters Can be stored in variablesCan be stored in variables
Second class valuesSecond class values Cannot be passed as parametersCannot be passed as parameters Can be stored in variablesCan be stored in variables
Third class valuesThird class values Cannot be passed as parametersCannot be passed as parameters Cannot be stored in variablesCannot be stored in variables
2121
Type CheckingType Checking
Use of incompatible types is called a “type Use of incompatible types is called a “type clash”clash”Example: Example: a is Array (1..10) of Integer;a is Array (1..10) of Integer;
a[20] := ‘a’;a[20] := ‘a’; Statically typed: Statically typed:
Type errors detectable at compile time Type errors detectable at compile time Most Algol-style languagesMost Algol-style languages
Dynamically typedDynamically typed Type errors detected at run-timeType errors detected at run-time Scheme, Smalltalk Scheme, Smalltalk
Static typing is preferable but not always Static typing is preferable but not always possiblepossible
2222
Strong vs Weak TypingStrong vs Weak Typing Strongly typed LanguagesStrongly typed Languages
Type rules strictly enforced at compile timeType rules strictly enforced at compile time Ada, JavaAda, Java
Weakly typed languagesWeakly typed languages Possibly unsafe type conversion permitted Possibly unsafe type conversion permitted Assembly, CAssembly, C
Type Equivalence of composite typesType Equivalence of composite types Structural vs. Name equivalenceStructural vs. Name equivalence
Type CompatibilityType Compatibility CoercionCoercion PromotionPromotion PolymorphismPolymorphism
2323
*Type Semantics*Type Semantics
Denotational SemanticsDenotational Semantics A type is a set of values A type is a set of values Operations are values of type Operations are values of type where where and and are type variables are type variables
ConstructiveConstructive Built-in or constructed from built-in typesBuilt-in or constructed from built-in types Everything reduces to built-in types and Everything reduces to built-in types and
operationsoperations Abstraction-based (Operational)Abstraction-based (Operational)
A type is a set of abstract operationsA type is a set of abstract operations
2424
Type InferenceType Inference
x = 1 + f(‘a’);x = 1 + f(‘a’); What is the type of f()? What is the type of f()? What is the type of x? What is the type of x? How do we know?How do we know?
2525
A little more AdaA little more Ada
2626
PragmasPragmas
A pragma is a message for the A pragma is a message for the compilercompiler Pragma inlinePragma inline name – requests that name – requests that
function be compiled inlinefunction be compiled inline Pragma OptimizePragma Optimize ( (TimeTime | | SpaceSpace | | OffOff))
2727
Union TypesUnion Types The union type in CThe union type in C
union u_if { int x; float f; }union u_if { int x; float f; } Large enough to hold largest memberLarge enough to hold largest member Either int or float, but which?Either int or float, but which?
Programmer needs to keep trackProgrammer needs to keep trackstruct {struct {
int u_type;int u_type; union {union {
int ival;int ival; float fval;float fval; char* cval;char* cval; }}} values;} values;
2828
Discriminated Types in AdaDiscriminated Types in Ada
A record can have discriminants:A record can have discriminants: typetype IF IF isis (Int, Float); (Int, Float);
typetype Int_Float (V : IF := Int) Int_Float (V : IF := Int) is recordis record casecase V V isis whenwhen Int => Int_Val : Integer; Int => Int_Val : Integer; whenwhen Float => Float_Val : Float; Float => Float_Val : Float; end caseend case;;end recordend record;;
Now the value of the discriminant V Now the value of the discriminant V shows what type is currently presentshows what type is currently present
2929
More on Discriminated More on Discriminated RecordsRecords
Referencing a discriminanted typeReferencing a discriminanted type Puzzle : Int_Float;Puzzle : Int_Float;
……Puzzle := (Float, 1.0);Puzzle := (Float, 1.0);F := Puzzle.Float_Val; F := Puzzle.Float_Val; -- OK-- OKI := Puzzle.Int_Val; I := Puzzle.Int_Val; -- raise exception-- raise exception……Puzzle.V := Int; Puzzle.V := Int; -- not allowed! -- not allowed!
3030
More on Discriminated More on Discriminated RecordsRecords
Can make subtypesCan make subtypes subtypesubtype PuzzleI PuzzleI isis puzzle (Int); puzzle (Int);
-- this type only holds int values-- this type only holds int values Can dimension arrays from discriminant:Can dimension arrays from discriminant:
Subtype Vlen is Integer range 1 .. 10;Subtype Vlen is Integer range 1 .. 10;type Vstr (Vlen : Integer := 0) is recordtype Vstr (Vlen : Integer := 0) is record Data : String (1 .. Vlen); Data : String (1 .. Vlen);end record;end record;VV : Vstr := (5, “hello”);VV : Vstr := (5, “hello”);