lecture3-binding
lecture3-binding
// example C code
int x = 5;
if (y>0) {
int x = 7;
print(x);
}
Lifetime and Storage Management
• Declarations
• Introduce a name; give its type (if in a typed language)
• Definitions
• Fully define an entity
• Specify value for variables, function body for functions
• Common rules
• Declaration before use
• Definition before use
• Why might we care about these?
Declarations and Definitions
• Declarations
• Introduce a name; give its type (if in a typed language)
• Definitions
• Fully define an entity
• Specify value for variables, function body for functions
• Declaration before use
• Makes it possible to write a one-pass compiler
• When you call a function, you know its signature
• In C, this requires separating declarations from definitions to support
recursion
• Definition before use
• Avoids accessing an undefined variable
• Java relaxes both of these for classes, fields, and methods
• But not for local variables
Static Scoping
– What does this Java code print?
class Outer {
int x = 1;
class Inner {
int x = 2;
Most recent
void foo() { binding of x in
an enclosing
if (flag) {
scope
int x = 3;
}
System.out.println(“x = ” + x); // what do I print?
} } }
• With static (or lexical) scope rules, a scope is defined in terms of the lexical structure
of the program
– The determination of scopes can be made by the compiler
– Bindings for identifiers are resolved by examining code
– Typically, the most recent binding in an enclosing scope
– Most compiled languages, C and Pascal included, employ static scope rules
Scope Rules
• Several implementations
– Allocate all referencing environments on the heap, copy a pointer
into the closure
• This is what most functional language implementations do—with
optimizations when no closure will be created
val union : 'a set -> 'a set -> 'a set
end = struct
type 'a set = 'a list Private helper functions are
also hidden by leaving them
let make () = ... out of the signature