Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,

Similar presentations


Presentation on theme: "1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,"— Presentation transcript:

1 1 Names, Scopes and Bindings

2 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Binding associates a names with an object Binding associates a names with an object A Name is an abstraction of an object A Name is an abstraction of an object Classes are type abstractions Classes are type abstractions Variables are data abstractions Variables are data abstractions Subroutines are control abstractions Subroutines are control abstractions Name Spaces Name Spaces separate lists of names, struct ids in C separate lists of names, struct ids in C

3 3 Binding Binding Times Binding Times Language Design time Language Design time Keywords Keywords Built-in Types Built-in Types Compile Time Compile Time Binding variables to locations in memory Binding variables to locations in memory Load Time Load Time Static linking Static linking Run Time Run Time Interpreted Languages e.g., Smalltalk Interpreted Languages e.g., Smalltalk Dynamic linking Dynamic linking Polymorphism Polymorphism Late binding => flexibility Late binding => flexibility Early binding => safety Early binding => safety

4 4 Object Lifetime A short biography of an Object A short biography of an Object Creation of Object – instantiation Creation of Object – instantiation Creation of Names – declaration Creation of Names – declaration Binding Name and Object Binding Name and Object Destruction of Bindings Destruction of Bindings Destruction of Objects Destruction of Objects Storage Allocation Mechanisms Storage Allocation Mechanisms Static objects – exist throughout execution of program Static objects – exist throughout execution of program Constants, global values, static members in C Constants, global values, static members in C static keyword overloaded, multiple meanings static keyword overloaded, multiple meanings Heap objects – explicitly created Heap objects – explicitly created Garbage collected or explicitly deleted Garbage collected or explicitly deleted Stack objects – exist within a block Stack objects – exist within a block

5 5 Stack Allocation Function Calls Function Calls Compiler determines size of stack frame Compiler determines size of stack frame Prologue and Epilog Prologue and Epilog Parameters Parameters Local Variables Local Variables Temporary (compiler generated) variables Temporary (compiler generated) variables Bookkeeping information Bookkeeping information Stack frame pushed onto stack when function is called at run- time Stack frame pushed onto stack when function is called at run- time Stack frame popped off stack when function returns Stack frame popped off stack when function returns Stack allocation for declarations in block statements Stack allocation for declarations in block statements Advantages of Stack Allocation Advantages of Stack Allocation Allocation is automatic Allocation is automatic Reentrant – allows for recursive calls Reentrant – allows for recursive calls Space & Time efficient Space & Time efficient Guarantees no side effects Guarantees no side effects

6 6 Heap Allocation Heap is random access memory Heap is random access memory Sequentially addressed memory Sequentially addressed memory Requires Memory Management System Requires Memory Management System Allocation must be explicit Allocation must be explicit malloc () – in C; new in C++ & Java malloc () – in C; new in C++ & Java Can be expensive Can be expensive Deallocation can be explicit or Garbage Collected Deallocation can be explicit or Garbage Collected Susceptible to Problems Susceptible to Problems Memory leaks Memory leaks Memory fragmentation Memory fragmentation Dangling references Dangling references

7 7 Scope Scope is the region over which a binding is active Scope is the region over which a binding is active 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 Scope Class Scope Static (Lexical) scope – Binding at compile time Static (Lexical) scope – Binding at compile time Dynamic scope – Binding at run-time Dynamic scope – Binding at run-time

8 8 Static Scope Most common: Most common: C, C++, Java, etc. C, C++, Java, etc. Binding determined by (lexical) structure of program Binding determined by (lexical) structure of 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;  Error c = y;  Error }

