CS 342 Lecture -*- Outline -*- * Procedure parameters ** problem: ensuring procedure parameter has proper access to variables ---------- program proc_parameters; function twice(function f(n:integer): integer, x: integer): integer; begin twice := f(f(x)) end; procedure tm(m: integer); function by_m(i: integer): integer; begin by_m := i*m end; begin writeln(twice(by_m,3)) end; begin tm(4) end. ---------- *draw stack as this executes, "m" illustrates the problem. ** Solution: closures pass static link (or display) along with procedure parameters. *** closure: pair of static link (or display) and code address (name derivation: procedure said to be closed if it does not refer to global variables. Closure is thus process of putting globals "into" proc) *** What static link is passed? in general, if def of actual is at static distance SD from call -traverse SD static links to find SL for closure How to call formal procedure 1. set static link from formal.EP 2. jump indirect through formal.IP *** What display must be passed? -simplest if pass entire display, save and restore whole display when call procedure parameter ** What happens if allow returns of functions? ---------- function curried_add(m: integer): function(i: integer): integer; function f(i: integer): integer; begin f := i+m; end; begin curried_add := f end {illegal} ---------- returning a closure will cause a dangling reference, -AR for curried_add will be popped -can allocate AR on the heap: called *full closure*