# Changeset 21f2e92

Ignore:
Timestamp:
Jun 7, 2021, 4:00:16 PM (4 months ago)
Branches:
jacob/cs343-translation, master, new-ast-unique-expr
Children:
382edbe
Parents:
dac16a0
Message:

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

This reverts commit 4ed7946e1c3092b517d444219a8ec8caf85a8b5a.

Location:
doc/theses/andrew_beach_MMath
Files:
3 edited

### Legend:

Unmodified
 rdac16a0 \label{c:existing} \CFA is an open-source project extending ISO C with \CFA (C-for-all)~\cite{Cforall} is an open-source project extending ISO C with modern safety and productivity features, while still ensuring backwards compatibility with C and its programmers.  \CFA is designed to have an existing C code-base allowing programmers to learn \CFA on an as-needed basis. Only those \CFA features pertaining to this thesis are discussed.  Many of the Only those \CFA features pertinent to this thesis are discussed.  Many of the \CFA syntactic and semantic features used in the thesis should be fairly obvious to the reader. // name mangling on by default int i; // _X1ii_1 @extern "C"@ {  // disables name mangling extern "C" {  // disables name mangling int j; // j @extern "Cforall"@ {  // enables name mangling extern "Cforall" {  // enables name mangling int k; // _X1ki_1 } \CFA adds a reference type to C as an auto-dereferencing pointer. They work very similarly to pointers. Reference-types are written the same way as a pointer-type but each Reference-types are written the same way as a pointer-type is but each asterisk (@*@) is replaced with a ampersand (@&@); this includes cv-qualifiers and multiple levels of reference, \eg: \begin{minipage}{0,5\textwidth} this includes cv-qualifiers and multiple levels of reference. They are intended for cases where you would want to use pointers but would be dereferencing them (almost) every usage. In most cases a reference can just be thought of as a pointer that automatically puts a dereference infront of each of its uses (per-level of reference). The address-of operator (@&@) acts as an escape and removes one of the automatic dereference operations. Mutable references may be assigned to by converting them to a pointer with a @&@ and then assigning a pointer too them. \begin{minipage}{0,45\textwidth} With references: \begin{cfa} int && rri = ri; rri = 3; &ri = &j; // reference assignment &ri = &j; ri = 5; \end{cfa} \end{minipage} \begin{minipage}{0,5\textwidth} \begin{minipage}{0,45\textwidth} With pointers: \begin{cfa} int ** ppi = π **ppi = 3; pi = &j; // pointer assignment pi = &j; *pi = 5; \end{cfa} \end{minipage} References are intended for cases where you would want to use pointers but would be dereferencing them (almost) every usage. In most cases a reference can just be thought of as a pointer that automatically puts a dereference in front of each of its uses (per-level of reference). The address-of operator (@&@) acts as an escape and removes one of the automatic dereference operations. Mutable references may be assigned by converting them to a pointer with a @&@ and then assigning a pointer to them, as in @&ri = &j;@ above. \section{Operators} \section{Constructors and Destructors} Both constructors and destructors are operators, which means they are functions with special operator names rather than type names in \Cpp. The special operator names may be used to call the functions explicitly (not allowed in \Cpp for constructors). In general, operator names in \CFA are constructed by bracketing an operator (such as @++?@) and post-fix operations (@?++@). An operator name may describe any function signature (it is just a name) but only certain signatures may be called in operator form. \begin{cfa} int ?+?( int i, int j, int k ) { return i + j + k; } The special name for a constructor is @?{}@, which comes from the initialization syntax in C. That initialation syntax is also the operator form. \CFA will generate a constructor call each time a variable is declared, passing the initialization arguments to the constructort. \begin{cfa} struct Example { ... }; void ?{}(Example & this) { ... } { sout | ?+?( 3, 4, 5 ); // no infix form } \end{cfa} Some near-misses" for unary/binary operator prototypes generate warnings. Both constructors and destructors are operators, which means they are functions with special operator names rather than type names in \Cpp. The special operator names may be used to call the functions explicitly (not allowed in \Cpp for constructors). The special name for a constructor is @?{}@, where the name @{}@ comes from the initialization syntax in C, \eg @Structure s = {...}@. % That initialization syntax is also the operator form. \CFA generates a constructor call each time a variable is declared, passing the initialization arguments to the constructor. \begin{cfa} struct Structure { ... }; void ?{}(Structure & this) { ... } Example a; Example b = {}; } void ?{}(Example & this, char first, int num) { ... } { Structure a; Structure b = {}; } void ?{}(Structure & this, char first, int num) { ... } Example c = {'a', 2}; } \end{cfa} Both @a@ and @b@ will be initalized with the first constructor (there is no general way to skip initialation) while @c@ will be initalized with the second. % I don't like the \^{} symbol but $^\wedge$ isn't better. Similarly destructors use the special name @^?{}@ (the @^@ has no special meaning). They can be called explicatly as well but normally they are implicitly called on a variable when it goes out of scope. \begin{cfa} void ^?{}(Example & this) { ... } { Structure c = {'a', 2}; } \end{cfa} Both @a@ and @b@ are initialized with the first constructor, while @c@ is initialized with the second. Currently, there is no general way to skip initialization. % I don't like the \^{} symbol but $^\wedge$ isn't better. Similarly, destructors use the special name @^?{}@ (the @^@ has no special meaning).  Normally, they are implicitly called on a variable when it goes out of scope but they can be called explicitly as well. \begin{cfa} void ^?{}(Structure & this) { ... } { Structure d; Example d; } // <- implicit destructor call \end{cfa} Whenever a type is defined, \CFA creates a default zero-argument No operator name is restricted in what function signatures they may be bound to although most of the forms cannot be called in operator form. Some near-misses" will generate warnings. Whenever a type is defined, \CFA will create a default zero-argument constructor, a copy constructor, a series of argument-per-field constructors and a destructor. All user constructors are defined after this. char capital_a = identity( 'A' ); \end{cfa} Each use of a polymorphic declaration resolves its polymorphic parameters Each use of a polymorphic declaration will resolve its polymorphic parameters (in this case, just @T@) to concrete types (@int@ in the first use and @char@ in the second). To allow a polymorphic function to be separately compiled, the type @T@ must be constrained by the operations used on @T@ in the function body. The @forall@ clause is augmented with a list of polymorphic variables (local type names) clauses is augmented with a list of polymorphic variables (local type names) and assertions (constraints), which represent the required operations on those types used in a function, \eg: \begin{cfa} forall( T | { void do_once(T); } ) forall( T | { void do_once(T); }) void do_twice(T value) { do_once(value); void do_once(double y) { ... } int quadruple(int x) { void do_once(int y) { y = y * 2; } // replace global do_once do_twice(x); // use local do_once do_twice(x + 1.5); // use global do_once void do_once(int y) { y = y * 2; } do_twice(x); return x; } \end{cfa} Specifically, the complier deduces that @do_twice@'s T is an integer from the argument @x@. It then looks for the most \emph{specific} definition matching the argument @x@. It then looks for the most specific definition matching the assertion, which is the nested integral @do_once@ defined within the function. The matched assertion function is then passed as a function pointer to @do_twice@ and called within it.  The global definition of @do_once@ is used for the second call because the float-point argument is a better match. to @do_twice@ and called within it. The global definition of @do_once@ is ignored. To avoid typing long lists of assertions, constraints can be collect into Each coroutine has a @main@ function, which takes a reference to a coroutine object and returns @void@. \begin{cfa}[numbers=left] \begin{cfa} void main(CountUp & this) { for (unsigned int next = 0 ; true ; ++next) { for (unsigned int next = 0 ; true ; ++next) { next = up; suspend;$\label{suspend}$
 rdac16a0 This chapter covers the design and user interface of the \CFA EHM, % or exception system. and begins with a general overview of EHMs. It is not a strict definition of all EHMs nor an exhaustive list of all possible features. However it does cover the most common structures and features found in them. exception-handling mechanism (EHM). % or exception system. We will begin with an overview of EHMs in general. It is not a strict definition of all EHMs nor an exaustive list of all possible features. However it does cover the most common structure and features found in them. % We should cover what is an exception handling mechanism and what is an % exception before this. Probably in the introduction. Some of this could % move there. \section{Raise / Handle} \paragraph{Raise / Handle} An exception operation has two main parts: raise and handle. These terms are sometimes also known as throw and catch but this work uses throw/catch as a particular kind of raise/handle. These are the two parts that the user writes and may These are the two parts that the user will write themselves and may be the only two pieces of the EHM that have any syntax in the language. \paragraph{Raise} \subparagraph{Raise} The raise is the starting point for exception handling. It marks the beginning of exception handling by raising an exception, which passes it to of exception handling by raising an excepion, which passes it to the EHM. Some well known examples include the @throw@ statements of \Cpp and Java and the \code{Python}{raise} statement from Python. A raise may perform some other work (such as memory management) but for the the \code{Python}{raise} statement from Python. In real systems a raise may preform some other work (such as memory management) but for the purposes of this overview that can be ignored. \paragraph{Handle} \subparagraph{Handle} The purpose of most exception operations is to run some user code to handle that exception. This code is given, with some other information, in a handler. A handler has three common features: the previously mentioned user code, a region of code they guard, and an exception label/condition that matches region of code they cover and an exception label/condition that matches certain exceptions. Only raises inside the guarded region and raising exceptions that match the Only raises inside the covered region and raising exceptions that match the label can be handled by a given handler. Different EHMs have different rules to pick a handler, if multiple handlers could be used, such as best match" or first found". Different EHMs will have different rules to pick a handler if multipe handlers could be used such as best match" or first found". The @try@ statements of \Cpp, Java and Python are common examples. All three also show another common feature of handlers, they are grouped by the guarded also show another common feature of handlers, they are grouped by the covered region. \section{Propagation} \paragraph{Propagation} After an exception is raised comes what is usually the biggest step for the EHM: finding and setting up the handler. The propagation from raise to EHM: finding and setting up the handler. The propogation from raise to handler can be broken up into three different tasks: searching for a handler, matching against the handler, and installing the handler. \paragraph{Searching} matching against the handler and installing the handler. \subparagraph{Searching} The EHM begins by searching for handlers that might be used to handle the exception. Searching is usually independent of the exception that was thrown as it looks for handlers that have the raise site in their guarded thrown as it looks for handlers that have the raise site in their covered region. This search includes handlers in the current function, as well as any in callers on the stack that have the function call in their guarded region. \paragraph{Matching} This includes handlers in the current function, as well as any in callers on the stack that have the function call in their covered region. \subparagraph{Matching} Each handler found has to be matched with the raised exception. The exception label defines a condition that is used with the exception to decide if label defines a condition that be use used with exception and decides if there is a match or not. In languages where the first match is used, this step is intertwined with searching: a match check is performed immediately after the search finds In languages where the first match is used this step is intertwined with searching, a match check is preformed immediately after the search finds a possible handler. \section{Installing} \subparagraph{Installing} After a handler is chosen it must be made ready to run. The implementation can vary widely to fit with the rest of the case when stack unwinding is involved. If a matching handler is not guarantied to be found, the EHM needs a different course of action for the case where no handler matches. This situation only occurs with unchecked exceptions as checked exceptions (such as in Java) can make the guarantee. This unhandled action can abort the program or install a very general handler. \paragraph{Hierarchy} If a matching handler is not guarantied to be found the EHM will need a different course of action here in the cases where no handler matches. This is only required with unchecked exceptions as checked exceptions (such as in Java) can make than guaranty. This different action can also be installing a handler but it is usually an implicat and much more general one. \subparagraph{Hierarchy} A common way to organize exceptions is in a hierarchical structure. This organization is often used in object-orientated languages where the This is especially true in object-orientated languages where the exception hierarchy is a natural extension of the object hierarchy. The EHM can return control to many different places, the most common are after the handler definition (termination) and after the raise (resumption). the most common are after the handler definition and after the raise. \paragraph{Communication} For effective exception handling, additional information is often passed from the raise to the handler and back again. from the raise to the handler. So far only communication of the exceptions' identity has been covered. A common communication method is putting fields into the exception instance and giving the handler access to them. References in the exception instance can push data back to the raise. A common method is putting fields into the exception instance and giving the handler access to them. \section{Virtuals} Virtual types and casts are not part of \CFA's EHM nor are they required for any EHM. However, one of the best ways to support an exception hierarchy is via a virtual system among exceptions and used for exception matching. Ideally, the virtual system would have been part of \CFA before the work However the \CFA uses a hierarchy built with the virtual system as the basis for exceptions and exception matching. The virtual system would have ideally been part of \CFA before the work on exception handling began, but unfortunately it was not. Therefore, only the features and framework needed for the EHM were Because of this only the features and framework needed for the EHM were designed and implemented. Other features were considered to ensure that the structure could accommodate other desirable features in the future but they were not the structure could accomidate other desirable features but they were not implemented. The rest of this section discusses the implemented subset of the virtual-system design. The rest of this section will only discuss the finalized portion of the virtual system. The virtual system supports multiple trees" of types. Each tree is % A type's ancestors are its parent and its parent's ancestors. % The root type has no ancestors. % A type's decedents are its children and its children's decedents. % A type's decendents are its children and its children's decendents. Every virtual type also has a list of virtual members. Children inherit It is important to note that these are virtual members, not virtual methods of object-orientated programming, and can be of any type. \PAB{I do not understand these sentences. Can you add an example? $\Rightarrow$ \CFA still supports virtual methods as a special case of virtual members. Function pointers that take a pointer to the virtual type are modified Function pointers that take a pointer to the virtual type will be modified with each level of inheritance so that refers to the new type. This means an object can always be passed to a function in its virtual table as if it were a method.} as if it were a method. Each virtual type has a unique id. This id and all the virtual members are combined This unique id and all the virtual members are combined into a virtual table type. Each virtual type has a pointer to a virtual table as a hidden field. \PAB{God forbid, maybe you need a UML diagram to relate these entities.} Up until this point the virtual system is similar to ones found in object-orientated languages but this where \CFA diverges. Objects encapsulate a single set of behaviours in each type, universally across the entire program, and indeed all programs that use that type definition. In this sense, the and indeed all programs that use that type definition. In this sense the types are closed" and cannot be altered. In \CFA, types do not encapsulate any behaviour. Traits are local and types can begin to satisfy a trait, stop satisfying a trait or satisfy the same In \CFA types do not encapsulate any behaviour. Traits are local and types can begin to statify a trait, stop satifying a trait or satify the same trait in a different way at any lexical location in the program. In this sense, they are open" as they can change at any time. This capability means it is impossible to pick a single set of functions that represent the type's In this sense they are open" as they can change at any time. This means it is implossible to pick a single set of functions that repersent the type's implementation across the program. \CFA side-steps this issue by not having a single virtual table for each type. A user can define virtual tables that are filled in at their declaration and given a name. Anywhere that name is visible, even if defined locally inside a function (although that means it does not have a type. A user can define virtual tables which are filled in at their declaration and given a name. Anywhere that name is visible, even if it was defined locally inside a function (although that means it will not have a static lifetime), it can be used. Specifically, a virtual type is bound" to a virtual table that Specifically, a virtual type is bound" to a virtual table which sets the virtual members for that object. The virtual members can be accessed through the object. \PAB{The above explanation is very good!} While much of the virtual infrastructure is created, it is currently only used internally for exception handling. The only user-level feature is the virtual cast cast, which is the same as the \Cpp \code{C++}{dynamic_cast}. \label{p:VirtualCast} \begin{cfa} (virtual TYPE)EXPRESSION \end{cfa} which is the same as the \Cpp \code{C++}{dynamic_cast}. Note, the syntax and semantics matches a C-cast, rather than the function-like \Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be \end{cfa} The trait is defined over two types, the exception type and the virtual table type. Each exception type should have a single virtual table type. There are no actual assertions in this trait because currently the trait system cannot express them (adding such assertions would be part of type. Each exception type should have but a single virtual table type. Now there are no actual assertions in this trait because the trait system actually can't express them (adding such assertions would be part of completing the virtual system). The imaginary assertions would probably come from a trait defined by the virtual system, and state that the exception type is a virtual type, is a descendent of @exception_t@ (the base exception type) is a virtual type, is a decendent of @exception_t@ (the base exception type) and note its virtual table type. }; \end{cfa} Both traits ensure a pair of types are an exception type and its virtual table, Both traits ensure a pair of types are an exception type and its virtual table and defines one of the two default handlers. The default handlers are used as fallbacks and are discussed in detail in \vref{s:ExceptionHandling}. \section{Exception Handling} \label{s:ExceptionHandling} As stated, \CFA provides two kinds of exception handling: termination and resumption. \CFA provides two kinds of exception handling: termination and resumption. These twin operations are the core of \CFA's exception handling mechanism. This section covers the general patterns shared by the two operations and then go on to cover the details of each individual operation. This section will cover the general patterns shared by the two operations and then go on to cover the details each individual operation. Both operations follow the same set of steps. Both start with the user performing a raise on an exception. Then the exception propagates up the stack. Both start with the user preforming a raise on an exception. Then the exception propogates up the stack. If a handler is found the exception is caught and the handler is run. After that control returns to a point specific to the kind of exception. If the search fails a default handler is run, and if it returns, control continues after the raise. Note, the default handler may further change control flow rather than return. After that control returns to normal execution. If the search fails a default handler is run and then control returns to normal execution after the raise. This general description covers what the two kinds have in common. Differences include how propagation is performed, where exception continues Differences include how propogation is preformed, where exception continues after an exception is caught and handled and which default handler is run. \subsection{Termination} \label{s:Termination} Termination handling is the familiar kind and used in most programming languages with exception handling. It is a dynamic, non-local goto. If the raised exception is matched and handled, the stack is unwound and control (usually) continues in the function It is dynamic, non-local goto. If the raised exception is matched and handled the stack is unwound and control will (usually) continue the function on the call stack that defined the handler. Termination is commonly used when an error has occurred and recovery is termination exception is any type that satisfies the trait @is_termination_exception@ at the call site. Through \CFA's trait system, the trait functions are implicitly passed into the Through \CFA's trait system the trait functions are implicity passed into the throw code and the EHM. A new @defaultTerminationHandler@ can be defined in any scope to change the throw's behaviour (see below). The throw copies the provided exception into managed memory to ensure the exception is not destroyed when the stack is unwound. change the throw's behavior (see below). The throw will copy the provided exception into managed memory to ensure the exception is not destroyed if the stack is unwound. It is the user's responsibility to ensure the original exception is cleaned up whether the stack is unwound or not. Allocating it on the stack is up wheither the stack is unwound or not. Allocating it on the stack is usually sufficient. Then propagation starts the search. \CFA uses a first match" rule so matching is performed with the copied exception as the search continues. It starts from the throwing function and proceeds towards the base of the stack, Then propogation starts with the search. \CFA uses a first match" rule so matching is preformed with the copied exception as the search continues. It starts from the throwing function and proceeds to the base of the stack, from callee to caller. At each stack frame, a check is made for resumption handlers defined by the } \end{cfa} When viewed on its own, a try statement simply executes the statements in \snake{GUARDED_BLOCK} and when those are finished, the try statement finishes. When viewed on its own, a try statement will simply execute the statements in \snake{GUARDED_BLOCK} and when those are finished the try statement finishes. However, while the guarded statements are being executed, including any invoked functions, all the handlers in these statements are included on the search path. Hence, if a termination exception is raised, the search includes the added handlers associated with the guarded block and those further up the stack from the guarded block. invoked functions, all the handlers in the statement are now on the search path. If a termination exception is thrown and not handled further up the stack they will be matched against the exception. Exception matching checks the handler in each catch clause in the order they appear, top to bottom. If the representation of the raised exception type they appear, top to bottom. If the representation of the thrown exception type is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ (if provided) is bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$ are executed. If control reaches the end of the handler, the exception is (if provided) is bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$ are executed. If control reaches the end of the handler, the exception is freed and control continues after the try statement. If no termination handler is found during the search, the default handler (\defaultTerminationHandler) visible at the raise statement is called. Through \CFA's trait system, the best match at the raise sight is used. This function is run and is passed the copied exception. If the default handler returns, control continues after the throw statement. If no termination handler is found during the search then the default handler (\defaultTerminationHandler) is run. Through \CFA's trait system the best match at the throw sight will be used. This function is run and is passed the copied exception. After the default handler is run control continues after the throw statement. There is a global @defaultTerminationHandler@ that is polymorphic over all termination exception types. Since it is so general, a more specific handler can be defined and is used for those types, effectively overriding the handler for a particular exception type. exception types. Since it is so general a more specific handler can be defined and will be used for those types, effectively overriding the handler for particular exception type. The global default termination handler performs a cancellation (see \vref{s:Cancellation}) on the current stack with the copied exception. just as old~\cite{Goodenough75} and is simpler in many ways. It is a dynamic, non-local function call. If the raised exception is matched a closure is taken from up the stack and executed, after which the raising function continues executing. These are most often used when a potentially repairable error occurs, some handler is found on the stack to fix it, and the raising function can continue with the correction. Another common usage is dynamic event analysis, \eg logging, without disrupting control flow. Note, if an event is raised and there is no interest, control continues normally. \PAB{We also have \lstinline{report} instead of \lstinline{throwResume}, \lstinline{recover} instead of \lstinline{catch}, and \lstinline{fixup} instead of \lstinline{catchResume}. You may or may not want to mention it. You can still stick with \lstinline{catch} and \lstinline{throw/catchResume} in the thesis.} matched a closure will be taken from up the stack and executed, after which the raising function will continue executing. These are most often used when an error occurred and if the error is repaired then the function can continue. A resumption raise is started with the @throwResume@ statement: @is_resumption_exception@ at the call site. The assertions from this trait are available to the exception system, while handling the exception. Resumption does not need to copy the raised exception, as the stack is not unwound. The exception and any values on the stack remain in scope, while the resumption is handled. the exception system while handling the exception. At run-time, no exception copy is made. As the stack is not unwound the exception and any values on the stack will remain in scope while the resumption is handled. The EHM then begins propogation. The search starts from the raise in the resuming function and proceeds towards the base of the stack, from callee to caller. resuming function and proceeds to the base of the stack, from callee to caller. At each stack frame, a check is made for resumption handlers defined by the @catchResume@ clauses of a @try@ statement. Note that termination handlers and resumption handlers may be used together in a single try statement, intermixing @catch@ and @catchResume@ freely. Each type of handler only interacts with exceptions from the matching kind of raise. When a try statement is executed, it simply executes the statements in the @GUARDED_BLOCK@ and then returns. Each type of handler will only interact with exceptions from the matching type of raise. When a try statement is executed it simply executes the statements in the @GUARDED_BLOCK@ and then finishes. However, while the guarded statements are being executed, including any invoked functions, all the handlers in these statements are included on the search path. Hence, if a resumption exception is raised the search includes the added handlers associated with the guarded block and those further up the stack from the guarded block. invoked functions, all the handlers in the statement are now on the search path. If a resumption exception is reported and not handled further up the stack they will be matched against the exception. Exception matching checks the handler in each catch clause in the order they appear, top to bottom. If the representation of the raised exception type they appear, top to bottom. If the representation of the thrown exception type is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ (if provided) is bound to a pointer to the exception and the statements in the raise statement that raised the handled exception. Like termination, if no resumption handler is found during the search, the default handler (\defaultResumptionHandler) visible at the raise statement is called. It uses the best match at the raise sight according to \CFA's overloading rules. The default handler is Like termination, if no resumption handler is found, the default handler visible at the throw statement is called. It will use the best match at the call sight according to \CFA's overloading rules. The default handler is passed the exception given to the throw. When the default handler finishes execution continues after the raise statement. There is a global \defaultResumptionHandler{} that is polymorphic over all resumption exception types and preforms a termination throw on the exception. The \defaultTerminationHandler{} can be There is a global \defaultResumptionHandler{} is polymorphic over all termination exceptions and preforms a termination throw on the exception. The \defaultTerminationHandler{} for that raise is matched at the original raise statement (the resumption @throw@\-@Resume@) and it can be customized by introducing a new or better match as well. \subsubsection{Resumption Marking} \label{s:ResumptionMarking} A key difference between resumption and termination is that resumption does not unwind the stack. A side effect that is that when a handler is matched and run, its try block (the guarded statements) and every try statement searched before it are still on the stack. Their existence can lead to the recursive and run it's try block (the guarded statements) and every try statement searched before it are still on the stack. This can lead to the recursive resumption problem. } \end{cfa} When this code is executed, the guarded @throwResume@ starts a search and matchs the handler in the @catchResume@ clause. This call is placed on the top of stack above the try-block. The second throw searchs the same try block and puts call another instance of the same handler on the stack leading to an infinite recursion. While this situation is trivial and easy to avoid, much more complex cycles When this code is executed the guarded @throwResume@ will throw, start a search and match the handler in the @catchResume@ clause. This will be call and placed on the stack on top of the try-block. The second throw then throws and will search the same try block and put call another instance of the same handler leading to an infinite loop. This situation is trivial and easy to avoid, but much more complex cycles can form with multiple handlers and different exception types. To prevent all of these cases, the exception search marks the try statements it visits. To prevent all of these cases we mark try statements on the stack. A try statement is marked when a match check is preformed with it and an exception. The statement is unmarked when the handling of that exception exception. The statement will be unmarked when the handling of that exception is completed or the search completes without finding a handler. While a try statement is marked, its handlers are never matched, effectify skipping over them to the next try statement. While a try statement is marked its handlers are never matched, effectify skipping over it to the next try statement. \begin{center} These rules mirror what happens with termination. When a termination throw happens in a handler, the search does not look at When a termination throw happens in a handler the search will not look at any handlers from the original throw to the original catch because that part of the stack is unwound. part of the stack has been unwound. A resumption raise in the same situation wants to search the entire stack, but with marking, the search does match exceptions for try statements at equivalent sections that would have been unwound by termination. The symmetry between resumption termination is why this pattern is picked. Other patterns, such as marking just the handlers that caught the exception, also work but lack the symmetry, meaning there are more rules to remember. but it will not try to match the exception with try statements in the section that would have been unwound as they are marked. The symmetry between resumption termination is why this pattern was picked. Other patterns, such as marking just the handlers that caught, also work but lack the symmetry means there are more rules to remember. \section{Conditional Catch} Both termination and resumption handler clauses can be given an additional condition to further control which exceptions they handle: did not match. The condition matching allows finer matching to check The condition matching allows finer matching by allowing the match to check more kinds of information than just the exception type. \begin{cfa} // Can't handle a failure relating to f2 here. \end{cfa} In this example, the file that experianced the IO error is used to decide In this example the file that experianced the IO error is used to decide which handler should be run, if any at all. \subsection{Comparison with Reraising} A more popular way to allow handlers to match in more detail is to reraise the exception after it has been caught, if it could not be handled here. the exception after it has been caught if it could not be handled here. On the surface these two features seem interchangable. If @throw@ is used to start a termination reraise then these two statements have the same behaviour: If we used @throw;@ to start a termination reraise then these two statements would have the same behaviour: \begin{cfa} try { } \end{cfa} However, if there are further handlers after this handler only the first is check. For multiple handlers on a single try block that could handle the same exception, the equivalent translations to conditional catch becomes more complex, resulting is multiple nested try blocks for all possible reraises. So while catch-with-reraise is logically equivilant to conditional catch, there is a lexical explosion for the former. \PAB{I think the following discussion makes an incorrect assumption. A conditional catch CAN happen with the stack unwound. Roy talked about this issue in Section 2.3.3 here: \newline \url{http://plg.uwaterloo.ca/theses/KrischerThesis.pdf}} Specifically for termination handling, a If there are further handlers after this handler only the first version will check them. If multiple handlers on a single try block that could handle the same exception the translations get more complex but they are equivilantly powerful. Until stack unwinding comes into the picture. In termination handling, a conditional catch happens before the stack is unwound, but a reraise happens afterwards. Normally this might only cause you to loose some debug information you could get from a stack trace (and that can be side stepped entirely by collecting information during the unwind). But for \CFA there is another issue, if the exception is not handled the default handler should be another issue, if the exception isn't handled the default handler should be run at the site of the original raise. There are two problems with this: the site of the original raise does not exist anymore and the default handler might not exist anymore. The site is always removed as part of the unwinding, often with the entirety of the There are two problems with this: the site of the original raise doesn't exist anymore and the default handler might not exist anymore. The site will always be removed as part of the unwinding, often with the entirety of the function it was in. The default handler could be a stack allocated nested function removed during the unwind. \section{Finally Clauses} \label{s:FinallyClauses} Finally clauses are used to preform unconditional clean-up when leaving a scope and are placed at the end of a try statement after any handler clauses: The @FINALLY_BLOCK@ is executed when the try statement is removed from the stack, including when the @GUARDED_BLOCK@ finishes, any termination handler finishes, or during an unwind. finishes or during an unwind. The only time the block is not executed is if the program is exited before the stack is unwound. Not all languages with unwinding have finally clauses. Notably \Cpp does without it as destructors with RAII serve a similar role. Although destructors and finally clauses have overlapping usage cases, they have their own specializations, like top-level functions and lambda functions with closures. Destructors take more work if a number of unrelated, local variables without destructors or dynamically allocated variables must be passed for de-intialization. Maintaining this destructor during local-block modification is a source of errors. A finally clause places local de-intialization inline with direct access to all local variables. without it as descructors serve a similar role. Although destructors and finally clauses can be used in many of the same areas they have their own use cases like top-level functions and lambda functions with closures. Destructors take a bit more work to set up but are much easier to reuse while finally clauses are good for one-off uses and can easily include local information. \section{Cancellation} raise, this exception is not used in matching only to pass information about the cause of the cancellation. (This restriction also means matching cannot fail so there is no default handler.) (This also means matching cannot fail so there is no default handler.) After @cancel_stack@ is called the exception is copied into the EHM's memory and the current stack is unwound. The result of a cancellation depends on the kind of stack that is being unwound. unwound. After that it depends one which stack is being cancelled. \paragraph{Main Stack} After the main stack is unwound there is a program-level abort. There are two reasons for this semantics. The first is that it obviously had to do the abort There are two reasons for this. The first is that it obviously had to do this in a sequential program as there is nothing else to notify and the simplicity of keeping the same behaviour in sequential and concurrent programs is good. \PAB{I do not understand this sentence. $\Rightarrow$ Also, even in concurrent programs, there is no stack that an innate connection to, so it would have be explicitly managed.} Also, even in concurrent programs there is no stack that an innate connection to, so it would have be explicitly managed. \paragraph{Thread Stack} A thread stack is created for a \CFA @thread@ object or object that satisfies the @is_thread@ trait. After a thread stack is unwound, the exception is stored until another After a thread stack is unwound there exception is stored until another thread attempts to join with it. Then the exception @ThreadCancelled@, which stores a reference to the thread and to the exception passed to the cancellation, is reported from the join to the joining thread. cancellation, is reported from the join. There is one difference between an explicit join (with the @join@ function) and an implicit join (from a destructor call). The explicit join takes the default handler (@defaultResumptionHandler@) from its calling context while the implicit join provides its own, which does a program abort if the the implicit join provides its own which does a program abort if the @ThreadCancelled@ exception cannot be handled. \PAB{Communication can occur during the lifetime of a thread using shared variable and \lstinline{waitfor} statements. Are 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 communication with other threads: start and join.} Communication is done at join because a thread only has to have to points of communication with other threads: start and join. Since a thread must be running to perform a cancellation (and cannot be cancelled from another stack), the cancellation must be after start and before the join, so join is use. before the join. So join is the one that we will use. % TODO: Find somewhere to discuss unwind collisions. A coroutine stack is created for a @coroutine@ object or object that satisfies the @is_coroutine@ trait. After a coroutine stack is unwound, control returns to the @resume@ function that most recently resumed it. The resume reports a @CoroutineCancelled@ exception, which contains references to the cancelled After a coroutine stack is unwound control returns to the resume function that most recently resumed it. The resume statement reports a @CoroutineCancelled@ exception, which contains a references to the cancelled coroutine and the exception used to cancel it. The @resume@ function also takes the \defaultResumptionHandler{} from the caller's context and passes it to the internal cancellation. The resume function also takes the \defaultResumptionHandler{} from the caller's context and passes it to the internal report. A coroutine knows of two other coroutines, its starter and its last resumer. The starter has a much more distant connection, while the last resumer just The starter has a much more distant connection while the last resumer just (in terms of coroutine state) called resume on this coroutine, so the message is passed to the latter.