9 9 Nested Subroutines Supported in Pascal, Ada, ML Supported in Pascal, Ada, ML Useful for “helper” functions Useful for “helper” functions function m return Integer is { function m return Integer is { x is Integer; x is Integer; function sub1 return Integer is { function sub1 return Integer is { x := 1 x := 1 } sub1(); sub1(); return x; return x; } Requires a static chain of pointers or a display to keep track of environments on the stack Requires a static chain of pointers or a display to keep track of environments on the stack

10 10 Static Chains A() { B() { B() { C() {} C() {} D() {} D() {} } E() {} E() {}} Nested Calls: Nested Calls: A, E, B, D, C A, E, B, D, C C D B E A

11 11 Dynamic Scope Scope determined at run-time Scope determined at run-time APL, Snobol, Perl APL, Snobol, Perl A variable local to a calling function will be available in the called function. A variable local to a calling function will be available in the called function. Requires dynamic chain of pointers to keep track of calling environments Requires dynamic chain of pointers to keep track of calling environments

12 12 Static vs Dynamic Scope 1. a : integer -- global declaration 2. procedure first 3. a := 1 4. procedure second 5. a: integer 6. first() 7. a := 2 8. if read_integer() > 0 9. second() 10. else 11. first() 12. 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?

13 13 Visibility A Binding may be temporarily hidden by a more local binding. A Binding may be temporarily hidden by a more local binding. Linkage – names must be exported to be visible Linkage – names must be exported to be visible Hidden declarations may be referenced using a qualified name Hidden declarations may be referenced using a qualified name int x = 0; int y = Super.x;

14 14 Name Overloading Same name used for more than one distinct function Same name used for more than one distinct function Built-in operators Built-in operators Example: 1.0 + 2.0 and 1 + 2 Example: 1.0 + 2.0 and 1 + 2 Function (or operator) names resolved using actual argument types Function (or operator) names resolved using actual argument types Name Mangling in C++ Name Mangling in C++

15 15 Access Control Declaration is in scope and not hidden, but access is controlled Declaration is in scope and not hidden, but access is controlled Applies to class members Applies to class members Private – only accessible in this class Private – only accessible in this class Public – access available throughout scope Public – access available throughout scope Protected – accessible in this class and its subclasses Protected – accessible in this class and its subclasses Package – accessible in all classes in package Package – accessible in all classes in package

16 16 Type Checking

17 17 What’s in a Type A type is (possibly infinite) set of values and the set of valid operations on those values A type is (possibly infinite) set of values and the set of valid operations on those values Integer – infinite set of discrete values and operators, e.g., succ(), pred(), +, -, *, /, etc. Integer – infinite set of discrete values and operators, e.g., succ(), pred(), +, -, *, /, etc. A Type System is a set of formal rules that defines a type, including rules for A Type System is a set of formal rules that defines a type, including rules for Constructing a new instance of the type Constructing a new instance of the type Determining type equivalence between values Determining type equivalence between values Determining type compatibility between values Determining type compatibility between values Defining and applying operators Defining and applying operators

18 18 Type Declaration Not all languages require explicit type delcaration: Not all languages require explicit type delcaration: Type implicit in name Type implicit in name Perl: $ => scalar, @ => array Perl: $ => scalar, @ => array Basic: $ => string Basic: $ => string Type inferred from context Type inferred from context x + 1.0; x + 1.0; Type associated with values, rather than names Type 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, but: Explicit declaration may not be necessary, but: Makes program easier to understand Makes program easier to understand Avoids common errors such as misspelling an identifier Avoids common errors such as misspelling an identifier

19 19 Type Declaration (2) What does a type declaration do? What does a type declaration do? a is array (1..10) of Integer Defines set of valid operations on a Defines set of valid operations on a Defines set of valid operations on elements of a Defines set of valid operations on elements of a Establishes size of a in memory Establishes size of a in memory Registers a in symbol table Registers a in symbol table Determines scope of a Determines scope of a May allocate storage and bind name to object May allocate storage and bind name to object

20 20 *1 st, 2 nd & 3 rd Class values First class values First class values Can be passed as parameters Can be passed as parameters Can be stored in variables Can be stored in variables Second class values Second class values Cannot be passed as parameters Cannot be passed as parameters Can be stored in variables Can be stored in variables Third class values Third class values Cannot be passed as parameters Cannot be passed as parameters Cannot be stored in variables Cannot be stored in variables

21 21 Type Checking Use of incompatible types is called a “type clash” Use of incompatible types is called a “type clash” Example: a is Array (1..10) of Integer; a[20] := ‘a’; Statically typed: Statically typed: Type errors detectable at compile time Type errors detectable at compile time Most Algol-style languages Most Algol-style languages Dynamically typed Dynamically typed Type errors detected at run-time Type errors detected at run-time Scheme, Smalltalk Scheme, Smalltalk Static typing is preferable but not always possible Static typing is preferable but not always possible

22 22 Strong vs Weak Typing Strongly typed Languages Strongly typed Languages Type rules strictly enforced at compile time Type rules strictly enforced at compile time Ada, Java Ada, Java Weakly typed languages Weakly typed languages Possibly unsafe type conversion permitted Possibly unsafe type conversion permitted Assembly, C Assembly, C Type Equivalence of composite types Type Equivalence of composite types Structural vs. Name equivalence Structural vs. Name equivalence Type Compatibility Type Compatibility Coercion Coercion Promotion Promotion Polymorphism Polymorphism

23 23 *Type Semantics Denotational Semantics Denotational 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  and  are type variables where  and  are type variables Constructive Constructive Built-in or constructed from built-in types Built-in or constructed from built-in types Everything reduces to built-in types and operations Everything reduces to built-in types and operations Abstraction-based (Operational) Abstraction-based (Operational) A type is a set of abstract operations A type is a set of abstract operations

24 24 Type 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?

25 25 A little more Ada

26 26 Pragmas A pragma is a message for the compiler A pragma is a message for the compiler Pragma inline name – requests that function be compiled inline Pragma inline name – requests that function be compiled inline Pragma Optimize (Time | Space | Off) Pragma Optimize (Time | Space | Off)

27 27 Union Types The union type in C The union type in C union u_if { int x; float f; } Large enough to hold largest member Large enough to hold largest member Either int or float, but which? Either int or float, but which? Programmer needs to keep track Programmer needs to keep track struct { int u_type; union { union { int ival; int ival; float fval; float fval; char* cval; char* cval; } } values;

28 28 Discriminated Types in Ada A record can have discriminants: A record can have discriminants: type IF is (Int, Float); type Int_Float (V : IF := Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; type IF is (Int, Float); type Int_Float (V : IF := Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; Now the value of the discriminant V shows what type is currently present Now the value of the discriminant V shows what type is currently present

29 29 More on Discriminated Records Referencing a discriminanted type Referencing a discriminanted type Puzzle : Int_Float; … Puzzle := (Float, 1.0); F := Puzzle.Float_Val; -- OK I := Puzzle.Int_Val; -- raise exception … Puzzle.V := Int; -- not allowed! Puzzle : Int_Float; … Puzzle := (Float, 1.0); F := Puzzle.Float_Val; -- OK I := Puzzle.Int_Val; -- raise exception … Puzzle.V := Int; -- not allowed!

30 30 More on Discriminated Records Can make subtypes Can make subtypes subtype PuzzleI is puzzle (Int); -- this type only holds int values subtype PuzzleI is puzzle (Int); -- this type only holds int values Can dimension arrays from discriminant: Can dimension arrays from discriminant: Subtype Vlen is Integer range 1.. 10; type Vstr (Vlen : Integer := 0) is record Data : String (1.. Vlen); end record; VV : Vstr := (5, “hello”); Subtype Vlen is Integer range 1.. 10; type Vstr (Vlen : Integer := 0) is record Data : String (1.. Vlen); end record; VV : Vstr := (5, “hello”);


Download ppt "1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,"

Similar presentations


Ads by Google