source:doc/theses/andrew_beach_MMath/features.tex@4ed7946e

Last change on this file since 4ed7946e was 4ed7946e, checked in by Peter A. Buhr <pabuhr@…>, 18 months ago

• Property mode set to 100644
File size: 32.9 KB
Line
1\chapter{Exception Features}
2\label{c:features}
3
4This chapter covers the design and user interface of the \CFA
5EHM, % or exception system.
6and begins with a general overview of EHMs. It is not a strict
7definition of all EHMs nor an exhaustive list of all possible features.
8However it does cover the most common structures and features found in them.
9
10% We should cover what is an exception handling mechanism and what is an
11% exception before this. Probably in the introduction. Some of this could
12% move there.
13\section{Raise / Handle}
14An exception operation has two main parts: raise and handle.
15These terms are sometimes also known as throw and catch but this work uses
16throw/catch as a particular kind of raise/handle.
17These are the two parts that the user writes and may
18be the only two pieces of the EHM that have any syntax in the language.
19
20\paragraph{Raise}
21The raise is the starting point for exception handling. It marks the beginning
22of exception handling by raising an exception, which passes it to
23the EHM.
24
25Some well known examples include the @throw@ statements of \Cpp and Java and
26the \code{Python}{raise} statement from Python. A raise may
27perform some other work (such as memory management) but for the
28purposes of this overview that can be ignored.
29
30\paragraph{Handle}
31The purpose of most exception operations is to run some user code to handle
32that exception. This code is given, with some other information, in a handler.
33
34A handler has three common features: the previously mentioned user code, a
35region of code they guard, and an exception label/condition that matches
36certain exceptions.
37Only raises inside the guarded region and raising exceptions that match the
38label can be handled by a given handler.
39Different EHMs have different rules to pick a handler,
40if multiple handlers could be used, such as best match" or first found".
41
42The @try@ statements of \Cpp, Java and Python are common examples. All three
43also show another common feature of handlers, they are grouped by the guarded
44region.
45
46\section{Propagation}
47After an exception is raised comes what is usually the biggest step for the
48EHM: finding and setting up the handler. The propagation from raise to
49handler can be broken up into three different tasks: searching for a handler,
50matching against the handler, and installing the handler.
51
52\paragraph{Searching}
53The EHM begins by searching for handlers that might be used to handle
54the exception. Searching is usually independent of the exception that was
55thrown as it looks for handlers that have the raise site in their guarded
56region.
57This search includes handlers in the current function, as well as any in callers
58on the stack that have the function call in their guarded region.
59
60\paragraph{Matching}
61Each handler found has to be matched with the raised exception. The exception
62label defines a condition that is used with the exception to decide if
63there is a match or not.
64
65In languages where the first match is used, this step is intertwined with
66searching: a match check is performed immediately after the search finds
67a possible handler.
68
69\section{Installing}
70After a handler is chosen it must be made ready to run.
71The implementation can vary widely to fit with the rest of the
72design of the EHM. The installation step might be trivial or it could be
73the most expensive step in handling an exception. The latter tends to be the
74case when stack unwinding is involved.
75
76If a matching handler is not guarantied to be found, the EHM needs a
77different course of action for the case where no handler matches.
78This situation only occurs with unchecked exceptions as checked exceptions
79(such as in Java) can make the guarantee.
80This unhandled action can abort the program or install a very general handler.
81
82\paragraph{Hierarchy}
83A common way to organize exceptions is in a hierarchical structure.
84This organization is often used in object-orientated languages where the
85exception hierarchy is a natural extension of the object hierarchy.
86
87Consider the following hierarchy of exceptions:
88\begin{center}
89\input{exception-hierarchy}
90\end{center}
91
92A handler labelled with any given exception can handle exceptions of that
93type or any child type of that exception. The root of the exception hierarchy
94(here \code{C}{exception}) acts as a catch-all, leaf types catch single types
95and the exceptions in the middle can be used to catch different groups of
96related exceptions.
97
98This system has some notable advantages, such as multiple levels of grouping,
99the ability for libraries to add new exception types and the isolation
100between different sub-hierarchies.
101This design is used in \CFA even though it is not a object-orientated
102language; so different tools are used to create the hierarchy.
103
104% Could I cite the rational for the Python IO exception rework?
105
106\paragraph{Completion}
107After the handler has finished the entire exception operation has to complete
108and continue executing somewhere else. This step is usually simple,
109both logically and in its implementation, as the installation of the handler
110is usually set up to do most of the work.
111
112The EHM can return control to many different places,
113the most common are after the handler definition (termination) and after the raise (resumption).
114
115\paragraph{Communication}
116For effective exception handling, additional information is often passed
117from the raise to the handler and back again.
118So far only communication of the exceptions' identity has been covered.
119A common communication method is putting fields into the exception instance and giving the
120handler access to them. References in the exception instance can push data back to the raise.
121
122\section{Virtuals}
123Virtual types and casts are not part of \CFA's EHM nor are they required for
124any EHM.
125However, one of the best ways to support an exception hierarchy is via a virtual system
126among exceptions and used for exception matching.
127
128Ideally, the virtual system would have been part of \CFA before the work
129on exception handling began, but unfortunately it was not.
130Therefore, only the features and framework needed for the EHM were
131designed and implemented. Other features were considered to ensure that
132the structure could accommodate other desirable features in the future but they were not
133implemented.
134The rest of this section discusses the implemented subset of the
135virtual-system design.
136
137The virtual system supports multiple trees" of types. Each tree is
138a simple hierarchy with a single root type. Each type in a tree has exactly
139one parent -- except for the root type which has zero parents -- and any
140number of children.
141Any type that belongs to any of these trees is called a virtual type.
142
143% A type's ancestors are its parent and its parent's ancestors.
144% The root type has no ancestors.
145% A type's decedents are its children and its children's decedents.
146
147Every virtual type also has a list of virtual members. Children inherit
148their parent's list of virtual members but may add new members to it.
149It is important to note that these are virtual members, not virtual methods
150of object-orientated programming, and can be of any type.
151
152\PAB{I do not understand these sentences. Can you add an example? $\Rightarrow$
153\CFA still supports virtual methods as a special case of virtual members.
154Function pointers that take a pointer to the virtual type are modified
155with each level of inheritance so that refers to the new type.
156This means an object can always be passed to a function in its virtual table
157as if it were a method.}
158
159Each virtual type has a unique id.
160This id and all the virtual members are combined
161into a virtual table type. Each virtual type has a pointer to a virtual table
162as a hidden field.
163
164\PAB{God forbid, maybe you need a UML diagram to relate these entities.}
165
166Up until this point the virtual system is similar to ones found in
167object-orientated languages but this where \CFA diverges. Objects encapsulate a
168single set of behaviours in each type, universally across the entire program,
169and indeed all programs that use that type definition. In this sense, the
170types are closed" and cannot be altered.
171
172In \CFA, types do not encapsulate any behaviour. Traits are local and
173types can begin to satisfy a trait, stop satisfying a trait or satisfy the same
174trait in a different way at any lexical location in the program.
175In this sense, they are open" as they can change at any time. This capability means it
176is impossible to pick a single set of functions that represent the type's
177implementation across the program.
178
179\CFA side-steps this issue by not having a single virtual table for each
180type. A user can define virtual tables that are filled in at their
181declaration and given a name. Anywhere that name is visible, even if
182defined locally inside a function (although that means it does not have a
183static lifetime), it can be used.
184Specifically, a virtual type is bound" to a virtual table that
185sets the virtual members for that object. The virtual members can be accessed
186through the object.
187
188\PAB{The above explanation is very good!}
189
190While much of the virtual infrastructure is created, it is currently only used
191internally for exception handling. The only user-level feature is the virtual
192cast
193\label{p:VirtualCast}
194\begin{cfa}
195(virtual TYPE)EXPRESSION
196\end{cfa}
197which is the same as the \Cpp \code{C++}{dynamic_cast}.
198Note, the syntax and semantics matches a C-cast, rather than the function-like
199\Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be
200a pointer to a virtual type.
201The cast dynamically checks if the @EXPRESSION@ type is the same or a sub-type
202of @TYPE@, and if true, returns a pointer to the
203@EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
204
205\section{Exception}
206% Leaving until later, hopefully it can talk about actual syntax instead
207% of my many strange macros. Syntax aside I will also have to talk about the
208% features all exceptions support.
209
210Exceptions are defined by the trait system; there are a series of traits, and
211if a type satisfies them, then it can be used as an exception. The following
212is the base trait all exceptions need to match.
213\begin{cfa}
214trait is_exception(exceptT &, virtualT &) {
215        // Numerous imaginary assertions.
216};
217\end{cfa}
218The trait is defined over two types, the exception type and the virtual table
219type. Each exception type should have a single virtual table type.
220There are no actual assertions in this trait because currently the trait system
221cannot express them (adding such assertions would be part of
222completing the virtual system). The imaginary assertions would probably come
223from a trait defined by the virtual system, and state that the exception type
224is a virtual type, is a descendent of @exception_t@ (the base exception type)
225and note its virtual table type.
226
227% I did have a note about how it is the programmer's responsibility to make
228% sure the function is implemented correctly. But this is true of every
229% similar system I know of (except Agda's I guess) so I took it out.
230
231There are two more traits for exceptions defined as follows:
232\begin{cfa}
233trait is_termination_exception(
234                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
235        void defaultTerminationHandler(exceptT &);
236};
237
238trait is_resumption_exception(
239                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
240        void defaultResumptionHandler(exceptT &);
241};
242\end{cfa}
243Both traits ensure a pair of types are an exception type and its virtual table,
244and defines one of the two default handlers. The default handlers are used
245as fallbacks and are discussed in detail in \vref{s:ExceptionHandling}.
246
247However, all three of these traits can be tricky to use directly.
248While there is a bit of repetition required,
249the largest issue is that the virtual table type is mangled and not in a user
250facing way. So these three macros are provided to wrap these traits to
251simplify referring to the names:
252@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
253
254All three take one or two arguments. The first argument is the name of the
255exception type. The macro passes its unmangled and mangled form to the trait.
256The second (optional) argument is a parenthesized list of polymorphic
257arguments. This argument is only used with polymorphic exceptions and the
258list is be passed to both types.
259In the current set-up, the two types always have the same polymorphic
260arguments so these macros can be used without losing flexibility.
261
262For example consider a function that is polymorphic over types that have a
263defined arithmetic exception:
264\begin{cfa}
265forall(Num | IS_EXCEPTION(Arithmetic, (Num)))
266void some_math_function(Num & left, Num & right);
267\end{cfa}
268
269\section{Exception Handling}
270\label{s:ExceptionHandling}
271As stated, \CFA provides two kinds of exception handling: termination and resumption.
272These twin operations are the core of \CFA's exception handling mechanism.
273This section covers the general patterns shared by the two operations and
274then go on to cover the details of each individual operation.
275
276Both operations follow the same set of steps.
278Then the exception propagates up the stack.
279If a handler is found the exception is caught and the handler is run.
280After that control returns to a point specific to the kind of exception.
281If the search fails a default handler is run, and if it returns, control
282continues after the raise. Note, the default handler may further change control flow rather than return.
283
284This general description covers what the two kinds have in common.
285Differences include how propagation is performed, where exception continues
286after an exception is caught and handled and which default handler is run.
287
288\subsection{Termination}
289\label{s:Termination}
290
291Termination handling is the familiar kind and used in most programming
292languages with exception handling.
293It is a dynamic, non-local goto. If the raised exception is matched and
294handled, the stack is unwound and control (usually) continues in the function
295on the call stack that defined the handler.
296Termination is commonly used when an error has occurred and recovery is
297impossible locally.
298
299% (usually) Control can continue in the current function but then a different
300% control flow construct should be used.
301
302A termination raise is started with the @throw@ statement:
303\begin{cfa}
304throw EXPRESSION;
305\end{cfa}
306The expression must return a reference to a termination exception, where the
307termination exception is any type that satisfies the trait
308@is_termination_exception@ at the call site.
309Through \CFA's trait system, the trait functions are implicitly passed into the
310throw code and the EHM.
311A new @defaultTerminationHandler@ can be defined in any scope to
312change the throw's behaviour (see below).
313
314The throw copies the provided exception into managed memory to ensure
315the exception is not destroyed when the stack is unwound.
316It is the user's responsibility to ensure the original exception is cleaned
317up whether the stack is unwound or not. Allocating it on the stack is
318usually sufficient.
319
320Then propagation starts the search. \CFA uses a first match" rule so
321matching is performed with the copied exception as the search continues.
322It starts from the throwing function and proceeds towards the base of the stack,
323from callee to caller.
324At each stack frame, a check is made for resumption handlers defined by the
325@catch@ clauses of a @try@ statement.
326\begin{cfa}
327try {
328        GUARDED_BLOCK
329} catch (EXCEPTION_TYPE$$$_1$$$ * [NAME$$$_1$$$]) {
330        HANDLER_BLOCK$$$_1$$$
331} catch (EXCEPTION_TYPE$$$_2$$$ * [NAME$$$_2$$$]) {
332        HANDLER_BLOCK$$$_2$$$
333}
334\end{cfa}
335When viewed on its own, a try statement simply executes the statements
336in \snake{GUARDED_BLOCK} and when those are finished, the try statement finishes.
337
338However, while the guarded statements are being executed, including any
339invoked functions, all the handlers in these statements are included on the search
340path. Hence, if a termination exception is raised, the search includes the added handlers associated with the guarded block and those further up the
341stack from the guarded block.
342
343Exception matching checks the handler in each catch clause in the order
344they appear, top to bottom. If the representation of the raised exception type
345is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$
346(if provided) is bound to a pointer to the exception and the statements in
347@HANDLER_BLOCK@$_i$ are executed.
348If control reaches the end of the handler, the exception is
349freed and control continues after the try statement.
350
351If no termination handler is found during the search, the default handler
352(\defaultTerminationHandler) visible at the raise statement is called.
353Through \CFA's trait system, the best match at the raise sight is used.
354This function is run and is passed the copied exception. If the default
355handler returns, control continues after the throw statement.
356
357There is a global @defaultTerminationHandler@ that is polymorphic over all
358termination exception types. Since it is so general, a more specific handler can be
359defined and is used for those types, effectively overriding the handler
360for a particular exception type.
361The global default termination handler performs a cancellation
362(see \vref{s:Cancellation}) on the current stack with the copied exception.
363
364\subsection{Resumption}
365\label{s:Resumption}
366
367Resumption exception handling is less common than termination but is
368just as old~\cite{Goodenough75} and is simpler in many ways.
369It is a dynamic, non-local function call. If the raised exception is
370matched a closure is taken from up the stack and executed,
371after which the raising function continues executing.
372These are most often used when a potentially repairable error occurs, some handler is found on the stack to fix it, and
373the raising function can continue with the correction.
374Another common usage is dynamic event analysis, \eg logging, without disrupting control flow.
375Note, if an event is raised and there is no interest, control continues normally.
376
378You may or may not want to mention it. You can still stick with \lstinline{catch} and \lstinline{throw/catchResume} in the thesis.}
379
380A resumption raise is started with the @throwResume@ statement:
381\begin{cfa}
382throwResume EXPRESSION;
383\end{cfa}
384It works much the same way as the termination throw.
385The expression must return a reference to a resumption exception,
386where the resumption exception is any type that satisfies the trait
387@is_resumption_exception@ at the call site.
388The assertions from this trait are available to
389the exception system, while handling the exception.
390
391Resumption does not need to copy the raised exception, as the stack is not unwound.
392The exception and
393any values on the stack remain in scope, while the resumption is handled.
394
395The EHM then begins propogation. The search starts from the raise in the
396resuming function and proceeds towards the base of the stack, from callee to caller.
397At each stack frame, a check is made for resumption handlers defined by the
398@catchResume@ clauses of a @try@ statement.
399\begin{cfa}
400try {
401        GUARDED_BLOCK
402} catchResume (EXCEPTION_TYPE$$$_1$$$ * [NAME$$$_1$$$]) {
403        HANDLER_BLOCK$$$_1$$$
404} catchResume (EXCEPTION_TYPE$$$_2$$$ * [NAME$$$_2$$$]) {
405        HANDLER_BLOCK$$$_2$$$
406}
407\end{cfa}
408% I wonder if there would be some good central place for this.
409Note that termination handlers and resumption handlers may be used together
410in a single try statement, intermixing @catch@ and @catchResume@ freely.
411Each type of handler only interacts with exceptions from the matching
412kind of raise.
413When a try statement is executed, it simply executes the statements in the
414@GUARDED_BLOCK@ and then returns.
415
416However, while the guarded statements are being executed, including any
417invoked functions, all the handlers in these statements are included on the search
418path. Hence, if a resumption exception is raised the search includes the added handlers associated with the guarded block and those further up the
419stack from the guarded block.
420
421Exception matching checks the handler in each catch clause in the order
422they appear, top to bottom. If the representation of the raised exception type
423is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$
424(if provided) is bound to a pointer to the exception and the statements in
425@HANDLER_BLOCK@$_i$ are executed.
426If control reaches the end of the handler, execution continues after the
427the raise statement that raised the handled exception.
428
429Like termination, if no resumption handler is found during the search, the default handler
430(\defaultResumptionHandler) visible at the raise statement is called.
431It uses the best match at the
433passed the exception given to the throw. When the default handler finishes
434execution continues after the raise statement.
435
436There is a global \defaultResumptionHandler{} that is polymorphic over all
437resumption exception types and preforms a termination throw on the exception.
438The \defaultTerminationHandler{} can be
439customized by introducing a new or better match as well.
440
441\subsubsection{Resumption Marking}
442\label{s:ResumptionMarking}
443
444A key difference between resumption and termination is that resumption does
445not unwind the stack. A side effect that is that when a handler is matched
446and run, its try block (the guarded statements) and every try statement
447searched before it are still on the stack. Their existence can lead to the recursive
448resumption problem.
449
450The recursive resumption problem is any situation where a resumption handler
451ends up being called while it is running.
452Consider a trivial case:
453\begin{cfa}
454try {
455        throwResume (E &){};
456} catchResume(E *) {
457        throwResume (E &){};
458}
459\end{cfa}
460When this code is executed, the guarded @throwResume@ starts a
461search and matchs the handler in the @catchResume@ clause. This
462call is placed on the top of stack above the try-block. The second throw
463searchs the same try block and puts call another instance of the
464same handler on the stack leading to an infinite recursion.
465
466While this situation is trivial and easy to avoid, much more complex cycles
467can form with multiple handlers and different exception types.
468
469To prevent all of these cases, the exception search marks the try statements it visits.
470A try statement is marked when a match check is preformed with it and an
471exception. The statement is unmarked when the handling of that exception
472is completed or the search completes without finding a handler.
473While a try statement is marked, its handlers are never matched, effectify
474skipping over them to the next try statement.
475
476\begin{center}
477\input{stack-marking}
478\end{center}
479
480These rules mirror what happens with termination.
481When a termination throw happens in a handler, the search does not look at
482any handlers from the original throw to the original catch because that
483part of the stack is unwound.
484A resumption raise in the same situation wants to search the entire stack,
485but with marking, the search does match exceptions for try statements at equivalent sections
486that would have been unwound by termination.
487
488The symmetry between resumption termination is why this pattern is picked.
489Other patterns, such as marking just the handlers that caught the exception, also work but
490lack the symmetry, meaning there are more rules to remember.
491
492\section{Conditional Catch}
493
494Both termination and resumption handler clauses can be given an additional
495condition to further control which exceptions they handle:
496\begin{cfa}
497catch (EXCEPTION_TYPE * [NAME] ; CONDITION)
498\end{cfa}
499First, the same semantics is used to match the exception type. Second, if the
500exception matches, @CONDITION@ is executed. The condition expression may
501reference all names in scope at the beginning of the try block and @NAME@
502introduced in the handler clause. If the condition is true, then the handler
503matches. Otherwise, the exception search continues as if the exception type
504did not match.
505
506The condition matching allows finer matching to check
507more kinds of information than just the exception type.
508\begin{cfa}
509try {
510        handle1 = open( f1, ... );
511        handle2 = open( f2, ... );
512        handle3 = open( f3, ... );
513        ...
514} catch( IOFailure * f ; fd( f ) == f1 ) {
515        // Only handle IO failure for f1.
516} catch( IOFailure * f ; fd( f ) == f3 ) {
517        // Only handle IO failure for f3.
518}
519// Can't handle a failure relating to f2 here.
520\end{cfa}
521In this example, the file that experianced the IO error is used to decide
522which handler should be run, if any at all.
523
524\begin{comment}
525% I know I actually haven't got rid of them yet, but I'm going to try
526% to write it as if I had and see if that makes sense:
527\section{Reraising}
528\label{s:Reraising}
529Within the handler block or functions called from the handler block, it is
530possible to reraise the most recently caught exception with @throw@ or
531@throwResume@, respectively.
532\begin{cfa}
533try {
534        ...
535} catch( ... ) {
536        ... throw;
537} catchResume( ... ) {
538        ... throwResume;
539}
540\end{cfa}
541The only difference between a raise and a reraise is that reraise does not
542create a new exception; instead it continues using the current exception, \ie
543no allocation and copy. However the default handler is still set to the one
544visible at the raise point, and hence, for termination could refer to data that
545is part of an unwound stack frame. To prevent this problem, a new default
546handler is generated that does a program-level abort.
547\end{comment}
548
549\subsection{Comparison with Reraising}
550
551A more popular way to allow handlers to match in more detail is to reraise
552the exception after it has been caught, if it could not be handled here.
553On the surface these two features seem interchangable.
554
555If @throw@ is used to start a termination reraise then these two statements
556have the same behaviour:
557\begin{cfa}
558try {
559    do_work_may_throw();
560} catch(exception_t * exc ; can_handle(exc)) {
561    handle(exc);
562}
563\end{cfa}
564
565\begin{cfa}
566try {
567    do_work_may_throw();
568} catch(exception_t * exc) {
569    if (can_handle(exc)) {
570        handle(exc);
571    } else {
572        throw;
573    }
574}
575\end{cfa}
576However, if there are further handlers after this handler only the first is
577check. For multiple handlers on a single try block that could handle the
578same exception, the equivalent translations to conditional catch becomes more complex, resulting is multiple nested try blocks for all possible reraises.
579So while catch-with-reraise is logically equivilant to conditional catch, there is a lexical explosion for the former.
580
581\PAB{I think the following discussion makes an incorrect assumption.
582A conditional catch CAN happen with the stack unwound.
584\url{http://plg.uwaterloo.ca/theses/KrischerThesis.pdf}}
585
586Specifically for termination handling, a
587conditional catch happens before the stack is unwound, but a reraise happens
588afterwards. Normally this might only cause you to loose some debug
589information you could get from a stack trace (and that can be side stepped
590entirely by collecting information during the unwind). But for \CFA there is
591another issue, if the exception is not handled the default handler should be
592run at the site of the original raise.
593
594There are two problems with this: the site of the original raise does not
595exist anymore and the default handler might not exist anymore. The site is
596always removed as part of the unwinding, often with the entirety of the
597function it was in. The default handler could be a stack allocated nested
598function removed during the unwind.
599
600This means actually trying to pretend the catch didn't happening, continuing
601the original raise instead of starting a new one, is infeasible.
602That is the expected behaviour for most languages and we can't replicate
603that behaviour.
604
605\section{Finally Clauses}
606\label{s:FinallyClauses}
607
608Finally clauses are used to preform unconditional clean-up when leaving a
609scope and are placed at the end of a try statement after any handler clauses:
610\begin{cfa}
611try {
612        GUARDED_BLOCK
613} ... // any number or kind of handler clauses
614... finally {
615        FINALLY_BLOCK
616}
617\end{cfa}
618The @FINALLY_BLOCK@ is executed when the try statement is removed from the
619stack, including when the @GUARDED_BLOCK@ finishes, any termination handler
620finishes, or during an unwind.
621The only time the block is not executed is if the program is exited before
622the stack is unwound.
623
624Execution of the finally block should always finish, meaning control runs off
625the end of the block. This requirement ensures control always continues as if
626the finally clause is not present, \ie finally is for cleanup not changing
627control flow.
628Because of this requirement, local control flow out of the finally block
629is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or
630@return@ that causes control to leave the finally block. Other ways to leave
631the finally block, such as a long jump or termination are much harder to check,
633discouraged.
634
635Not all languages with unwinding have finally clauses. Notably \Cpp does
636without it as destructors with RAII serve a similar role. Although destructors and
637finally clauses have overlapping usage cases, they have their own
638specializations, like top-level functions and lambda functions with closures.
639Destructors take more work if a number of unrelated, local variables without destructors or dynamically allocated variables must be passed for de-intialization.
640Maintaining this destructor during local-block modification is a source of errors.
641A finally clause places local de-intialization inline with direct access to all local variables.
642
643\section{Cancellation}
644\label{s:Cancellation}
645Cancellation is a stack-level abort, which can be thought of as as an
646uncatchable termination. It unwinds the entire current stack, and if
647possible forwards the cancellation exception to a different stack.
648
649Cancellation is not an exception operation like termination or resumption.
650There is no special statement for starting a cancellation; instead the standard
651library function @cancel_stack@ is called passing an exception. Unlike a
652raise, this exception is not used in matching only to pass information about
653the cause of the cancellation.
654(This restriction also means matching cannot fail so there is no default handler.)
655
656After @cancel_stack@ is called the exception is copied into the EHM's memory
657and the current stack is
658unwound.
659The result of a cancellation depends on the kind of stack that is being unwound.
660
661\paragraph{Main Stack}
662The main stack is the one used by the program main at the start of execution,
663and is the only stack in a sequential program.
664After the main stack is unwound there is a program-level abort.
665
666There are two reasons for this semantics. The first is that it obviously had to do the abort
667in a sequential program as there is nothing else to notify and the simplicity
668of keeping the same behaviour in sequential and concurrent programs is good.
669\PAB{I do not understand this sentence. $\Rightarrow$ Also, even in concurrent programs, there is no stack that an innate connection
670to, so it would have be explicitly managed.}
671
673A thread stack is created for a \CFA @thread@ object or object that satisfies
675After a thread stack is unwound, the exception is stored until another
677which stores a reference to the thread and to the exception passed to the
678cancellation, is reported from the join to the joining thread.
679There is one difference between an explicit join (with the @join@ function)
680and an implicit join (from a destructor call). The explicit join takes the
681default handler (@defaultResumptionHandler@) from its calling context while
682the implicit join provides its own, which does a program abort if the
684
685\PAB{Communication can occur during the lifetime of a thread using shared variable and \lstinline{waitfor} statements.
686Are you sure you mean communication here? Maybe you mean synchronization (rendezvous) point. $\Rightarrow$ Communication is done at join because a thread only has two points of
687communication with other threads: start and join.}
688Since a thread must be running to perform a cancellation (and cannot be
689cancelled from another stack), the cancellation must be after start and
690before the join, so join is use.
691
692% TODO: Find somewhere to discuss unwind collisions.
693The difference between the explicit and implicit join is for safety and
694debugging. It helps prevent unwinding collisions by avoiding throwing from
696the user is not equipped to deal with it.
697Also you can always add an explicit join if that is the desired behaviour.
698
699\paragraph{Coroutine Stack}
700A coroutine stack is created for a @coroutine@ object or object that
701satisfies the @is_coroutine@ trait.
702After a coroutine stack is unwound, control returns to the @resume@ function
703that most recently resumed it. The resume reports a
704@CoroutineCancelled@ exception, which contains references to the cancelled
705coroutine and the exception used to cancel it.
706The @resume@ function also takes the \defaultResumptionHandler{} from the
707caller's context and passes it to the internal cancellation.
708
709A coroutine knows of two other coroutines, its starter and its last resumer.
710The starter has a much more distant connection, while the last resumer just
711(in terms of coroutine state) called resume on this coroutine, so the message
712is passed to the latter.
Note: See TracBrowser for help on using the repository browser.