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

arm-ehenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-expr
Last change on this file since c21f5a9 was c21f5a9, checked in by Andrew Beach <ajbeach@…>, 15 months ago

Andrew MMath: Work on figures and linkonce.

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