source: doc/theses/andrew_beach_MMath/features.tex @ 21f2e92

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 21f2e92 was 21f2e92, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Revert "proofread Andrew's thesis chapters", changes saved locally.

This reverts commit 4ed7946e1c3092b517d444219a8ec8caf85a8b5a.

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