03 Binding
03 Binding
// example C code
int x = 5;
if (y>0) {
int x = 7;
print(x);
}
Lifetime and Storage Management
• Why a stack? C
D
–allocate space for recursive routines
(not necessary in FORTRAN – no recursion) B
–reuse space (in all programming languages)
A
• 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
apply_to_2 plus3 => 5
• Let’s look at how this executes
(on the whiteboard)
Closures
• A closure is a pair of a function and a referencing
environment
fun k -> n + k
plus_3
n=3
• 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
Private helper functions are
type 'a set = 'a list also hidden by leaving them
let make () = ... out of the signature
let union_helper(...) = ...
let union(set1, set2) = union_helper(...)
end
Hiding Names with Modules
• Related facilities in other languages
• Java: hide elements with private keyword
• C: put public members into header file