1
SCOPE, FUNCTION CALLS AND STORAGE MANAGEMENT
Topics
Block-structuredlanguagesandstackstorage In-lineBlockso ac5va5onrecordso storageforlocal,globalvariables First-orderfunc5onso parameterpassingo tailrecursionanditera5on Higher-orderfunc5onso devia5onsfromstackdisciplineo languageexpressiveness=>implementa5oncomplexity
2
Block-StructuredLanguages
Nestedblocks,localvariableso Example{intx=2; {inty=3;x=y+2;
}}o Storagemanagement
ü Enterblock:allocatespaceforvariablesü Exitsblock:someorallspacemaybedeallocated
new variables declared in nested blocks
inner block
outer block local variable
global variable
Examples
Blocksincommonlanguageso C,{…}o Algolbegin…endo MLlet…in…end Twoformsofblockso In-lineblockso Blocksassociatedwithfunc5onsorprocedures
Topic:block-basedmemorymanagement,accesstolocalvariables,parameters,globalvariables
* JavaScript functions provide blocks
3
SimplifiedMachineModelRegisters
Environment Pointer
Program Counter
Data Code
Heap
Stack
InterestedinMemoryMgmtOnly
Registers,Codesegment,Programcountero Ignoreregisterso Detailsofinstruc5onsetwillnotmaWer
DataSegmento Stackcontainsdatarelatedtoblockentry/exito Heapcontainsdataofvaryinglife5meo Environmentpointerpointstocurrentstackposi5on
ü Blockentry:addnewac5va5onrecordtostackü Blockexit:removemostrecentac5va5onrecord
4
Somebasicconcepts
Scopeo Regionofprogramtextwheredeclara5onisvisible Life5meo Periodof5mewhenloca5onisallocatedtoprogram
• 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-lineBlocks
Ac5va5onrecordo Datastructurestoredonrun-5mestacko Containsspaceforlocalvariables 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
5
Ac5va5onrecordforin-lineblock
Controllinko pointertopreviousrecordonstack
Pushrecordonstack:o Setnewcontrollinktopointtooldenvptr
o Setenvptrtonewrecord Poprecordoffstacko Followcontrollinkofcurrentrecordtoresetenvironmentpointer
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
6
Scopingrules
Globalandlocalvariables{ 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.
Func5onsandprocedures
Syntaxofprocedures(Algol)andfunc5ons(C)procedureP(<pars>)<type>func5onf(<pars>)begin{<localvars><localvars><procbody><func5onbody>end;} Ac5va5onrecordmustincludespacefor• parameters • return address • local variables,
intermediate results
• return value (an intermediate result)
• location to put return value on function exit
7
Ac5va5onrecordforfunc5on
Returnaddresso Loca5onofcodetoexecuteonfunc5onreturn
Return-resultaddresso Addressinac5va5onrecordofcallingblocktoreceivereturnaddress
Parameterso Loca5onstocontaindatafromcallingblock
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return-result addr
Example
Func5onfact(n)=ifn<=1then1elsen*fact(n-1)o Returnresultaddresso loca5ontoputfact(n) Parametero settovalueofnbycallingsequence
Intermediateresulto loca5onstocontainvalueoffact(n-1)
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return result addr
8
Control link
fact(n-1) n
Return-result addr 3
fact(3)
Func5oncall
ReturnaddressomiWed;wouldbeptrintocodesegment
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 →
Func5onreturn
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)
9
Topicsforfirst-orderfunc5ons Parameterpassingo pass-by-value:copyvaluetonewac5va5onrecordo pass-by-reference:copyptrtonewac5va5onrecord Accesstoglobalvariableso globalvariablesarecontainedinanac5va5onrecordhigher“up”thestack
Tailrecursiono anop5miza5onforcertainrecursivefunc5ons
Seethisyourself:writefactorialandrununderdebugger
Parameterpassing
Generalterminology:L-valuesandR-valueso Assignmenty:=x+3
ü Iden5fieronlebreferstoloca5on,calleditsL-valueü Iden5fieronrightreferstocontents,calledR-value
Pass-by-referenceo PlaceL-value(address)inac5va5onrecordo Func5oncanassigntovariablethatispassed Pass-by-valueo PlaceR-value(contents)inac5va5onrecordo Func5oncannotchangevalueofcaller’svariableo Reducesaliasing(alias:twonamesrefertosameloc)
10
Example
function f (x) = { x = x+1; return x; } var y = 0; print (f(y)+y);
pseudo-code activation records
pass-by-re
f
pass-by-value
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)
Accesstoglobalvariables
Twopossiblescopingconven5onso Sta5cscope:refertoclosestenclosingblocko Dynamicscope:mostrecentac5va5onrecordonstack Examplevar 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 ?
11
Ac5va5onrecordforsta5cscope
Controllinko Linktoac5va5onrecordofprevious(calling)block
Accesslinko Linktoac5va5onrecordofclosestenclosingblockinprogramtext
Differenceo Controllinkdependsondynamicbehaviorofprog
o Accesslinkdependsonsta5cformofprogramtext
Control link
Local variables
Intermediate results
Environment Pointer
Parameters
Return address
Return result addr
Access link
Complexnes5ngstructure
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.
12
Sta5cscopewithaccesslinks
Useaccesslinktofindglobalvariable:ü Accesslinkisalwayssettoframeofclosestenclosinglexicalblock
ü Forfunc5onbody,thisisblockthatcontainsfunc5ondeclara5on
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-OrderFunc5ons
Languagefeatureso Func5onspassedasargumentso Func5onsthatreturnfunc5onsfromnestedblockso Needtomaintainenvironmentoffunc5on Simplercaseo Func5onpassedasargumento Needpointertoac5va5onrecord“higherup”instack Morecomplicatedsecondcaseo Func5onreturnedasresultoffunc5oncallo Needtokeepac5va5onrecordofreturningfunc5on
13
Passfunc5onasargument
intx=4;funf(y)=x*y;fung(h)=letintx=7inh(3)+x;g(f);Therearetwodeclara5onsofxWhichoneisusedforeachoccurrenceofx?
{ var x = 4; { function f(y) {return x*y}; { function g(h) { var x = 7; return h(3) + x; }; g(f); } } }
Haskell Pseudo-JavaScript
Sta5cScopeforFunc5onArgument
intx=4;funf(y)=x*y;fung(h)=letintx=7inh(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?
14
Sta5cScopeforFunc5onArgument
{varx=4;{func5onf(y){returnx*y};{func5ong(h){intx=7;returnh(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
Func5onvalueispairclosure=〈env,code〉 Whenafunc5onrepresentedbyaclosureiscalled,o Allocateac5va5onrecordforcall(asalways)o Settheaccesslinkintheac5va5onrecordusingtheenvironmentpointerfromtheclosure
15
Func5onArgumentandClosures
intx=4;funf(y)=x*y;fung(h)=letintx=7inh(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);
}}}
Func5onArgumentandClosures
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
16
Summary:Func5onArguments
Useclosuretomaintainapointertothesta5cenvironmentofafunc5onbody Whencalled,setaccesslinkfromclosure Allaccesslinkspoint“up”instacko Mayjumppastac5vrecordstofindglobalvarso S5lldeallocateac5vrecordsusingstack(lifo)order
ReturnFunc5onasResult Languagefeatureo Func5onsthatreturn“new”func5onso Needtomaintainenvironmentoffunc5on Examplefunc5oncompose(f,g){returnfunc5on(x){returng(f(x))}}; Func5on“created”dynamicallyo expressionwithfreevariables
valuesaredeterminedatrun5meo func5onvalueisclosure=〈env,code〉o codenotcompileddynamically(inmostlanguages)
17
Example:Returnfctnwithprivatestate
funmk_counter(init:int)=letvalcount=refinit
funcounter(inc:int)=(count:=!count+inc;!count)incounterend;
valc=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:Returnfctnwithprivatestate
func5onmk_counter(init){varcount=init;func5oncounter(inc){count=count+inc;returncount};returncounter};varc=mk_counter(1);c(2)+c(2);Func5onto“makecounter”returnsaclosureHowiscorrectvalueofcountdeterminedincallc(2)?
JS
18
Func5onResultsandClosuresfunmk_counter(init:int)=letvalcount=refinit
funcounter(inc:int)=(count:=!count+inc;!count)incounterend
end;valc=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
Func5onResultsandClosuresfunc5onmk_counter(init){varcount=init;func5oncounter(inc){count=count+inc;returncount};returncounter};varc=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
19
ClosuresinWebprogramming
UsefulforeventhandlersinWebprogramming:func5onAppendBuWon(container,name,message){varbtn=document.createElement('buWon');btn.innerHTML=name;btn.onclick=func5on(evt){alert(message);}container.appendChild(btn);}
EnvironmentpointerletsthebuWon’sclickhandlerfindthemessagetodisplay
Summary:ReturnFunc5onResults
Useclosuretomaintainsta5cenvironment Mayneedtokeepac5va5onrecordsaberreturno Stack(lifo)orderfails!
Possible“stack”implementa5ono Forgetaboutexplicitdealloca5ono Putac5va5onrecordsonheapo Invokegarbagecollectorasneededo Notastotallycrazyasissounds
Mayonlyneedtosearchreachabledata
20
Summaryofscopeissues
Block-structuredlangusesstackofac5vrecordso Ac5va5onrecordscontainparameters,localvars,…o Alsopointerstoenclosingscope Severaldifferentparameterpassingmechanisms Tailcallsmaybeop5mized Func5onparameters/resultsrequireclosureso Closureenvironmentpointerusedonfunc5oncallo Stackdealloca5onmayfailiffunc5onreturnedfromcallo Closuresnotneedediffunc5onsnotinnestedblocks