15-312 Recitation #5: The C-machine and Escaping Exceptions 2002-09-25 Joshua Dunfield (joshuad@cs) Carnegie Mellon University ASST2 ----- ... ASST3 ----- ... THE C-MACHINE: SUMS ------------------- C-machine review: k > e evaluate e under k k < v return v to k Stacks k: empty k |> f (Note: supplementary notes and the Harper book disagree on which direction stacks grow.) k > inl(e1) |-> k |> inl([]) > e1 k |> inl([]) < v1 |-> k < inl(v1) k > case(e, xL.eL, xR.eR) |-> k |> case([], xL.eL, xR.eR) > e k |> case([], xL.eL, xR.eR) < inl(v) |-> k > {v/xL} eL " " " ( " " ) < inr(v) |-> k > {v/xR} eR (Need subscripted types.) Implementation left as an exercise (possibly part of asst4). ASST4 PREVIEW ------------- - try e1 catch v2 with e3 end try(e1,v2,e3) - raise(e) raise(e) - exception x in e end exception(x.e) Review of exception handling in ML: exception E raise E e1 handle p1 => e1 | p2 => e2 ... fun f x = let exception E in raise E; x+1 end (f 5) handle E => 0 [Somewhat irrelevant trick question!] [Answer: returns 0. E is not in scope, so E is a wildcard pattern.] Another example: fun g y = let exception E of string in E("XX") end val g : fn : 'a -> exn - g 3; val it = E(-) : exn In fact, exceptions are *generative*. I'll post example code (disturbing.sml), but the main point is that every time f is applied to an argument, a *new* exception E, different from all other exceptions, is created. Some people like this... (!) For the assignment, we'll take the view that this whole business of exceptions escaping their scope -- either by being raised, or by being returned as values -- is just too weird. Hence we'll write an operational semantics in which exceptions cannot escape; if they "try" (pun intended), it is a runtime error (the machine enters some error state). In the assignment, the "try" construct will not have a pattern. It will only allow you to compare the raised exception to one exception; if that particular exception was raised, the handler will be invoked. Example: exception E in try raise E catch E with (* E can't be wildcard *) 35 end end Examples: exception E in E end E about to escape: error state exception E in (E, 2) end Same (E can't run, E can't hide inside a subexpression!). exception E in raise E end E about to escape by being raised: error state Part of asst4 will be to figure out (and then implement) the right C-machine rules to get the above behavior.