Date post: | 22-Dec-2015 |
Category: |
Documents |
View: | 218 times |
Download: | 2 times |
Catriel Beeri Pls/Winter 2004/5 environment 1
II. Frames and frame structures• Frame – set of bindings generated together in a
binding generation event (frame ~ mini environment )
• When an event generates frame F, then the new environment is (for some E)
• E itself was similarly generated • In the future, E may become again the current
environment Frames are added/removed in LIFO
A stack discipline
FE
Catriel Beeri Pls/Winter 2004/5 environment 2
Environment structure --- past and present frames -- a tree: each path from root is a stack of frames
• Activation start (binding generation event)
• generation of frame • implemented as push (onto current environment)
• Look-up --- search in frame stack, top-to-bottom
• Activation exit -- restoration of previous environment
• Frame disposed of (automatically/garbage collection) --- pop
Let us re-visit previous example
FE
Catriel Beeri Pls/Winter 2004/5 environment 3
Example:
(start with empty environment)
Activation directly evaluated frame
The value 7 is returned, down to to act0
evaluate 3, . (4) let* in x f y x y f
2act 4 { . }f f y x y
3act , , 3 4 { 4}x y y
0act 3
1act . { 3}y x y x
Catriel Beeri Pls/Winter 2004/5 environment 4
Dynamic scoping
Results of resolutions depend on how environments are modified when a activation is entered
Option A: new generated bindings are always merged into current environment (at point of entrance)
dynamic scoping• Simple, elegant approach
• Works well with stack-based implementations of pl’s
We discuss implementation, present examples , show that approach is WRONG
Catriel Beeri Pls/Winter 2004/5 environment 5
1 1
1 1
: , 1..
{ , ..., } :(env-nat-let-d)
<E:let , ..., in b>
i i
n n
n n
e v i n
x v x v b v
x e x e v
< >ß Î
®Å >ß
= = ß
a a< E
E
1 1
1 1
1
1
{ λy ,..., λy } :(env-nat-letrec-d)
< :letrec λy , ..., λy in b>
. .
. .n n
n n
n
n
x b x b b v
x b x b v
®Å >ß
= = ß
a a
E
< E
1
1 1
1
(λ.( ) : , 1..
{ , ..., } :
)
)
: (
env-nat-
applic-fun-d
,..., .
,...
i i
n n
n
n
f x x b e v i n
x v x v b v
vE f e e
ß < >ß Î
®Å >ß
>ß<
æ ö÷ç ÷ç ÷çè øa a< E
E
Catriel Beeri Pls/Winter 2004/5 environment 6
Activation and frame stacks are in 1-1 correspondence!• Each activation A --- associated frame F(A)
generated & removed together• Look-up when A is current (top of activation stack)
starts at F(A) (then top of frame stack) then (if needed) goes down
Wlog: going down uses the dynamic parent to reach the activation below, then its frame
Look-up follows the dynamic parents chain, until a binding is found (or fail announced)
Catriel Beeri Pls/Winter 2004/5 environment 7
Example revisited (let* x =3, f = ….)
Act frame d-eval exp evaluated exp
The result 7 is returned from #3 to #2 to #1 to #0
Q: What would happen if the body of f contained f?
#0 - 3 3, . (4)
le
t*
in
x f y x yf
let*#1 { 3} . . (4in )x y x y f y x y f
#2 { . } 4 (4)f y x y f f
#3 { 4} y x y x y
Catriel Beeri Pls/Winter 2004/5 environment 8
processed expr fram e
1: ( ) : ( ) ( 1) { 3}act g f y f y y
Example:
We start from g(3), after the bindings of the let* were established, showing successive (partial) stacks, (‘control’ shown with a circle) )
Here, f, y are d-evaluated
( ) 1, ( ) ( ) ( 1l )
(3
et*
i )n
f x x g y f y f y
g
12 : ( ) : 1 { 3}
( ) : ( ) ( 1) { 3}
act f x x
act g f y f y y
Catriel Beeri Pls/Winter 2004/5 environment 9
When returns with 4, we are back at act(g)
Now, d-eval f, y+1
Finally, back in act(g), 4+5 evaluates 9, and the computation of the let* returns this value
2
( 4)
4 : ( ) : 1 { 4}
( ) : ( ) ( 1) { 3}
act f x x
act g f y f y y
( 4)3: ( ) : ( ) ( 1) : { 3}act g f y f y y
( 4) ( 5)5 : ( ) : ( ) ( 1) { 3}act g f y f y y
1( )act f
Catriel Beeri Pls/Winter 2004/5 environment 10
Example: Evaluate
( ) 5, 3, . ( (2)let* in )g x x x f y x y f g
See details of stack evolution next page
Catriel Beeri Pls/Winter 2004/5 environment 11
let#0 * ( ) . 5g x x x
#1: { . 5} let* 3,.. 3g x x x
let*#2 : { 3} .x f y x y
#3 : { . } ( (2)) , , 2f y x y f g f g
Act frame eval d-eval
#4 : { 2} 5 5x x x #5 : { 7}y x y x y
The final result, 10, moves down to #0
(2)g
(2) 7g
(7)f
( ) 5, 3, . ( (2)let* in )g x x x f y x y f g
Catriel Beeri Pls/Winter 2004/5 environment 12
Example:
next page
Evaluate , 3, . , ( ) ( 5)
let*
i 2
)n (
x f y x y g x f x
g
Catriel Beeri Pls/Winter 2004/5 environment 13
# 2 { . } *let ( ) . ( 5)f y x y g x x f x
let*#0 : 3 x
let*#1 : { 3} .x f y x y
#3 : { . ( 5)} (2) , 2g x f x g g
Act frame eval d-eval
# 4 : { 2} ( 5) , 5x f x f x
#5 : { 7}y x y x y
The final result is 9
(2)g
, 3, . , ( )let* in( 5) (2)x f y x y g x f x g
Wrong!
(7)f
Catriel Beeri Pls/Winter 2004/5 environment 14
The source of the problem: A delay between • creation of a function value (from a function expression)
• its application
The bindings for its free variables available when it is applied may differ from those when it is created
Catriel Beeri Pls/Winter 2004/5 environment 15
#1: { . . } ,1f x y x y f
#0 : . .x y x y
#3 : { . } ,3g y x y g
#2 : { 1} .x y x y
#4 : { 3}y x y
Act frame d-eval
(1) :f #2 and the binding x1 are gone! #3 is on top of #1
: evaluate . . ;;
g = (1);; (a
Exam
sim
ple let
l ple "object")
(3);
et
f x y x y
f
g
Free variable: x (or worse, could be defined)
(3) :g
Catriel Beeri Pls/Winter 2004/5 environment 16
The source of the problem: A delay between • creation of a function value (from a function expression)
• its application
The bindings for its free variables available when it is applied may differ from those when it is created
Catriel Beeri Pls/Winter 2004/5 environment 17
3;
. ;
.......
2;
(3)
let
let
let
x
f y x y
x
f
What is the result? Right or wrong?
Catriel Beeri Pls/Winter 2004/5 environment 18
of start body of
( ){
( ){ return }
( ){ print (3) }
print (3); (* *)(5);
}
Pascal
E
proc E x
func F y x y
proc G x F
FG
let rec
let rec ......
and .....
in (print ( 3)); 5);;
ML
E x
F y
G x
F G
What happens after a call E(2)?
Catriel Beeri Pls/Winter 2004/5 environment 19
Can such phenomena also happen in C?
Catriel Beeri Pls/Winter 2004/5 environment 20
In dynamic scoping the free (global) variables in a function body are associated with bindings late:
when resolution is performed
The associations use the stack of frames, accessed in order of generation
This allows interference!
no relationship to static structure
Static structure is not a reliable predictor of execution
Catriel Beeri Pls/Winter 2004/5 environment 21
Various problems of dynamic scoping:
• Same calls of a function (with same arg value) may return different results (including error msgs in some)
(lack of referential transparency)
• Change of a formal parameter of a function may cause others to change their behavior
• A function called by F may `see’ F’s parameters and locals– a breach of abstraction/security
• Useless to perform static checks such as
– Static type-check
– Is a variable defined before being used? (free var check)
unpredictable behavior, often unrelated to static structure
Catriel Beeri Pls/Winter 2004/5 environment 22
Manifestation of problems does not require• Higher-order functions• Recursion (Although it is more common when these are present)
Conclusion: dynamic scoping is Simple, elegant, (quite) efficient, but wrong!now considered an error, not used in modern pl’s
Recall: Results of resolutions depend on how environments
are modified when a activation is entered What other options are there ?
Catriel Beeri Pls/Winter 2004/5 environment 23
The problem (in dynamic): A delay between
creation of a function value and its applicationThe bindings for its free variables available when it is applied
are different from those when it is created
The solution:• When a function value is created, the bindings for its
free variables (from current environment) are attached to it• When it is applied, these bindings are used as base
environment
Static scoping
Catriel Beeri Pls/Winter 2004/5 environment 24
A function value (static scoping): fv= <p;b;E> , where • p is the parameter(s)• b is the body• E is an environment with bindings for
The triple <p;b,E> is called a
(function) closure• Intended to be used later in various places
(delayed evaluation)• A closed package that contains everything needed for
its future evaluation(s)
freevars( . )p b
Catriel Beeri Pls/Winter 2004/5 environment 25
Closure and environment creation:• When a function expression is evaluated in environment
E, the value <pars;b,E’> is created E’ is derived from E
• When a function value <pars;b,E’> is applied to args in environment E’’– a frame F of bindings parsargs is generated – the activation executes in environment– When it terminates, the environment E’’ is restored
'E F
The environment component of a function value is derived from that of its time & place of creation
Catriel Beeri Pls/Winter 2004/5 environment 26
Note: environment creation upon entrance to let, let* is unchanged
For letrec --- below
Catriel Beeri Pls/Winter 2004/5 environment 27
Implementation of Environment creation:(in all implementations, the term function closure is used)
Fully computed at the time of creation:• The environment component of a function value is
computed (when it is created) by copying the relevant bindings from the current environment:
if E is current environment,
• That of an activation is computed (before it starts)
A common choice in implementations of functional pl’s
|freevars( ) is computedfE
Catriel Beeri Pls/Winter 2004/5 environment 28
Using frames linked by references:
(A common approach for imperative pl’s)
1. An environment is a (linked) list of frames, viewed as a stack:
• An entry: a frame & a reference to the next entry
[F1,&F2] [F2, &F3] …..
• The first entry in the list is the top of the stack
The reference in an entry is its
static parent or static pointer
Catriel Beeri Pls/Winter 2004/5 environment 29
2. An activation contain a reference to the top/first entry of its environment
and a dynamic parent/pointer, to the next entry on the activation stack
The dynamic and static parents, from an activation and its environment, may lead to unrelated activation and environment!
activations environments
a8 f8
f1f4
env(a8) = f8, f4, f1, …
a1
f11
Catriel Beeri Pls/Winter 2004/5 environment 30
3. A function value: <p;b;&F> , where &F is a reference to a frame --- the top frame of the current environment at its time of creation
The triple <p;b;&F> is also called a function closure(note: it may contain extra bindings!)
4. implemented as push --- create an entry < F,&top(E)> , make it the new top
(this reference is the static parent of F)
E F
Previous examples revisited:
Catriel Beeri Pls/Winter 2004/5 environment 31
[ 4 :{ 2}; & 2]F x F
[ 1:{ 3}; & 0]F x F
; ( 5);& 2[ 3 :{ }; & 2]x f x FF g F
Evaluate , 3, . , ( ) ( 5)
let*
i 2
)n (
x f y x y g x f x
g
A0 3
A4 f, x+5
•A3 g, 2
A1 .y x y
A2 . ( 5)x f x [ 2 :{ };; ;& 1 & 1]y x y FF f F
[F0:{}; nill]
[ 5 :{ 7}; & 1]F y FA5 x+y
act frame
dynamic: static:
Result: 10 passed down to A4, … A0
(2)g
(7)f
Catriel Beeri Pls/Winter 2004/5 environment 32
: evaluate . . ;;
g = (1);; (
Examp
a simple "object
le let
")let
(3);
f x y x y
f
g
[ 1 : { }; &; ; 0 0. & ]x y x FFF f y
[ 2 : { 1}; & 0]F x F
A1 f, 1
A2
A3 g, 3
A4 x+y
.y x y
. .x y x y A0 [ 0 : {}; ]F nill
[ 3 : { };; ;& 2 & 1]y x y FF g F
[ 4 : { 3}; & 2]F y F
A2 is now gone from stack
Frame lives!
(1)f
(3)g
Catriel Beeri Pls/Winter 2004/5 environment 33
[ 4 :{ 2}; & 2]F x F
[ 1:{ 3}; & 0]F x F
; ( 5);& 2[ 3 :{ }; & 2]x f x FF g F
Evaluate , 3, . , ( ) ( 5)
2 1
let*
in
x f y x y g x f x
g f
A0 3
A4 f, x+5
A3 g, 2
A1 .y x y
A2 . ( 5)x f x [ 2 :{ };; ;& 1 & 1]y x y FF f F
[F0{}; nill]
[ 5 :{ 7}; & 1]F y FA5 x+y Result 10 to A4 to A3; what next?
(2)g
(7)f
Catriel Beeri Pls/Winter 2004/5 environment 34
Observations:• Assume (A;F) are current static parent(F), dynamic parent(A) are not necessarily associated with each other • When an activation dies, the frames of its associated
environment may be referenced from live activations or function values
1. An activation popped from stack is gone (dead);
its associated frame (often) lives on (where?) 2. Static parent may correspond to no live activation! (is that a problem?)
Catriel Beeri Pls/Winter 2004/5 environment 35
• The environment structure is a tree
(how do we know it is a tree, not a graph? )
– Current environment is a path from a node to the root– When an activation starts, a node is added to the tree, as a
child of some existing node (& becomes top of current environment)
– When an activation terminates, a different path becomes the current environment
Nodes are removed from the tree only by garbage collection (when provably they are not referenced from any live entity)
no explicit pop
Catriel Beeri Pls/Winter 2004/5 environment 36
Other kinds of blocks:
A function value is a package, carrying its own environment, since it moves around and may be invoked in various places
A regular block (let, let*, letrec) has no need of such a mechanism
• Upon entrance to new region, new bindings are added to current environment
(static parent ~ dynamic parent!)
• Upon exit, previous environment is restored
let and let* are simple, letrec requires re-consideration
Catriel Beeri Pls/Winter 2004/5 environment 37
Rules for let: (entered in current environment E)• Evaluate defining expressions in current environment • Create the frame F for the defined variables• Evaluate the body (~ activation) in• Upon exit, restore E
reflects the scope rule of let, the fact that it is not recursive
What are the rules for let*?
E F
1 1
1 1
: , 1..
{ , ..., } :(env-nat-let-s)
< : let , ..., in
i i
n n
n n
E V i n
x V x V B V
E x E x E B V
< >ß Î
®Å >ß
= = >ß
a a
E
< E
Catriel Beeri Pls/Winter 2004/5 environment 38
For a letrec, the defining expressions need to be evaluated in the new environment!
Assume is evaluated in environment E
But, this solution does not work now!
1 1 ,...,letrec i nn nx e x e e
1The environment for evaluating ,... is
bindings for
and
the '
n
i
e e e
x sE
: a binding for cannot exist ib s evaluatedefore ?Q i ix e
(evaluate to) : If the are , then can evfunc alauti teA ns no iie E
Catriel Beeri Pls/Winter 2004/5 environment 39
The solution:
Do the evaluation of the functions and the construction of the new environment in one step
The requirement:
After this step
' { ; ;& ' , 1,.., }i i if p B i n®= Å < > =aE E E
Catriel Beeri Pls/Winter 2004/5 environment 40
1 1 1 . ,.l .etrec ., . inn n nf x e f x e e
(* - undefined)1 extend with { * ,..., *}
let the result be
nE f f
E
evaluate each in. to < ; ;&i i i ix e E x e E
replace (assignment) * b
backpatching
y ; ; }
( )
i i i if f x e E
A solution with assignable cells: (the Scheme implementation)
What is the role of delayed evaluation here?Can you think of a purely functional solution?
Catriel Beeri Pls/Winter 2004/5 environment 41
Assume computation starts from
activation A0, and frame [F0:{};nill]
How will the activation stack and the environment structure evolve?
Note: The final value true is returned from final activation #i to #i-1, … to #0. Those in middle just pass it on
even . 0 odd( -1),
odd . 0 even( -1)
letrec if then else
if t
e
hen else
i )n ve (4
n
n n true n
n n false n
Catriel Beeri Pls/Winter 2004/5 environment 42
The rules:
(env-nat-lambda) < : . ; ;x b x bE E
1
1 1
1
: ( ); ;
: , 1..
{ ,..., } :
: ( ,..., )
env-nat-
applic-fun-s
,...,
i i
n n
n
n
f x x b
e v i n
x v x v b v
f e e v
< >ß<
< >ß Î
®Å >ß
< >ß
æ ö÷ç ÷ç ÷çè øa a
E E >
E
E
< E
1 1(env-nat-lambda) < : ( . ( ; ;,..., ) ., , ,. )n nx b x bx xE E
Catriel Beeri Pls/Winter 2004/5 environment 43
For letrec:
1 1 1
1 1 1
Denote by
. { ; ; ,..., ; ; }
the environment that satisfies
{ ; ; ,..., ; ; }
(a definition, can be implemented by
references and
recursive
assig
n n n
n n n
Rec E E f x b E f x b E
E
E E f x b E f x b E
ment lazy lists more )
1 1 1
1 1 1
(env-nat-letrec-s)
. { ; ; ,..., ; ; } :
< : . ,let ... , . in b>recn n n
n n n
rec E E f x b E f x b E b v
E f x b f x b v
Catriel Beeri Pls/Winter 2004/5 environment 44
Comments:• How does a computation start? A zero’th activation, with initial environment which
may be empty, or not (depending on pl/implementation)
• The model as described can explain
activations and binding management
in most languages, including
interactive mode in functional languages
however, the global environment and define in Scheme behave differently (still based on environments)
Catriel Beeri Pls/Winter 2004/5 environment 45
• Functions in a pl exist on three levels:
– L1: Function expressions (static)
– L2: function values (dynamic)
– L3: activations of function values (dynamic)
The relationships L1L2 , L2L3 are 1-m:
– Many values may be created from an expression
– Many activations of a value may occur, even be live simultaneously
The distinction between L1, L2 is not evident in substitution model and in dynamic scope
Catriel Beeri Pls/Winter 2004/5 environment 46
Is behavior under static scoping compatible with static structure?
Denote:
• For a use u(x) in program: declu(u(x)) – the declaration d(x) that statically binds it (static)
• For a binding b generated at run-time for a declaration d(x) : declb(b)=d(x) (dynamic)
• For a use u(x) : resol(u(x)) – the binding returned by resolving it in current environment (dynamic)
Claim1: declb(resol(u(x)))= declu(u(x))
Catriel Beeri Pls/Winter 2004/5 environment 47
Meaning of arrows: resolves to
static binding generated for
d(x)
u(x) u(x)
d(x)
xv2
xv1
xv3
xv4
Catriel Beeri Pls/Winter 2004/5 environment 48
Can prove a stronger statement:
If a binding xv is generated for declaration of x for a new activation,
Then for every use of x in the scope of this declaration, its resolution always returns v
let f =
let x = 3 in lambda y.x+y;;
….f 5 returns 8 (always)
Static structure is a reliable predictor of execution
Catriel Beeri Pls/Winter 2004/5 environment 49
Static scope avoids the problems of dynamic scope:• Calls of a function with same arguments behave the
same – referential transparency holds• Change of formal parameter of a function does not
change behavior (in activations of other functions) -- no surprises
• function is a black box – no external function may observe values of locals
• Useful to perform static check: – that a use is in scope of a declaration
guarantees: resolution never returns unbound variable
– Static type-checking guarantees absence of run-time type errors