440 likes | 457 Views
Discover the definition, activation, and environments of procedures in programming. Learn about parameter passing methods like pass by value and pass by reference, with examples. Explore pass by value-result and pass by name concepts.
E N D
Procedure Definition • A procedure is a mechanism for abstracting a group of related operations into a single operation that can be used repeatedly without repeating the code • The group of operations is called the body of the procedure • A procedure is defined by providing a specification or interface and a body • The specification gives the procedure name, a list of types and names of parameters, and the type of its returned value
An Example void intswap (int &x, int &y) // specification { // body begins int t = x; x = y; y = t; } // body ends void intswap (int &, int &); // specification only
Procedure Activation • A procedure is called or activated by stating its name, together with arguments to the call, which correspond to its parameters • A call to a procedure transfers control to the beginning of the body of the called procedure (the callee) • When execution reaches the end of the body, control is returned to the caller • Control can also be returned to the caller before reaching the end of the body by using return-statements
Environments • A procedure communicates with the rest of the program through its parameters and also through nonlocal references • The defining (or static) environment is the environment defining the meaning of nonlocal references • The calling (or dynamic) environment is the environment defining the meaning of the caller
defining environment calling environment Environments int a, b;int q(int d){ int e; … }int p(int c){ int a; … q(a); } main(){ int b; p(a); } a, b globalb main a, c pd, e q
Environments • In static scoping, a procedure can communicate with its defining environment through nonlocal references or parameters • In static scoping, a procedure can communicate with its calling environment through only parameters • In dynamic scoping, the defining environment is the same as the calling environment
Parameter Passing • Pass by value • Pass by reference • Pass by value-result • Pass by name
Pass by Value • Arguments are expressions that are evaluated at the time of the call, and their values become the values of the parameters during the execution of the procedure • Parameters are viewed as constant values given by the values of the arguments, or • Parameters are viewed as local variables with initial value given by the values of the arguments
An Example void init_p(int *p){ *p = 0; }void init_ptr(int *p){ p = (int *) malloc(sizeof(int)); }void init_p_0(int p[ ]){ p[0] = 0; } void append_1(Vector v){ v.addElement(new Integer(1)); }void make_new(Vector v){ v = new Vector(): } error! error!
Pass by Reference • An argument must in principle be a variable with an allocated address. Instead of the value, the location of the variable is passed to the parameter • The parameter becomes an alias of the argument. Any changes made to the parameter occur to the argument as well
An Example int a; void inc(int &x){ x++; }… inc(a);void inc(int *x){ (*x)++; }… inc(&a);void yuck(int &x, int &y){ x = 2; y = 3; a = 4;} … yuck(a, a); void inc(int &x){ x++; }… inc(2); an error in C++! ok in Fortran!
Pass by Value-Result • The value of the argument is copied and used in the procedure, and then the final value of the parameter is copied back out to the location of the argument when the procedure exits • This method is also known as copy-in, copy-out, or copy-restore • A language may offer a pass by result method, in which there is no incoming value, but only an outgoing value
An Example void p(int x, int y){ x++; y++; } main( ){ int a = 1; p(a, a); …} a = 3 for pass by reference a = 2 for pass by value-result
Pass by Name • The semantics of procedures is described by a form of textual replacement • An argument is not evaluated until its actual use in the called procedure. The name (or textual representation) of the argument replaces the name of the corresponding parameter at the point of call • It turns out that pass by name is essentially equivalent to the normal order evaluation
An Example int i;int a[10];void p(int x){ i++; x++; } main( ){ i = 1; a[1] = 1; a[2] = 2; p(a[i]); return 0;} /* i = 1, a[2] = 2 */ i++; /* i = 2 */a[i]++; /* a[2] = 3 */
Pass by Name • The text of an argument at the point of call is viewed as a function in its own right, which is evaluated every time the corresponding parameter name is reached in the called procedure • The argument will always be evaluated in the calling environment, while the called procedure will be executed in its defining environment
An Example int i;int p(int y){ int j = y; i++; return j + y; }int q(void){ int j = 2; i = 1; printf(“%d\n”, p(i + j)); } main(){ q( ); return 0;} i + j 3 i + j 4
An Example int i, j;int i_plus_j(void){ return i + j; }int p(int (*y) (void)){ int j = y(); i++; return j + y(); }int q(void){ j = 2; i = 1; printf(“%d\n”, p(i_plus_j)); } main(){ q( ); return 0;} thunk
An Example void intswap(int x, int y){ int t = x; x = y; y = t; }intswap(i, a[i]); t = i; i = a[i]; a[i] = t;
Fully Static Environments • In Fortran 77, function and procedure definitions cannot be nested • Recursion is not allowed • The locations of all variables are fixed for the duration of program execution
Fully Static Environments COMMON areaActivation record of mainActivation record of S1Activation record of S2… space for local variablesspace for passed parametersreturn addresstemporary space for expression evaluation
An Example REAL TABLE(10), MAXVAL READ *, TABLE(1), TABLE(2) CALL LRGST(TABLE, 2, MAXVAL) PRINT *, MAXVALENDSUBROUTINE LRGST(A, SIZE, V) INTEGER SIZE REAL A(SIZE), V INTEGER K V = A(1) DO 10 K = 1, SIZE IF (A(K) .GT. V) V = A(K)10 CONTINUE RETURNEND TABLE (1) … TABLE (10) MAXVAL Temp: 2 K A SIZE V Return addr
Stack-Based Environment • In a block-structured language with recursion, activations of procedures can be done in a stack manner, with a new activation record created on the stack every time a procedure is entered and released on exit
Stack-Based Environment • Environment (or frame) pointer points to the current activation record • Control (or dynamic) link points to the calling environment, i.e., the activation record of the caller • Access (or static) link points to the defining environment, i.e., the activation record where nonlocal references are defined
Stack-Based Environment control linkaccess linklocal variablespassed parametersreturn address temporaries
ep ep ep mainq mainq p An Example int p(void){ … }int q(void){ … p(); } main(){ q( ); … } main
procedure q is x: integer;procedure p(y: integer) is i: integer := x;begin … end p; procedure r is x: float;begin p(1); … end r;begin r; end q; qr p controllink accesslink An Example
Access Chaining procedure ex is x: …; procedure p is procedure q is begin … x …; end q; begin … end p; begin … end ex; ex: xp q nesting depth = 2
Closure procedure lastex is procedure p(n: integer) is procedure show is begin if n > 0 then p(n - 1); end if; put(n); new_line; end show; begin show; end p; begin p(1); end lastex; <ep, ip> lastexp show p show
Procedure Parameters • For a procedure parameter, the corresponding argument will be a closure <ep, ip> • The ep is used to set the access link of the called procedure • The ip points to the code of the called procedure
Dynamically Created Procedures • When procedures can be created dynamically and be returned via returned values or reference parameters, they become first-class values • Since the closure of a locally defined procedure will have an ep points to the current activation record. If that closure is available outside the activation of the procedure that created it, the ep will point to an activation record that no longer exits
An Example type WithdrawProc isaccess function(x: integer) return integer;InsufficientFunds: exception;function makeNewBalance(initBalance: integer) return WithDrawProc iscurrentBalance: integer;function withdraw(amt: integer) return integer isbegin if amt <= currentBalance thencurrentbalance := currentBalance – amt; else raise InsufficientFunds; end if; return currentBalance;end withdraw; begin curentBalance := initBalance; return withdraw’access;end makeNewbalance;
An Example withdraw1, withdraw2: WithdrawProc;withdraw1 := makeNewBalance(500);withdraw2 := makeNewBalance(100); /* similar to dangling reference */ newBalance1 := withdraw1(100); newBalance2 := withdraw2(50);
Fully Dynamic Environments • In fully dynamic environment, like scheme, an activation record can be removed only if they can no longer be reached from within the executing program • Such an environment must perform some kind of automatic reclamation of unreachable storage called garbage collection • Two standard methods of garbage collectionare reference counting and mark and sweep
MakeNewBalance:currentBalance: 500Withdraw: … MakeNewBalance:currentBalance: 100Withdraw: … An Example defining environment…Withdraw1 Withdraw2 The structure of the activations becomestreelike instead of stacklike
Reference Counting • It (an eager method) reclaims a space as soon as it is no longer referenced • Each block of allocated storage contains an extra count field, which stores the number of references to the block from other blocks • Each time a reference is changed, these reference counts must be updated • When the reference count drops to zero, the block can be returned to the free list
Drawbacks of Reference Counting • Need extra memory to keep the reference counts • The effort to maintain the reference counts can be fairly large • Circular references can cause unreferenced memory to never be deallocated
Maintaining Reference Counts void decrement(p){ p->refcount--; if (p->refcount == 0) { for all fields r of *p that are pointers do decrement(r); deallocate(*p); } }void assign(p, q){ decrement(p); p = q; q->refcount++;}
Circular References p p is deallocated
Mark and Sweep • It (a lazy method) puts off reclaiming any storage until the allocator runs out of space, at which point it looks for all storage that can be referenced and removes all unreferenced storage back to the free list • The first pass follows all pointers recursively, starting with the symbol table, and marks each of block reached with an extra bit • The second pass then sweeps linearly through memory, returning unmarked blocks to the free list
Drawbacks of Mark and Sweep • Need extra space to keep the marks • The double pass through memory causes a significant delay in processing, sometimes as much as a few seconds, each time the garbage collector is invoked, which can be every few minutes • Two improvements: stop and copy, and generational garbage collection
Stop and Copy • Splitting memory into two halves and allocating storage only from one half at a time • During the marking pass, all reached blocks are copied to the other half • No extra bit is required. Only one pass is required. Compaction is performed automatically
Generational Garbage Collection • A permanent storage area is added to the reclamation scheme • Allocated objects that survive long enough are simply copied into permanent space and are never deallocated during subsequent storage reclamations • The garbage collector needs to search only a very small section of memory for newer storage allocations