Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
SCOPE, FUNCTION CALLS AND STORAGE MANAGEMENT
Topics
Block-‐structured languages and stack storage In-‐line Blocks o ac5va5on records o storage for local, global variables
First-‐order func5ons o parameter passing o tail recursion and itera5on
Higher-‐order func5ons o devia5ons from stack discipline o language expressiveness => implementa5on complexity
Block-‐Structured Languages
Nested blocks, local variables o Example { int x = 2;
{ int y = 3; x = y+2;
} }
o Storage management ! Enter block: allocate space for variables ! Exits block: some or all space may be deallocated
new variables declared in nested blocks
inner block
outer block local variable
global variable
Examples
Blocks in common languages o C, { … } o Algol begin … end o ML let … in … end
Two forms of blocks o In-‐line blocks o Blocks associated with func5ons or procedures
Topic: block-‐based memory management, access to local variables, parameters, global variables
* JavaScript functions provide blocks
Simplified Machine Model
Registers
Environment Pointer
Program Counter
Data Code
Heap
Stack
Interested in Memory Mgmt Only
Registers, Code segment, Program counter o Ignore registers o Details of instruc5on set will not maWer
Data Segment o Stack contains data related to block entry/exit
o Heap contains data of varying life5me o Environment pointer points to current stack posi5on
! Block entry: add new ac5va5on record to stack ! Block exit: remove most recent ac5va5on record
Some basic concepts
Scope o Region of program text where declara5on is visible
Life5me o Period of 5me when loca5on is allocated to program
• Inner declaration of x hides outer one. • Called “hole in scope” • Lifetime of outer x includes time when
inner block is executed • Lifetime ≠ scope • Lines indicate “contour model” of scope.
{ int x = … ; { int y = … ; { int x = … ; …. }; };
};
In-‐line Blocks
Ac5va5on record o Data structure stored on run-‐5me stack o Contains space for local variables
Example
May need space for variables and intermediate results like (x+y), (x-y)
{ int x=0;
int y=x+1;
{ int z=(x+y)*(x-y);
};
};
Push record with space for x, y Set values of x, y Push record for inner block Set value of z Pop record for inner block Pop record for outer block
Ac5va5on record for in-‐line block
Control link o pointer to previous record on stack
Push record on stack: o Set new control link to point to old env ptr
o Set env ptr to new record
Pop record off stack o Follow control link of current record to reset environment pointer
Control link
Local variables
Intermediate results
Control link
Local variables
Intermediate results
Environment Pointer
Can be optimized away, but assume not for purpose of discussion.
Example
{ int x=0;
int y=x+1;
{ int z=(x+y)*(x-y);
};
};
Push record with space for x, y Set values of x, y Push record for inner block Set value of z Pop record for inner block Pop record for outer block
Control link x y
0 1
x+y x-y
Environment Pointer
1 -1
Control link z -1
Scoping rules
Global and local variables { int x=0;
int y=x+1;
{ int z=(x+y)*(x-y);
};
};
• x, y are local to outer block • z is local to inner bock • x, y are global to inner block
◆ Static scope • global refers to declaration in closest enclosing block
◆ Dynamic scope • global refers to most recent activation record
These are same until we consider function calls.
Func5ons and procedures
Syntax of procedures (Algol) and func5ons (C) procedure P (<pars>) <type> func5on f(<pars>) begin { <local vars> <local vars> <proc body> <func5on body> end; }
Ac5va5on record must include space for
• parameters • return address • local variables,
intermediate results
• return value (an intermediate result)
• location to put return value on function exit
Ac5va5on record for func5on
Return address o Loca5on of code to execute on func5on return
Return-‐result address o Address in ac5va5on record of calling block to receive return address
Parameters o Loca5ons to contain data from calling block
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return-result addr
Example
Func5on fact(n) = if n<= 1 then 1 else n * fact(n-‐1) o Return result address o loca5on to put fact(n)
Parameter o set to value of n by calling sequence
Intermediate result o loca5ons to contain value of fact(n-‐1)
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return result addr
Control link
fact(n-1) n
Return-result addr 3
fact(3)
Func5on call
Return address omiWed; would be ptr into code segment
Control link
fact(n-1) n
Return-result addr 2
fact(2)
fact(n) = if n<= 1 then 1 else n * fact(n-1)
Control link
fact(n-1) n
Return-result addr k
fact(k)
Environment Pointer
Control link
fact(n-1) n
Return-result addr 1
fact(1)
Function return next slide →
Func5on return
Control link
fact(n-1) n
Return result addr 3
fact(3)
Control link
fact(n-1) n
Return result addr
1 2
fact(2)
Control link
fact(n-1) n
Return result addr 1
fact(1)
fact(n) = if n<= 1 then 1 else n * fact(n-1)
Control link
fact(n-1) n
Return result addr
2 3
fact(3)
Control link
fact(n-1) n
Return result addr
1 2
fact(2)
Topics for first-‐order func5ons
Parameter passing o pass-‐by-‐value: copy value to new ac5va5on record o pass-‐by-‐reference: copy ptr to new ac5va5on record Access to global variables o global variables are contained in an ac5va5on record higher “up” the stack
Tail recursion o an op5miza5on for certain recursive func5ons
See this yourself: write factorial and run under debugger
Parameter passing
General terminology: L-‐values and R-‐values o Assignment y := x+3
! Iden5fier on led refers to loca5on, called its L-‐value ! Iden5fier on right refers to contents, called R-‐value
Pass-‐by-‐reference o Place L-‐value (address) in ac5va5on record o Func5on can assign to variable that is passed
Pass-‐by-‐value o Place R-‐value (contents) in ac5va5on record o Func5on cannot change value of caller’s variable o Reduces aliasing (alias: two names refer to same loc)
Example
function f (x) = { x = x+1; return x; } var y = 0; print (f(y)+y);
pseudo-code activation records
f(y) y 0
Control link
x Return result addr
•
f(y)
f(y) y 0
Control link
x Return result addr
0
f(y)
Access to global variables
Two possible scoping conven5ons o Sta5c scope: refer to closest enclosing block o Dynamic scope: most recent ac5va5on record on stack
Example var x=1; function g(z) { return x+z; } function f(y) { var x = y+1; return g(y*x); } f(3);
x 1
x 4 y 3
z 12
outer block
f(3)
g(12)
Which x is used for expression x+z ?
Ac5va5on record for sta5c scope
Control link o Link to ac5va5on record of previous (calling) block
Access link o Link to ac5va5on record of closest enclosing block in program text
Difference o Control link depends on dynamic behavior of prog
o Access link depends on sta5c form of program text
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return result addr
Access link
Complex nes5ng structure
var x=1; function g(z) { return x+z; } function f(y) { var x = y+1; return g(y*x); } f(3);
function m(…) { var x=1; … function n( … ){ function g(z) { return x+z; } … { … function f(y) { var x = y+1; return g(y*x); } … f(3); … } … n( … ) …} … m(…)
Simplify to
Simplified code has same block nesting, if we follow convention that each declaration begins a new block.
Sta5c scope with access links
Use access link to find global variable: ! Access link is always set to frame of closest enclosing lexical block
! For func5on body, this is block that contains func5on declara5on
var x=1; function g(z) = { return x+z; } function f(y) = { var x = y+1; return g(y*x); } f(3);
x 1
x 4 y 3
z 12
outer block
f(3)
g(12) control link access link
g …
f …
control link access link
control link access link
access link control link
Higher-‐Order Func5ons
Language features o Func5ons passed as arguments o Func5ons that return func5ons from nested blocks o Need to maintain environment of func5on
Simpler case o Func5on passed as argument o Need pointer to ac5va5on record “higher up” in stack
More complicated second case o Func5on returned as result of func5on call o Need to keep ac5va5on record of returning func5on
Pass func5on as argument
int x = 4; fun f(y) = x*y; fun g(h) = let int x=7 in h(3) + x; g(f);
There are two declara5ons of x Which one is used for each occurrence of x?
{ var x = 4; { function f(y) {return x*y}; { function g(h) { var x = 7; return h(3) + x; }; g(f); } } }
Haskell Pseudo-JavaScript
Sta5c Scope for Func5on Argument
int x = 4; fun f(y) = x*y;
fun g(h) = let
int x=7 in h(3) + x;
g(f);
x 4
h
y 3
f
g
Code for f
Code for g g(f)
h(3)
x * y
x 7
follow access link local var
How is access link for h(3) set?
Sta5c Scope for Func5on Argument
{ var x = 4; { func5on f(y) {return x*y};
{ func5on g(h) {
int x=7;
return h(3) + x; };
g(f); } } }
x 4
h
y 3
f
g
Code for f
Code for g g(f)
h(3)
x * y
x 7
follow access link local var
How is access link for h(3) set?
Closures
Func5on value is pair closure = 〈env, code 〉 When a func5on represented by a closure is called, o Allocate ac5va5on record for call (as always)
o Set the access link in the ac5va5on record using the environment pointer from the closure
Func5on Argument and Closures
int x = 4;
fun f(y) = x*y;
fun g(h) =
let int x=7
in
h(3) + x;
g(f);
x 4
access link set from closure
Code for f
f access
Run-time stack with access links
Code for g
h(3) y 3
access
g(f) h
access
x 7
g access
{ var x = 4;
{ function f(y){return x*y};
{ function g(h) {
int x=7;
return h(3)+x;
};
g(f);
}}}
Func5on Argument and Closures
x 4
access link set from closure
Code for f
f access
Run-time stack with access links
Code for g
h(3) y 3
access
g(f) h
access
x 7
g access
Summary: Func5on Arguments
Use closure to maintain a pointer to the sta5c environment of a func5on body
When called, set access link from closure
All access links point “up” in stack o May jump past ac5v records to find global vars
o S5ll deallocate ac5v records using stack (lifo) order
Return Func5on as Result
Language feature o Func5ons that return “new” func5ons o Need to maintain environment of func5on Example func5on compose(f,g) {return func5on(x) { return g(f (x)) }}; Func5on “created” dynamically o expression with free variables
values are determined at run 5me o func5on value is closure = 〈env, code〉 o code not compiled dynamically (in most languages)
Example: Return fctn with private state
fun mk_counter (init : int) = let val count = ref init
fun counter(inc:int) =
(count := !count + inc; !count) in counter end;
val c = mk_counter(1);
c(2) + c(2);
• Function to “make counter” returns a closure
• How is correct value of count determined in c(2) ?
ML
Example: Return fctn with private state
func5on mk_counter (init) { var count = init;
func5on counter(inc) {count=count+inc; return count}; return counter};
var c = mk_counter(1); c(2) + c(2);
Func5on to “make counter” returns a closure How is correct value of count determined in call c(2) ?
JS
Func5on Results and Closures fun mk_counter (init : int) = let val count = ref init
fun counter(inc:int) = (count := !count + inc; !count) in counter end
end; val c = mk_counter(1); c(2) + c(2);
c access
Code for counter
Code for mk_counter
c(2) access inc 2
1 mk_counter(1)
count init 1
access
counter
mk_c
Call changes cell value from 1 to 3
3
ML
Func5on Results and Closures
func5on mk_counter (init) {
var count = init;
func5on counter(inc) {count=count+inc; return count}; return counter};
var c = mk_counter(1);
c(2) + c(2); c
access
Code for counter
Code for mk_counter
c(2) access inc 2
mk_counter(1)
count 1 init 1
access
counter
mk_c
JS
3
Closures in Web programming
Useful for event handlers in Web programming: func5on AppendBuWon(container, name, message) {
var btn = document.createElement('buWon');
btn.innerHTML = name; btn.onclick = func5on (evt) { alert(message); }
container.appendChild(btn);
}
Environment pointer lets the buWon’s click handler find the message to display
Summary: Return Func5on Results
Use closure to maintain sta5c environment
May need to keep ac5va5on records ader return o Stack (lifo) order fails!
Possible “stack” implementa5on o Forget about explicit dealloca5on o Put ac5va5on records on heap
o Invoke garbage collector as needed o Not as totally crazy as is sounds
May only need to search reachable data
Summary of scope issues
Block-‐structured lang uses stack of ac5v records o Ac5va5on records contain parameters, local vars, … o Also pointers to enclosing scope
Several different parameter passing mechanisms Tail calls may be op5mized Func5on parameters/results require closures o Closure environment pointer used on func5on call o Stack dealloca5on may fail if func5on returned from call o Closures not needed if func5ons not in nested blocks