source: doc/theses/andrew_beach_MMath/features.tex @ 4260566

Last change on this file since 4260566 was 4260566, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Andrew MMath: Clean-up of features.tex. Put more general EHM information in the opening and started updating the virtual section.

  • Property mode set to 100644
File size: 27.3 KB
1\chapter{Exception Features}
3This chapter covers the design and user interface of the \CFA
4exception-handling mechanism (EHM). % or exception system.
6% We should cover what is an exception handling mechanism and what is an
7% exception before this. Probably in the introduction. Some of this could
8% move there.
9\paragraph{Raise / Handle}
10An exception operation has two main parts: raise and handle.
11These are the two parts that the user will write themselves and so
12might be the only two pieces of the EHM that have any syntax.
13These terms are sometimes also known as throw and catch but this work uses
14throw/catch as a particular kind of raise/handle.
17The raise is the starting point for exception handling and usually how
18Some well known examples include the throw statements of \Cpp and Java and
19the raise statement from Python.
21For this overview a raise does nothing more kick off the handling of an
22exception, which is called raising the exception. This is inexact but close
23enough for the broad strokes of the overview.
26The purpose of most exception operations is to run some sort of handler that
27contains user code.
28The try statement of \Cpp illistrates the common features
29Handlers have three common features: a region of code they apply to, an
30exception label that describes what exceptions they handle and code to run
31when they handle an exception.
32Each handler can handle exceptions raised in that region that match their
33exception label. Different EHMs will have different rules to pick a handler
34if multipe handlers could be used such as ``best match" or ``first found".
37After an exception is raised comes what is usually the biggest step for the
38EHM, finding and setting up the handler. This can be broken up into three
39different tasks: searching for a handler, matching against the handler and
40installing the handler.
42First the EHM must search for possible handlers that could be used to handle
43the exception. Searching is usually independent of the exception that was
44thrown and instead depends on the call stack, the current function, its caller
45and repeating down the stack.
47Second it much match the exception with each handler to see which one is the
48best match and hence which one should be used to handle the exception.
49In languages where the best match is the first match these two are often
50intertwined, a match check is preformed immediately after the search finds
51a possible handler.
53Third, after a handler is chosen it must be made ready to run.
54What this actually involves can vary widely to fit with the rest of the
55design of the EHM. The installation step might be trivial or it could be
56the most expensive step in handling an exception. The latter tends to be the
57case when stack unwinding is involved.
59As an alternate third step if no appropriate handler is found then some sort
60of recovery has to be preformed. This is only required with unchecked
61exceptions as checked exceptions can promise that a handler is found. It also
62is also installing a handler but it is a special default that may be
63installed differently.
66In \CFA the EHM uses a hierarchial system to organise its exceptions.
67This stratagy is borrowed from object-orientated languages where the
68exception hierarchy is a natural extension of the object hierarchy.
70Consider the following hierarchy of exceptions:
74\put(2100,-1411){\vector(1, 0){225}}
75\put(3450,-1411){\vector(1, 0){225}}
77\put(3550,-1636){\vector(1, 0){150}}
79\put(3550,-1861){\vector(1, 0){150}}
88A handler labelled with any given exception can handle exceptions of that
89type or any child type of that exception. The root of the exception hierarchy
90(here \texttt{exception}) acts as a catch-all, leaf types catch single types
91and the exceptions in the middle can be used to catch different groups of
92related exceptions.
94This system has some notable advantages, such as multiple levels of grouping,
95the ability for libraries to add new exception types and the isolation
96between different sub-hierarchies. So the design was adapted for a
97non-object-orientated language.
99% Could I cite the rational for the Python IO exception rework?
102After the handler has finished the entire exception operation has to complete
103and continue executing somewhere else. This step is usually very simple
104both logically and in its implementation as the installation of the handler
105usually does the heavy lifting.
107The EHM can return control to many different places.
108However, the most common is after the handler definition and the next most
109common is after the raise.
112For effective exception handling, additional information is usually required
113as this base model only communicates the exception's identity. Common
114additional methods of communication are putting fields on an exception and
115allowing a handler to access the lexical scope it is defined in (usually
116a function's local variables).
118\paragraph{Other Features}
119Any given exception handling mechanism is free at add other features on top
120of this. This is an overview of the base that all EHMs use but it is not an
121exaustive list of everything an EHM can do.
124Virtual types and casts are not part of the exception system nor are they
125required for an exception system. But an object-oriented style hierarchy is a
126great way of organizing exceptions so a minimal virtual system has been added
127to \CFA.
129The virtual system supports multiple ``trees" of types. Each tree is
130a simple hierarchy with a single root type. Each type in a tree has exactly
131one parent - except for the root type which has zero parents - and any
132number of children.
133Any type that belongs to any of these trees is called a virtual type.
135% A type's ancestors are its parent and its parent's ancestors.
136% The root type has no ancestors.
137% A type's decendents are its children and its children's decendents.
139Every virtual type also has a list of virtual members. Children inherit
140their parent's list of virtual members but may add new members to it.
141It is important to note that these are virtual members, not virtual methods.
142However as function pointers are allowed they can be used to mimic virtual
143methods as well.
145The unique id for the virtual type and all the virtual members are combined
146into a virtual table type. Each virtual type has a pointer to a virtual table
147as a hidden field.
149\todo{Open/Closed types and how that affects the virtual design.}
151While much of the virtual infrastructure is created, it is currently only used
152internally for exception handling. The only user-level feature is the virtual
153cast, which is the same as the \Cpp \lstinline[language=C++]|dynamic_cast|.
158Note, the syntax and semantics matches a C-cast, rather than the function-like
159\Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be
160a pointer to a virtual type.
161The cast dynamically checks if the @EXPRESSION@ type is the same or a sub-type
162of @TYPE@, and if true, returns a pointer to the
163@EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
166% Leaving until later, hopefully it can talk about actual syntax instead
167% of my many strange macros. Syntax aside I will also have to talk about the
168% features all exceptions support.
170Exceptions are defined by the trait system; there are a series of traits, and
171if a type satisfies them, then it can be used as an exception. The following
172is the base trait all exceptions need to match.
174trait is_exception(exceptT &, virtualT &) {
175        virtualT const & get_exception_vtable(exceptT *);
178The trait is defined over two types, the exception type and the virtual table
179type. This should be one-to-one, each exception type has only one virtual
180table type and vice versa. The only assertion in the trait is
181@get_exception_vtable@, which takes a pointer of the exception type and
182returns a reference to the virtual table type instance.
184The function @get_exception_vtable@ is actually a constant function.
185Regardless of the value passed in (including the null pointer) it should
186return a reference to the virtual table instance for that type.
187The reason it is a function instead of a constant is that it make type
188annotations easier to write as you can use the exception type instead of the
189virtual table type; which usually has a mangled name.
190% Also \CFA's trait system handles functions better than constants and doing
191% it this way reduce the amount of boiler plate we need.
193% I did have a note about how it is the programmer's responsibility to make
194% sure the function is implemented correctly. But this is true of every
195% similar system I know of (except Agda's I guess) so I took it out.
197There are two more traits for exceptions @is_termination_exception@ and
198@is_resumption_exception@. They are defined as follows:
201trait is_termination_exception(
202                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
203        void defaultTerminationHandler(exceptT &);
206trait is_resumption_exception(
207                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
208        void defaultResumptionHandler(exceptT &);
212In other words they make sure that a given type and virtual type is an
213exception and defines one of the two default handlers. These default handlers
214are used in the main exception handling operations \see{Exception Handling}
215and their use will be detailed there.
217However all three of these traits can be tricky to use directly.
218There is a bit of repetition required but
219the largest issue is that the virtual table type is mangled and not in a user
220facing way. So there are three macros that can be used to wrap these traits
221when you need to refer to the names:
224All take one or two arguments. The first argument is the name of the
225exception type. Its unmangled and mangled form are passed to the trait.
226The second (optional) argument is a parenthesized list of polymorphic
227arguments. This argument should only with polymorphic exceptions and the
228list will be passed to both types.
229In the current set-up the base name and the polymorphic arguments have to
230match so these macros can be used without losing flexibility.
232For example consider a function that is polymorphic over types that have a
233defined arithmetic exception:
235forall(Num | IS_EXCEPTION(Arithmetic, (Num)))
236void some_math_function(Num & left, Num & right);
239\section{Exception Handling}
240\CFA provides two kinds of exception handling, termination and resumption.
241These twin operations are the core of the exception handling mechanism and
242are the reason for the features of exceptions.
243This section will cover the general patterns shared by the two operations and
244then go on to cover the details each individual operation.
246Both operations follow the same set of steps to do their operation. They both
247start with the user preforming a throw on an exception.
248Then there is the search for a handler, if one is found than the exception
249is caught and the handler is run. After that control returns to normal
252If the search fails a default handler is run and then control
253returns to normal execution immediately. That is where the default handlers
254@defaultTermiationHandler@ and @defaultResumptionHandler@ are used.
259Termination handling is more familiar kind and used in most programming
260languages with exception handling.
261It is dynamic, non-local goto. If a throw is successful then the stack will
262be unwound and control will (usually) continue in a different function on
263the call stack. They are commonly used when an error has occurred and recovery
264is impossible in the current function.
266% (usually) Control can continue in the current function but then a different
267% control flow construct should be used.
269A termination throw is started with the @throw@ statement:
271throw EXPRESSION;
273The expression must return a reference to a termination exception, where the
274termination exception is any type that satisfies @is_termination_exception@
275at the call site.
276Through \CFA's trait system the functions in the traits are passed into the
277throw code. A new @defaultTerminationHandler@ can be defined in any scope to
278change the throw's behavior (see below).
280The throw will copy the provided exception into managed memory. It is the
281user's responsibility to ensure the original exception is cleaned up if the
282stack is unwound (allocating it on the stack should be sufficient).
284Then the exception system searches the stack using the copied exception.
285It starts starts from the throw and proceeds to the base of the stack,
286from callee to caller.
287At each stack frame, a check is made for resumption handlers defined by the
288@catch@ clauses of a @try@ statement.
290try {
291        GUARDED_BLOCK
292} catch (EXCEPTION_TYPE$\(_1\)$ * NAME$\(_1\)$) {
293        HANDLER_BLOCK$\(_1\)$
294} catch (EXCEPTION_TYPE$\(_2\)$ * NAME$\(_2\)$) {
295        HANDLER_BLOCK$\(_2\)$
298When viewed on its own a try statement will simply execute the statements in
299@GUARDED_BLOCK@ and when those are finished the try statement finishes.
301However, while the guarded statements are being executed, including any
302functions they invoke, all the handlers following the try block are now
303or any functions invoked from those
304statements, throws an exception, and the exception
305is not handled by a try statement further up the stack, the termination
306handlers are searched for a matching exception type from top to bottom.
308Exception matching checks the representation of the thrown exception-type is
309the same or a descendant type of the exception types in the handler clauses. If
310it is the same of a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ is
311bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$
312are executed. If control reaches the end of the handler, the exception is
313freed and control continues after the try statement.
315If no handler is found during the search then the default handler is run.
316Through \CFA's trait system the best match at the throw sight will be used.
317This function is run and is passed the copied exception. After the default
318handler is run control continues after the throw statement.
320There is a global @defaultTerminationHandler@ that cancels the current stack
321with the copied exception. However it is generic over all exception types so
322new default handlers can be defined for different exception types and so
323different exception types can have different default handlers.
328Resumption exception handling is a less common form than termination but is
329just as old~\cite{Goodenough75} and is in some sense simpler.
330It is a dynamic, non-local function call. If the throw is successful a
331closure will be taken from up the stack and executed, after which the throwing
332function will continue executing.
333These are most often used when an error occurred and if the error is repaired
334then the function can continue.
336A resumption raise is started with the @throwResume@ statement:
338throwResume EXPRESSION;
340The semantics of the @throwResume@ statement are like the @throw@, but the
341expression has return a reference a type that satisfies the trait
342@is_resumption_exception@. The assertions from this trait are available to
343the exception system while handling the exception.
345At run-time, no copies are made. As the stack is not unwound the exception and
346any values on the stack will remain in scope while the resumption is handled.
348Then the exception system searches the stack using the provided exception.
349It starts starts from the throw and proceeds to the base of the stack,
350from callee to caller.
351At each stack frame, a check is made for resumption handlers defined by the
352@catchResume@ clauses of a @try@ statement.
354try {
355        GUARDED_BLOCK
356} catchResume (EXCEPTION_TYPE$\(_1\)$ * NAME$\(_1\)$) {
357        HANDLER_BLOCK$\(_1\)$
358} catchResume (EXCEPTION_TYPE$\(_2\)$ * NAME$\(_2\)$) {
359        HANDLER_BLOCK$\(_2\)$
362If the handlers are not involved in a search this will simply execute the
363@GUARDED_BLOCK@ and then continue to the next statement.
364Its purpose is to add handlers onto the stack.
365(Note, termination and resumption handlers may be intermixed in a @try@
366statement but the kind of throw must be the same as the handler for it to be
367considered as a possible match.)
369If a search for a resumption handler reaches a try block it will check each
370@catchResume@ clause, top-to-bottom.
371At each handler if the thrown exception is or is a child type of
372@EXCEPTION_TYPE@$_i$ then the a pointer to the exception is bound to
373@NAME@$_i$ and then @HANDLER_BLOCK@$_i$ is executed. After the block is
374finished control will return to the @throwResume@ statement.
376Like termination, if no resumption handler is found, the default handler
377visible at the throw statement is called. It will use the best match at the
378call sight according to \CFA's overloading rules. The default handler is
379passed the exception given to the throw. When the default handler finishes
380execution continues after the throw statement.
382There is a global @defaultResumptionHandler@ is polymorphic over all
383termination exceptions and preforms a termination throw on the exception.
384The @defaultTerminationHandler@ for that throw is matched at the original
385throw statement (the resumption @throwResume@) and it can be customized by
386introducing a new or better match as well.
388% \subsubsection?
390A key difference between resumption and termination is that resumption does
391not unwind the stack. A side effect that is that when a handler is matched
392and run it's try block (the guarded statements) and every try statement
393searched before it are still on the stack. This can lead to the recursive
394resumption problem.
396The recursive resumption problem is any situation where a resumption handler
397ends up being called while it is running.
398Consider a trivial case:
400try {
401        throwResume (E &){};
402} catchResume(E *) {
403        throwResume (E &){};
406When this code is executed the guarded @throwResume@ will throw, start a
407search and match the handler in the @catchResume@ clause. This will be
408call and placed on the stack on top of the try-block. The second throw then
409throws and will search the same try block and put call another instance of the
410same handler leading to an infinite loop.
412This situation is trivial and easy to avoid, but much more complex cycles
413can form with multiple handlers and different exception types.
415To prevent all of these cases we mask sections of the stack, or equivalently
416the try statements on the stack, so that the resumption search skips over
417them and continues with the next unmasked section of the stack.
419A section of the stack is marked when it is searched to see if it contains
420a handler for an exception and unmarked when that exception has been handled
421or the search was completed without finding a handler.
423% This might need a diagram. But it is an important part of the justification
424% of the design of the traversal order.
426       throwResume2 ----------.
427            |                 |
428 generated from handler       |
429            |                 |
430         handler              |
431            |                 |
432        throwResume1 -----.   :
433            |             |   :
434           try            |   : search skip
435            |             |   :
436        catchResume  <----'   :
437            |                 |
440The rules can be remembered as thinking about what would be searched in
441termination. So when a throw happens in a handler; a termination handler
442skips everything from the original throw to the original catch because that
443part of the stack has been unwound, a resumption handler skips the same
444section of stack because it has been masked.
445A throw in a default handler will preform the same search as the original
446throw because; for termination nothing has been unwound, for resumption
447the mask will be the same.
449The symmetry with termination is why this pattern was picked. Other patterns,
450such as marking just the handlers that caught, also work but lack the
451symmetry which means there is more to remember.
453\section{Conditional Catch}
454Both termination and resumption handler clauses can be given an additional
455condition to further control which exceptions they handle:
459First, the same semantics is used to match the exception type. Second, if the
460exception matches, @CONDITION@ is executed. The condition expression may
461reference all names in scope at the beginning of the try block and @NAME@
462introduced in the handler clause. If the condition is true, then the handler
463matches. Otherwise, the exception search continues as if the exception type
464did not match.
466try {
467        f1 = open( ... );
468        f2 = open( ... );
469        ...
470} catch( IOFailure * f ; fd( f ) == f1 ) {
471        // only handle IO failure for f1
474Note, catching @IOFailure@, checking for @f1@ in the handler, and re-raising the
475exception if not @f1@ is different because the re-raise does not examine any of
476remaining handlers in the current try statement.
479\colour{red}{From Andrew: I recomend we talk about why the language doesn't
480have rethrows/reraises instead.}
483Within the handler block or functions called from the handler block, it is
484possible to reraise the most recently caught exception with @throw@ or
485@throwResume@, respectively.
487try {
488        ...
489} catch( ... ) {
490        ... throw;
491} catchResume( ... ) {
492        ... throwResume;
495The only difference between a raise and a reraise is that reraise does not
496create a new exception; instead it continues using the current exception, \ie
497no allocation and copy. However the default handler is still set to the one
498visible at the raise point, and hence, for termination could refer to data that
499is part of an unwound stack frame. To prevent this problem, a new default
500handler is generated that does a program-level abort.
502\section{Finally Clauses}
503Finally clauses are used to preform unconditional clean-up when leaving a
504scope. They are placed at the end of a try statement:
506try {
507        GUARDED_BLOCK
508} ... // any number or kind of handler clauses
509... finally {
510        FINALLY_BLOCK
513The @FINALLY_BLOCK@ is executed when the try statement is removed from the
514stack, including when the @GUARDED_BLOCK@ finishes, any termination handler
515finishes or during an unwind.
516The only time the block is not executed is if the program is exited before
517the stack is unwound.
519Execution of the finally block should always finish, meaning control runs off
520the end of the block. This requirement ensures always continues as if the
521finally clause is not present, \ie finally is for cleanup not changing control
522flow. Because of this requirement, local control flow out of the finally block
523is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or
524@return@ that causes control to leave the finally block. Other ways to leave
525the finally block, such as a long jump or termination are much harder to check,
526and at best requiring additional run-time overhead, and so are mealy
529Not all languages with exceptions have finally clauses. Notably \Cpp does
530without it as descructors serve a similar role. Although destructors and
531finally clauses can be used in many of the same areas they have their own
532use cases like top-level functions and lambda functions with closures.
533Destructors take a bit more work to set up but are much easier to reuse while
534finally clauses are good for once offs and can include local information.
537Cancellation is a stack-level abort, which can be thought of as as an
538uncatchable termination. It unwinds the entirety of the current stack, and if
539possible forwards the cancellation exception to a different stack.
541Cancellation is not an exception operation like termination or resumption.
542There is no special statement for starting a cancellation; instead the standard
543library function @cancel_stack@ is called passing an exception. Unlike a
544throw, this exception is not used in matching only to pass information about
545the cause of the cancellation.
546(This also means matching cannot fail so there is no default handler either.)
548After @cancel_stack@ is called the exception is copied into the exception
549handling mechanism's memory. Then the entirety of the current stack is
550unwound. After that it depends one which stack is being cancelled.
552\item[Main Stack:]
553The main stack is the one used by the program main at the start of execution,
554and is the only stack in a sequential program. Even in a concurrent program
555the main stack is only dependent on the environment that started the program.
556Hence, when the main stack is cancelled there is nowhere else in the program
557to notify. After the stack is unwound, there is a program-level abort.
559\item[Thread Stack:]
560A thread stack is created for a @thread@ object or object that satisfies the
561@is_thread@ trait. A thread only has two points of communication that must
562happen: start and join. As the thread must be running to perform a
563cancellation, it must occur after start and before join, so join is used
564for communication here.
565After the stack is unwound, the thread halts and waits for
566another thread to join with it. The joining thread checks for a cancellation,
567and if present, resumes exception @ThreadCancelled@.
569There is a subtle difference between the explicit join (@join@ function) and
570implicit join (from a destructor call). The explicit join takes the default
571handler (@defaultResumptionHandler@) from its calling context, which is used if
572the exception is not caught. The implicit join does a program abort instead.
574This semantics is for safety. If an unwind is triggered while another unwind
575is underway only one of them can proceed as they both want to ``consume'' the
576stack. Letting both try to proceed leads to very undefined behaviour.
577Both termination and cancellation involve unwinding and, since the default
578@defaultResumptionHandler@ preforms a termination that could more easily
579happen in an implicate join inside a destructor. So there is an error message
580and an abort instead.
581\todo{Perhaps have a more general disucssion of unwind collisions before
582this point.}
584The recommended way to avoid the abort is to handle the initial resumption
585from the implicate join. If required you may put an explicate join inside a
586finally clause to disable the check and use the local
587@defaultResumptionHandler@ instead.
589\item[Coroutine Stack:] A coroutine stack is created for a @coroutine@ object
590or object that satisfies the @is_coroutine@ trait. A coroutine only knows of
591two other coroutines, its starter and its last resumer. Of the two the last
592resumer has the tightest coupling to the coroutine it activated and the most
593up-to-date information.
595Hence, cancellation of the active coroutine is forwarded to the last resumer
596after the stack is unwound. When the resumer restarts, it resumes exception
597@CoroutineCancelled@, which is polymorphic over the coroutine type and has a
598pointer to the cancelled coroutine.
600The resume function also has an assertion that the @defaultResumptionHandler@
601for the exception. So it will use the default handler like a regular throw.
Note: See TracBrowser for help on using the repository browser.