300 likes | 322 Views
Names, Scopes and Bindings. Names. Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Binding associates a names with an object A Name is an abstraction of an object Classes are type abstractions Variables are data abstractions
E N D
Names • Kinds of names • Variables, functions, classes, types, labels, blocks, operators, tasks, etc. • Binding associates a names with an object • A Name is an abstraction of an object • Classes are type abstractions • Variables are data abstractions • Subroutines are control abstractions • Name Spaces • separate lists of names, struct ids in C
Binding • Binding Times • Language Design time • Keywords • Built-in Types • Compile Time • Binding variables to locations in memory • Load Time • Static linking • Run Time • Interpreted Languages e.g., Smalltalk • Dynamic linking • Polymorphism • Late binding => flexibility • Early binding => safety
Object Lifetime • A short biography of an Object • Creation of Object – instantiation • Creation of Names – declaration • Binding Name and Object • Destruction of Bindings • Destruction of Objects • Storage Allocation Mechanisms • Static objects – exist throughout execution of program • Constants, global values, static members in C • static keyword overloaded, multiple meanings • Heap objects – explicitly created • Garbage collected or explicitly deleted • Stack objects – exist within a block
Stack Allocation • Function Calls • Compiler determines size of stack frame • Prologue and Epilog • Parameters • Local Variables • Temporary (compiler generated) variables • Bookkeeping information • Stack frame pushed onto stack when function is called at run-time • Stack frame popped off stack when function returns • Stack allocation for declarations in block statements • Advantages of Stack Allocation • Allocation is automatic • Reentrant – allows for recursive calls • Space & Time efficient • Guarantees no side effects
Heap Allocation • Heap is random access memory • Sequentially addressed memory • Requires Memory Management System • Allocation must be explicit • malloc() – in C; new in C++ & Java • Can be expensive • Deallocation can be explicit or Garbage Collected • Susceptible to Problems • Memory leaks • Memory fragmentation • Dangling references
Scope • Scope is the region over which a binding is active • Examples: • Function Scope – labels • Block (Local) Scope • File Scope in C & C++ • Package Scope in Java • Class Scope • Static (Lexical) scope – Binding at compile time • Dynamic scope – Binding at run-time
Static Scope • Most common: • C, C++, Java, etc. • Binding determined by (lexical) structure of program • void Foo (char x) { • char c = ‘a’; • Fum (x); • } • void Fum(char y) { • c = y; Error • }
Nested Subroutines • Supported in Pascal, Ada, ML • Useful for “helper” functions • function m return Integer is { • x is Integer; • function sub1 return Integer is { • x := 1 • } • sub1(); • return x; • } • Requires a static chain of pointers or a display to keep track of environments on the stack
Static Chains A() { B() { C() {} D() {} } E() {} } • Nested Calls: • A, E, B, D, C
Dynamic Scope • Scope determined at run-time • APL, Snobol, Perl • 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
Static vs Dynamic Scope • a : integer -- global declaration • procedure first • a := 1 • procedure second • a: integer • first() • a := 2 • if read_integer() > 0 • second() • else • first() • write_integer(a) • What is the result under Static Scope? • What is the result under Dynamic Scope?
Visibility • A Binding may be temporarily hidden by a more local binding. • Linkage – names must be exported to be visible • Hidden declarations may be referenced using a qualified name int x = 0; int y = Super.x;
Name Overloading • Same name used for more than one distinct function • Built-in operators • Example: 1.0 + 2.0 and 1 + 2 • Function (or operator) names resolved using actual argument types • Name Mangling in C++
Access Control • Declaration is in scope and not hidden, but access is controlled • Applies to class members • Private – only accessible in this class • Public – access available throughout scope • Protected – accessible in this class and its subclasses • Package – accessible in all classes in package
What’s in a Type • 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. • A Type System is a set of formal rules that defines a type, including rules for • Constructing a new instance of the type • Determining type equivalence between values • Determining type compatibility between values • Defining and applying operators
Type Declaration • Not all languages require explicit type delcaration: • Type implicit in name • Perl: $ => scalar, @ => array • Basic: $ => string • Type inferred from context • x + 1.0; • Type associated with values, rather than names • x := “abc”; x := 2.0; x + 1.0; • Explicit declaration may not be necessary, but: • Makes program easier to understand • Avoids common errors such as misspelling an identifier
Type Declaration (2) • What does a type declaration do? ais array (1..10) of Integer • Defines set of valid operations on a • Defines set of valid operations on elements of a • Establishes size of a in memory • Registers a in symbol table • Determines scope of a • May allocate storage and bind name to object
*1st, 2nd & 3rd Class values • First class values • Can be passed as parameters • Can be stored in variables • Second class values • Cannot be passed as parameters • Can be stored in variables • Third class values • Cannot be passed as parameters • Cannot be stored in variables
Type Checking • Use of incompatible types is called a “type clash” Example: a is Array (1..10) of Integer; a[20] := ‘a’; • Statically typed: • Type errors detectable at compile time • Most Algol-style languages • Dynamically typed • Type errors detected at run-time • Scheme, Smalltalk • Static typing is preferable but not always possible
Strong vs Weak Typing • Strongly typed Languages • Type rules strictly enforced at compile time • Ada, Java • Weakly typed languages • Possibly unsafe type conversion permitted • Assembly, C • Type Equivalence of composite types • Structural vs. Name equivalence • Type Compatibility • Coercion • Promotion • Polymorphism
*Type Semantics • Denotational Semantics • A type is a set of values • Operations are values of type • where and are type variables • Constructive • Built-in or constructed from built-in types • Everything reduces to built-in types and operations • Abstraction-based (Operational) • A type is a set of abstract operations
Type Inference • x = 1 + f(‘a’); • What is the type of f()? • What is the type of x? • How do we know?
Pragmas • A pragma is a message for the compiler • Pragma inline name – requests that function be compiled inline • Pragma Optimize (Time | Space | Off)
Union Types • The union type in C union u_if { int x; float f; } • Large enough to hold largest member • Either int or float, but which? • Programmer needs to keep track struct { int u_type; union { int ival; float fval; char* cval; } } values;
Discriminated Types in Ada • A record can have discriminants: • type IF is (Int, Float);type Int_Float (V : IF := Int) is recordcase V iswhen 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
More on Discriminated Records • Referencing a discriminanted type • Puzzle : Int_Float;…Puzzle := (Float, 1.0);F := Puzzle.Float_Val; -- OKI := Puzzle.Int_Val; -- raise exception…Puzzle.V := Int; -- not allowed!
More on Discriminated Records • Can make subtypes • subtype PuzzleI is puzzle (Int);-- this type only holds int values • 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”);