Docsity

Continuation and Exceptions - Programming Languages | CS 3723, Study notes of Programming Languages

Partial preview of the text

Download Continuation and Exceptions - Programming Languages | CS 3723 and more Study notes Programming Languages in PDF only on Docsity!

Continuation and

Exceptions

Control flow in sequential languages

Topics  Control flow --- ordering of sequential statements  Structured Programming (Goto considered harmful)  Continuation --- dynamic re-enterable evaluation  Function representing the rest of the expression  In functional programming, the rest of program  Include the enclosing environment as part of function closure  Convert expressions/functions to statements/loops  Exceptions --- dynamic jump to exit in unusual situations  Structured goto that may return a value  Dynamic scoping of exception handler  Manual control of evaluation order (force and delay)  Use function definitions to put off computations  Use function calls to force the evaluation of computations  Details skipped

Fortran Control Structure 10 IF (X .GT. 0.000001) GO TO 20 11 X = -X IF (X .LT. 0.000001) GO TO 50 20 IF (X*Y .LT. 0.00001) GO TO 30 X = X-Y-Y 30 X = X+Y ... 50 CONTINUE X = A Y = B-A GO TO 11 …

Similar structure may occur in assembly code

Controlling Jumps  Standard constructs that structure jumps if … then … else … end while … do … end for … { … } case …  Modern style  Group code in logical blocks  Avoid uncontrolled jumps  E.g., into the middle of a block without allocating local variables  What if I need to jump into the mid of a block?  E.g., interrupted tasks in OS; web applications (the back/forward button); check-pointing  The scenario: my task was interrupted, now I want to resume from where I stopped  Solution: save the entire runtime environment as a closure  Code pointer: where to start evaluating the instructions  Environment pointer: the entire relevant memory stores

Continuation of Expressions  Continuation: impose sequential ordering in sub-expressions  The continuation of an expression is “the remaining work to be done after evaluating the expression”  Continuation of e is a function applied to the result of e  Implementing control flow in functional languages  Evaluate current expression  Save the result into a variable  Evaluate the rest of the computation 2x + 3y + 1/x + 2/y let val r2x = 2 * x in let val r3y = 3 * y in let val sum1=r2x + r3y in let val r1x = 1 / x in let val sum2 = sum1 + r1x in let val r2y = 2 / y in sum2 + r2y end …….end let r2x = 2x in … end is equivalent to (fn r2x=> …) (2 * x) Continuation of 2x

Continuation and Tail Recursion  A function call from g to f is a tail callif g returns the result of calling f with no further computation  Example (red: tail call; blue: non-tail call) fun f(x) = if x > 0 then x else f(x+1)* fun f(x,y) = if x>y then x else f(2*x,y);  But most function calls are not tail calls  Can we convert all recursive functions to tail recursion?  If a program needs to be re-enterable, function calls shouldn’t return to caller  Solution: continuation passing  Pass continuation as parameter to callee  Callee does not need to return to caller

Tail Recursive Factorial

 Factorial in continuation passing style

fact(n, K) = if n=0 then K(1) else fact(n-1, λx.K (nx) )  Continuation of fact(n-1): λx.K (nx)  Cannot pop caller’s activation record before recursion -- need to save the local variable n

 Recursion  tail recursion loops

fun fact(n) = let val r = ref 1; val nl = ref 0 in while not (!nl=n) do

(nl := !nl + 1; r := !r * !nl);

!r end;

General uses of continuations  Explicit control  Normal termination -- call continuation  Abnormal termination -- do something else  Compilation techniques  Call to continuation is functional form of “go to”  Jump to the middle of a block by saving the environment in the function closure and restore the environment before jump  Web applications, Web Services, MOM and SOA services  Handle long running workflows  Workflow may take 1 year to complete  Progress of subtasks is asynchronous  Sequential programming is simpler than asynchronous  Continuations provide  An easy way to suspend workflow execution at a wait state  Thread of control can be resumed when the next message/event occurs, maybe some long time ahead

Exception: Alternative Way of Return  In C: can we tell whether “x” is in “l”? struct IntList { int x; IntList* rest;} IntList* remove(IntList* l, int x) { if (l == 0) return 0; if (l->x == x) return l->rest; l->rest = remove(l->rest,x); return l; }  In C++/Java, we can make sure only existing things are removed IntList* remove(IntList* l, int x) { if (l == 0) throw “no such element”; if (l->x == x) return l->rest; l->rest = remove(l->rest,x); return l; } IntList* removeIfExist(IntList* l, int x) { try { remove(l, x);} catch (const char*) { return l; } }  Two main language constructs  Statement or expression to raise or throw exception  Declaration to establish exception handler

Exception: A Controlled Dynamic Jump

 A normal jump is a static “goto label”

 Label is defined statically as the destination of jump  Label is defined in an enclosing scope of the jump  Examples  L:{ … continue… }: jump to start of current scope  {…break…}L: jump to end of current scope  {…return…}L: jump to end of current function

 An exception is a dynamic jump

 Don’t know where to resume execution until runtime  Jump out of current block  Look for a matching exception handler in enclosing scopes  Use dynamic scoping rule instead of static scoping

Defining Exceptions

 Exception declaration

 Type of data that can be passed in exception  ML: exception of  C++/Java: any data type

 Raising an exception

 Abort the rest of current block and jump out  ML: raise ;  C++: throw ;

 Handling an exception

 Continue normal execution after exception  ML: handle =>; ...  C++: try { …} catch ( var) {…} …

Exceptions in ML and in C++

 ML

exception X; let fun f(y) = (raise X; 1); fun g() = f(1) handle X => 2 in g() handle X => 4 end;

 C++

class X {}; int f(int y) {throw X(); return 1;} int g() { try { return f(1); } catch (X x) { return 2; } int main() { try { g(); } catch (X x) { return 4; }

cs3723 19 Dynamic Scope of Handler

exception X;

let fun f(y) = (raise X; 1);

fun g() =

f(1) handle X => 2

in g() handle X => 4

end;

handler X 2 access link formal y 1 access link g() f(1) fun f access link fun g

Dynamic scope:

find first X handler,

going up the

dynamic call chain

(control link instead

of access link)

leading to raise X.

handler X 4

Which handler is used?

 Dynamic scoping of handlers

 Multiple functions could handle the same

exception

 One function handles exception one way  Another function handles exception another way

 General dynamic scoping rule

Jump to most recently established handler on run-time stack

 Dynamic scoping is not an accident

 User knows how to handler error

 Author of library function does not