Index: doc/theses/andrew_beach_MMath/conclusion.tex
===================================================================
--- doc/theses/andrew_beach_MMath/conclusion.tex	(revision 315e5e373412e790b084d3570db5755620ef6682)
+++ doc/theses/andrew_beach_MMath/conclusion.tex	(revision 1a6a6f26a61c6a96404ba4a9bf6062bd5ba07959)
@@ -1,3 +1,4 @@
 \chapter{Conclusion}
+\label{c:conclusion}
 % Just a little knot to tie the paper together.
 
Index: doc/theses/andrew_beach_MMath/existing.tex
===================================================================
--- doc/theses/andrew_beach_MMath/existing.tex	(revision 315e5e373412e790b084d3570db5755620ef6682)
+++ doc/theses/andrew_beach_MMath/existing.tex	(revision 1a6a6f26a61c6a96404ba4a9bf6062bd5ba07959)
@@ -10,5 +10,4 @@
 
 Only those \CFA features pertaining to this thesis are discussed.
-% Also, only new features of \CFA will be discussed,
 A familiarity with
 C or C-like languages is assumed.
@@ -17,9 +16,9 @@
 \CFA has extensive overloading, allowing multiple definitions of the same name
 to be defined~\cite{Moss18}.
-\begin{lstlisting}[language=CFA,{moredelim=**[is][\color{red}]{@}{@}}]
-char @i@; int @i@; double @i@;
-int @f@(); double @f@();
-void @g@( int ); void @g@( double );
-\end{lstlisting}
+\begin{cfa}
+char i; int i; double i;
+int f(); double f();
+void g( int ); void g( double );
+\end{cfa}
 This feature requires name mangling so the assembly symbols are unique for
 different overloads. For compatibility with names in C, there is also a syntax
@@ -63,5 +62,5 @@
 int && rri = ri;
 rri = 3;
-&ri = &j; // rebindable
+&ri = &j;
 ri = 5;
 \end{cfa}
@@ -79,13 +78,15 @@
 \end{minipage}
 
-References are intended for pointer situations where dereferencing is the common usage,
-\ie the value is more important than the pointer.
+References are intended to be used when the indirection of a pointer is
+required, but the address is not as important as the value and dereferencing
+is the common usage.
 Mutable references may be assigned to by converting them to a pointer
-with a @&@ and then assigning a pointer to them, as in @&ri = &j;@ above
+with a @&@ and then assigning a pointer to them, as in @&ri = &j;@ above.
+% ???
 
 \section{Operators}
 
 \CFA implements operator overloading by providing special names, where
-operator usages are translated into function calls using these names.
+operator expressions are translated into function calls using these names.
 An operator name is created by taking the operator symbols and joining them with
 @?@s to show where the arguments go.
@@ -94,5 +95,6 @@
 This syntax make it easy to tell the difference between prefix operations
 (such as @++?@) and post-fix operations (@?++@).
-For example, plus and equality operators are defined for a point type.
+
+As an example, here are the addition and equality operators for a point type.
 \begin{cfa}
 point ?+?(point a, point b) { return point{a.x + b.x, a.y + b.y}; }
@@ -102,23 +104,17 @@
 }
 \end{cfa}
-Note these special names are not limited to builtin
-operators, and hence, may be used with arbitrary types.
-\begin{cfa}
-double ?+?( int x, point y ); // arbitrary types
-\end{cfa}
-% Some ``near misses", that are that do not match an operator form but looks like
-% it may have been supposed to, will generate warning but otherwise they are
-% left alone.
-Because operators are never part of the type definition they may be added
-at any time, including on built-in types.
+Note that this syntax works effectively but a textual transformation,
+the compiler converts all operators into functions and then resolves them
+normally. This means any combination of types may be used,
+although nonsensical ones (like @double ?==?(point, int);@) are discouraged.
+This feature is also used for all builtin operators as well,
+although those are implicitly provided by the language.
 
 %\subsection{Constructors and Destructors}
-
-\CFA also provides constructors and destructors as operators, which means they
-are functions with special operator names rather than type names in \Cpp.
-While constructors and destructions are normally called implicitly by the compiler,
-the special operator names, allow explicit calls.
-
-% Placement new means that this is actually equivalent to C++.
+In \CFA, constructors and destructors are operators, which means they are
+functions with special operator names rather than type names in \Cpp.
+Both constructors and destructors can be implicity called by the compiler,
+however the operator names allow explicit calls.
+% Placement new means that this is actually equivant to C++.
 
 The special name for a constructor is @?{}@, which comes from the
@@ -129,27 +125,30 @@
 struct Example { ... };
 void ?{}(Example & this) { ... }
+{
+	Example a;
+	Example b = {};
+}
 void ?{}(Example & this, char first, int num) { ... }
-Example a;		// implicit constructor calls
-Example b = {};
-Example c = {'a', 2};
-\end{cfa}
-Both @a@ and @b@ are initialized with the first constructor,
-while @c@ is initialized with the second.
-Constructor calls can be replaced with C initialization using special operator \lstinline{@=}.
-\begin{cfa}
-Example d @= {42};
-\end{cfa}
+{
+	Example c = {'a', 2};
+}
+\end{cfa}
+Both @a@ and @b@ will be initalized with the first constructor,
+@b@ because of the explicit call and @a@ implicitly.
+@c@ will be initalized with the second constructor.
+Currently, there is no general way to skip initialation.
+% I don't use @= anywhere in the thesis.
+
 % I don't like the \^{} symbol but $^\wedge$ isn't better.
 Similarly, destructors use the special name @^?{}@ (the @^@ has no special
 meaning).
-% These are a normally called implicitly called on a variable when it goes out
-% of scope. They can be called explicitly as well.
 \begin{cfa}
 void ^?{}(Example & this) { ... }
 {
-	Example e;	// implicit constructor call
-	^?{}(e);		// explicit destructor call
-	?{}(e);		// explicit constructor call
-} // implicit destructor call
+	Example d;
+	^?{}(d);
+
+	Example e;
+} // Implicit call of ^?{}(e);
 \end{cfa}
 
@@ -225,9 +224,9 @@
 The global definition of @do_once@ is ignored, however if quadruple took a
 @double@ argument, then the global definition would be used instead as it
-is a better match.
-% Aaron's thesis might be a good reference here.
-
-To avoid typing long lists of assertions, constraints can be collect into
-convenient package called a @trait@, which can then be used in an assertion
+would then be a better match.
+\todo{cite Aaron's thesis (maybe)}
+
+To avoid typing long lists of assertions, constraints can be collected into
+convenient a package called a @trait@, which can then be used in an assertion
 instead of the individual constraints.
 \begin{cfa}
@@ -253,5 +252,5 @@
 	node(T) * next;
 	T * data;
-}
+};
 node(int) inode;
 \end{cfa}
@@ -293,13 +292,12 @@
 };
 CountUp countup;
-for (10) sout | resume(countup).next; // print 10 values
 \end{cfa}
 Each coroutine has a @main@ function, which takes a reference to a coroutine
 object and returns @void@.
 %[numbers=left] Why numbers on this one?
-\begin{cfa}[numbers=left,numberstyle=\scriptsize\sf]
+\begin{cfa}
 void main(CountUp & this) {
-	for (unsigned int up = 0;; ++up) {
-		this.next = up;
+	for (unsigned int next = 0 ; true ; ++next) {
+		this.next = next;
 		suspend;$\label{suspend}$
 	}
@@ -307,16 +305,24 @@
 \end{cfa}
 In this function, or functions called by this function (helper functions), the
-@suspend@ statement is used to return execution to the coroutine's resumer
-without terminating the coroutine's function(s).
+@suspend@ statement is used to return execution to the coroutine's caller
+without terminating the coroutine's function.
 
 A coroutine is resumed by calling the @resume@ function, \eg @resume(countup)@.
 The first resume calls the @main@ function at the top. Thereafter, resume calls
 continue a coroutine in the last suspended function after the @suspend@
-statement, in this case @main@ line~\ref{suspend}.  The @resume@ function takes
-a reference to the coroutine structure and returns the same reference. The
-return value allows easy access to communication variables defined in the
-coroutine object. For example, the @next@ value for coroutine object @countup@
-is both generated and collected in the single expression:
-@resume(countup).next@.
+statement. In this case there is only one and, hence, the difference between
+subsequent calls is the state of variables inside the function and the
+coroutine object.
+The return value of @resume@ is a reference to the coroutine, to make it
+convent to access fields of the coroutine in the same expression.
+Here is a simple example in a helper function:
+\begin{cfa}
+unsigned int get_next(CountUp & this) {
+	return resume(this).next;
+}
+\end{cfa}
+
+When the main function returns the coroutine halts and can no longer be
+resumed.
 
 \subsection{Monitor and Mutex Parameter}
@@ -330,7 +336,7 @@
 exclusion on a monitor object by qualifying an object reference parameter with
 @mutex@.
-\begin{lstlisting}[language=CFA,{moredelim=**[is][\color{red}]{@}{@}}]
-void example(MonitorA & @mutex@ argA, MonitorB & @mutex@ argB);
-\end{lstlisting}
+\begin{cfa}
+void example(MonitorA & mutex argA, MonitorB & mutex argB);
+\end{cfa}
 When the function is called, it implicitly acquires the monitor lock for all of
 the mutex parameters without deadlock.  This semantics means all functions with
@@ -362,5 +368,5 @@
 {
 	StringWorker stringworker; // fork thread running in "main"
-} // implicitly join with thread / wait for completion
+} // Implicit call to join(stringworker), waits for completion.
 \end{cfa}
 The thread main is where a new thread starts execution after a fork operation
Index: doc/theses/andrew_beach_MMath/features.tex
===================================================================
--- doc/theses/andrew_beach_MMath/features.tex	(revision 315e5e373412e790b084d3570db5755620ef6682)
+++ doc/theses/andrew_beach_MMath/features.tex	(revision 1a6a6f26a61c6a96404ba4a9bf6062bd5ba07959)
@@ -19,5 +19,5 @@
 
 \paragraph{Raise}
-The raise is the starting point for exception handling
+The raise is the starting point for exception handling,
 by raising an exception, which passes it to
 the EHM.
@@ -30,9 +30,10 @@
 \paragraph{Handle}
 The primary purpose of an EHM is to run some user code to handle a raised
-exception. This code is given, with some other information, in a handler.
+exception. This code is given, along with some other information,
+in a handler.
 
 A handler has three common features: the previously mentioned user code, a
-region of code it guards, and an exception label/condition that matches
-the raised exception.
+region of code it guards and an exception label/condition that matches
+against the raised exception.
 Only raises inside the guarded region and raising exceptions that match the
 label can be handled by a given handler.
@@ -41,18 +42,11 @@
 
 The @try@ statements of \Cpp, Java and Python are common examples. All three
-show the common features of guarded region, raise, matching and handler.
-\begin{cfa}
-try {				// guarded region
-	...	 
-	throw exception;	// raise
-	...	 
-} catch( exception ) {	// matching condition, with exception label
-	...				// handler code
-}
-\end{cfa}
+also show another common feature of handlers, they are grouped by the guarded
+region.
 
 \subsection{Propagation}
 After an exception is raised comes what is usually the biggest step for the
-EHM: finding and setting up the handler for execution. The propagation from raise to
+EHM: finding and setting up the handler for execution.
+The propagation from raise to
 handler can be broken up into three different tasks: searching for a handler,
 matching against the handler and installing the handler.
@@ -60,6 +54,6 @@
 \paragraph{Searching}
 The EHM begins by searching for handlers that might be used to handle
-the exception. The search is restricted to
-handlers that have the raise site in their guarded
+the exception.
+The search will find handlers that have the raise site in their guarded
 region.
 The search includes handlers in the current function, as well as any in
@@ -67,7 +61,8 @@
 
 \paragraph{Matching}
-Each handler found is matched with the raised exception. The exception
+Each handler found is with the raised exception. The exception
 label defines a condition that is used with the 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
@@ -84,5 +79,5 @@
 different course of action for this case.
 This situation only occurs with unchecked exceptions as checked exceptions
-(such as in Java) are guaranteed to find a matching handler.
+(such as in Java) can make the guarantee.
 The unhandled action is usually very general, such as aborting the program.
 
@@ -98,10 +93,10 @@
 A handler labeled with any given exception can handle exceptions of that
 type or any child type of that exception. The root of the exception hierarchy
-(here \code{C}{exception}) acts as a catch-all, leaf types catch single types,
+(here \code{C}{exception}) acts as a catch-all, leaf types catch single types
 and the exceptions in the middle can be used to catch different groups of
 related exceptions.
 
 This system has some notable advantages, such as multiple levels of grouping,
-the ability for libraries to add new exception types, and the isolation
+the ability for libraries to add new exception types and the isolation
 between different sub-hierarchies.
 This design is used in \CFA even though it is not a object-orientated
@@ -123,24 +118,28 @@
 For effective exception handling, additional information is often passed
 from the raise to the handler and back again.
-So far, only communication of the exception's identity is covered.
-A common communication method for passing more information is putting fields into the exception instance
+So far, only communication of the exceptions' identity is covered.
+A common communication method for adding information to an exception
+is putting fields into the exception instance
 and giving the handler access to them.
-Using reference fields pointing to data at the raise location allows data to be
-passed in both directions.
+% You can either have pointers/references in the exception, or have p/rs to
+% the exception when it doesn't have to be copied.
+Passing references or pointers allows data at the raise location to be
+updated, passing information in both directions.
 
 \section{Virtuals}
-\label{s:Virtuals}
+\label{s:virtuals}
 Virtual types and casts are not part of \CFA's EHM nor are they required for
 an EHM.
 However, one of the best ways to support an exception hierarchy
 is via a virtual hierarchy and dispatch system.
-Ideally, the virtual system should have been part of \CFA before the work
+Ideally, the virtual system would have been part of \CFA before the work
 on exception handling began, but unfortunately it was not.
 Hence, only the features and framework needed for the EHM were
-designed and implemented for this thesis. Other features were considered to ensure that
+designed and implemented for this thesis.
+Other features were considered to ensure that
 the structure could accommodate other desirable features in the future
 but are not implemented.
 The rest of this section only discusses the implemented subset of the
-virtual-system design.
+virtual system design.
 
 The virtual system supports multiple ``trees" of types. Each tree is
@@ -149,57 +148,77 @@
 number of children.
 Any type that belongs to any of these trees is called a virtual type.
-For example, the following hypothetical syntax creates two virtual-type trees.
-\begin{flushleft}
-\lstDeleteShortInline@
-\begin{tabular}{@{\hspace{20pt}}l@{\hspace{20pt}}l}
-\begin{cfa}
-vtype V0, V1(V0), V2(V0);
-vtype W0, W1(W0), W2(W1);
-\end{cfa}
-&
-\raisebox{-0.6\totalheight}{\input{vtable}}
-\end{tabular}
-\lstMakeShortInline@
-\end{flushleft}
 % A type's ancestors are its parent and its parent's ancestors.
 % The root type has no ancestors.
 % A type's descendants are its children and its children's descendants.
-Every virtual type (tree node) has a pointer to a virtual table with a unique
-@Id@ and a list of virtual members (see \autoref{s:VirtualSystem} for
-details). Children inherit their parent's list of virtual members but may add
-and/or replace members.  For example,
-\begin{cfa}
-vtable W0 | { int ?<?( int, int ); int ?+?( int, int ); }
-vtable W1 | { int ?+?( int, int ); int w, int ?-?( int, int ); }
-\end{cfa}
-creates a virtual table for @W0@ initialized with the matching @<@ and @+@
-operations visible at this declaration context.  Similarly, @W1@ is initialized
-with @<@ from inheritance with @W0@, @+@ is replaced, and @-@ is added, where
-both operations are matched at this declaration context. It is important to
-note that these are virtual members, not virtual methods of object-orientated
-programming, and can be of any type. Finally, trait names can be used to
-specify the list of virtual members.
-
-\PAB{Need to look at these when done.
-
-\CFA still supports virtual methods as a special case of virtual members.
-Function pointers that take a pointer to the virtual type are 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.
-\todo{Clarify (with an example) virtual methods.}
-}%
+
+For the purposes of illistration, a proposed -- but unimplemented syntax --
+will be used. Each virtual type is repersented by a trait with an annotation
+that makes it a virtual type. This annotation is empty for a root type, which
+creates a new tree:
+\begin{cfa}
+trait root_type(T) virtual() {}
+\end{cfa}
+The annotation may also refer to any existing virtual type to make this new
+type a child of that type and part of the same tree. The parent may itself
+be a child or a root type and may have any number of existing children.
+\begin{cfa}
+trait child_a(T) virtual(root_type) {}
+trait grandchild(T) virtual(child_a) {}
+trait child_b(T) virtual(root_type) {}
+\end{cfa}
+\todo{Update the diagram in vtable.fig to show the new type tree.}
+
+Every virtual type also has a list of virtual members and a unique id,
+both are stored in a virtual table.
+Every instance of a virtual type also has a pointer to a virtual table stored
+in it, although there is no per-type virtual table as in many other languages.
+
+The list of virtual members is built up down the tree. Every virtual type
+inherits the list of virtual members from its parent and may add more
+virtual members to the end of the list which are passed on to its children.
+Again, using the unimplemented syntax this might look like:
+\begin{cfa}
+trait root_type(T) virtual() {
+	const char * to_string(T const & this);
+	unsigned int size;
+}
+
+trait child_type(T) virtual(root_type) {
+	char * irrelevant_function(int, char);
+}
+\end{cfa}
+% Consider adding a diagram, but we might be good with the explanation.
+
+As @child_type@ is a child of @root_type@ it has the virtual members of
+@root_type@ (@to_string@ and @size@) as well as the one it declared
+(@irrelivant_function@).
+
+It is important to note that these are virtual members, and may contain   
+arbitrary fields, functions or otherwise.
+The names ``size" and ``align" are reserved for the size and alignment of the
+virtual type, and are always automatically initialized as such.
+The other special case are uses of the trait's polymorphic argument
+(@T@ in the example), which are always updated to refer to the current
+virtual type. This allows functions that refer to to polymorphic argument
+to act as traditional virtual methods (@to_string@ in the example), as the
+object can always be passed to a virtual method in its virtual table.
 
 Up until this point the virtual system is similar to ones found in
-object-orientated languages but this is where \CFA diverges. Objects encapsulate a
-single set of methods in each type, universally across the entire program,
-and indeed all programs that use that type definition. Even if a type inherits and adds methods, it still encapsulate a
-single set of methods. In this sense,
-object-oriented types are ``closed" and cannot be altered.
-
-In \CFA, types do not encapsulate any code. Traits are local for each function and
-types can satisfy a local trait, stop satisfying it or, satisfy the same
-trait in a different way at any lexical location in the program where a function is call.
-In this sense, the set of functions/variables that satisfy a trait for a type is ``open" as the set can change at every call site.
+object-oriented languages but this is where \CFA diverges.
+Objects encapsulate a single set of methods in each type,
+universally across the entire program,
+and indeed all programs that use that type definition.
+The only way to change any method is to inherit and define a new type with
+its own universal implementation. In this sense,
+these object-oriented types are ``closed" and cannot be altered.
+% Because really they are class oriented.
+
+In \CFA, types do not encapsulate any code.
+Whether or not satisfies any given assertion, and hence any trait, is
+context sensitive. Types can begin to satisfy a trait, stop satisfying it or
+satisfy the same trait at any lexical location in the program.
+In this sense, an type's implementation in the set of functions and variables
+that allow it to satisfy a trait is ``open" and can change
+throughout the program.
 This capability means it is impossible to pick a single set of functions
 that represent a type's implementation across a program.
@@ -208,9 +227,33 @@
 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 it is
-defined locally inside a function \PAB{What does this mean? (although that means it does not have a
-static lifetime)}, it can be used.
+defined locally inside a function (although in this case the user must ensure
+it outlives any objects that use it), it can be used.
 Specifically, a virtual type is ``bound" to a virtual table that
 sets the virtual members for that object. The virtual members can be accessed
 through the object.
+
+This means virtual tables are declared and named in \CFA.
+They are declared as variables, using the type
+@vtable(VIRTUAL_TYPE)@ and any valid name. For example:
+\begin{cfa}
+vtable(virtual_type_name) table_name;
+\end{cfa}
+
+Like any variable they may be forward declared with the @extern@ keyword.
+Forward declaring virtual tables is relatively common.
+Many virtual types have an ``obvious" implementation that works in most
+cases.
+A pattern that has appeared in the early work using virtuals is to
+implement a virtual table with the the obvious definition and place a forward
+declaration of it in the header beside the definition of the virtual type.
+
+Even on the full declaration, no initializer should be used.
+Initialization is automatic.
+The type id and special virtual members ``size" and ``align" only depend on
+the virtual type, which is fixed given the type of the virtual table and
+so the compiler fills in a fixed value.
+The other virtual members are resolved, using the best match to the member's
+name and type, in the same context as the virtual table is declared using
+\CFA's normal resolution rules.
 
 While much of the virtual infrastructure is created, it is currently only used
@@ -228,10 +271,48 @@
 @EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
 
-\section{Exception}
-% Leaving until later, hopefully it can talk about actual syntax instead
-% of my many strange macros. Syntax aside I will also have to talk about the
-% features all exceptions support.
-
-Exceptions are defined by the trait system; there are a series of traits, and
+\section{Exceptions}
+
+The syntax for declaring an exception is the same as declaring a structure
+except the keyword that is swapped out:
+\begin{cfa}
+exception TYPE_NAME {
+	FIELDS
+};
+\end{cfa}
+
+Fields are filled in the same way as a structure as well. However an extra
+field is added, this field contains the pointer to the virtual table.
+It must be explicitly initialised by the user when the exception is
+constructed.
+
+Here is an example of declaring an exception type along with a virtual table,
+assuming the exception has an ``obvious" implementation and a default
+virtual table makes sense.
+
+\begin{minipage}[t]{0.4\textwidth}
+Header:
+\begin{cfa}
+exception Example {
+	int data;
+};
+
+extern vtable(Example)
+	example_base_vtable;
+\end{cfa}
+\end{minipage}
+\begin{minipage}[t]{0.6\textwidth}
+Source:
+\begin{cfa}
+vtable(Example) example_base_vtable
+\end{cfa}
+\vfil
+\end{minipage}
+
+%\subsection{Exception Details}
+If one is only raising and handling exceptions, that is the only interface
+that is needed. However it is actually a short hand for a more complex
+trait based interface.
+
+The language views exceptions through a series of traits,
 if a type satisfies them, then it can be used as an exception. The following
 is the base trait all exceptions need to match.
@@ -247,6 +328,6 @@
 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 descendant of @exception_t@ (the base exception type),
-and note its virtual table type.
+is a virtual type, is a descendant of @exception_t@ (the base exception type)
+and allow the user to find the virtual table type.
 
 % I did have a note about how it is the programmer's responsibility to make
@@ -267,5 +348,5 @@
 \end{cfa}
 Both traits ensure a pair of types are an exception type, its virtual table
-type,
+type
 and defines one of the two default handlers. The default handlers are used
 as fallbacks and are discussed in detail in \vref{s:ExceptionHandling}.
@@ -276,5 +357,5 @@
 facing way. So these three macros are provided to wrap these traits to
 simplify referring to the names:
-@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@, and @IS_RESUMPTION_EXCEPTION@.
+@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
 
 All three take one or two arguments. The first argument is the name of the
@@ -299,21 +380,24 @@
 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 goes on to cover the details of each individual operation.
+then goes on to cover the details each individual operation.
 
 Both operations follow the same set of steps.
 First, a user raises an exception.
-Second, the exception propagates up the stack.
+Second, the exception propagates up the stack, searching for a handler.
 Third, if a handler is found, the exception is caught and the handler is run.
 After that control continues at a raise-dependent location.
-Fourth, if a handler is not found, a default handler is run and, if it returns, then control
+As an alternate to the third step,
+if a handler is not found, a default handler is run and, if it returns,
+then control
 continues after the raise.
 
-%This general description covers what the two kinds have in common.
-The differences in the two operations include how propagation is performed, where execution continues
-after an exception is caught and handled, and which default handler is run.
+The differences between the two operations include how propagation is
+performed, where excecution after an exception is handler
+and which default handler is run.
 
 \subsection{Termination}
 \label{s:Termination}
-Termination handling is the familiar EHM and used in most programming
+Termination handling is the familiar kind of handling
+and used in most programming
 languages with exception handling.
 It is a dynamic, non-local goto. If the raised exception is matched and
@@ -347,5 +431,5 @@
 Then propagation starts with the search. \CFA uses a ``first match" rule so
 matching is performed with the copied exception as the search key.
-It starts from the raise in the throwing function and proceeds towards the base of the stack,
+It starts from the raise site and proceeds towards base of the stack,
 from callee to caller.
 At each stack frame, a check is made for termination handlers defined by the
@@ -361,5 +445,5 @@
 \end{cfa}
 When viewed on its own, a try statement simply executes the statements
-in the \snake{GUARDED_BLOCK}, and when those are finished,
+in the \snake{GUARDED_BLOCK} and when those are finished,
 the try statement finishes.
 
@@ -387,12 +471,14 @@
 termination exception types.
 The global default termination handler performs a cancellation
-(see \vref{s:Cancellation} for the justification) on the current stack with the copied exception.
-Since it is so general, a more specific handler is usually
-defined, possibly with a detailed message, and used for specific exception type, effectively overriding the default handler.
+(as described in \vref{s:Cancellation})
+on the current stack with the copied exception.
+Since it is so general, a more specific handler can be defined,
+overriding the default behaviour for the specific exception types.
 
 \subsection{Resumption}
 \label{s:Resumption}
 
-Resumption exception handling is the less familar EHM, but is
+Resumption exception handling is less familar form of exception handling,
+but is
 just as old~\cite{Goodenough75} and is simpler in many ways.
 It is a dynamic, non-local function call. If the raised exception is
@@ -403,5 +489,9 @@
 function once the error is corrected, and
 ignorable events, such as logging where nothing needs to happen and control
-should always continue from the raise point.
+should always continue from the raise site.
+
+Except for the changes to fit into that pattern, resumption exception
+handling is symmetric with termination exception handling, by design
+(see \autoref{s:Termination}).
 
 A resumption raise is started with the @throwResume@ statement:
@@ -410,20 +500,18 @@
 \end{cfa}
 \todo{Decide on a final set of keywords and use them everywhere.}
-It works much the same way as the termination throw.
-The expression must return a reference to a resumption exception,
-where the resumption exception is any type that satisfies the trait
-@is_resumption_exception@ at the call site.
-The assertions from this trait are available to
-the exception system while handling the exception.
-
-At run-time, no exception copy is made, since
+It works much the same way as the termination raise, except the
+type must satisfy the \snake{is_resumption_exception} that uses the
+default handler: \defaultResumptionHandler.
+This can be specialized for particular exception types.
+
+At run-time, no exception copy is made. Since
 resumption does not unwind the stack nor otherwise remove values from the
-current scope, so there is no need to manage memory to keep the exception in scope.
-
-Then propagation starts with the search. It starts from the raise in the
-resuming function and proceeds towards 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.
+current scope, there is no need to manage memory to keep the exception
+allocated.
+
+Then propagation starts with the search,
+following the same search path as termination,
+from the raise site to the base of stack and top of try statement to bottom.
+However, the handlers on try statements are defined by @catchResume@ clauses.
 \begin{cfa}
 try {
@@ -435,64 +523,18 @@
 }
 \end{cfa}
-% PAB, you say this above.
-% 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 in the
-% search path.
-% Hence, if a resumption exception is raised, these handlers may be matched
-% against the exception and may handle it.
-% 
-% 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
-% 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, execution continues after the
-% the raise statement that raised the handled exception.
-% 
-% Like termination, if no resumption handler is found during the search,
-% then the default handler (\defaultResumptionHandler) visible at the raise
-% statement is called. It will use the best match at the raise sight according
-% to \CFA's overloading rules. The default handler is
-% passed the exception given to the raise. When the default handler finishes
-% execution continues after the raise statement.
-% 
-% There is a global @defaultResumptionHandler{} is polymorphic over all
-% resumption exceptions and performs a termination throw on the exception.
-% The \defaultTerminationHandler{} can be overridden by providing a new
-% function that is a better match.
-
-The @GUARDED_BLOCK@ and its associated nested guarded statements work the same
-for resumption as for termination, as does exception matching at each
-@catchResume@. Similarly, if no resumption handler is found during the search,
-then the currently visible default handler (\defaultResumptionHandler) is
-called and control continues after the raise statement if it returns. Finally,
-there is also a global @defaultResumptionHandler@, which can be overridden,
-that is polymorphic over all resumption exceptions but performs a termination
-throw on the exception rather than a cancellation.
-
-Throwing the exception in @defaultResumptionHandler@ has the positive effect of
-walking the stack a second time for a recovery handler. Hence, a programmer has
-two chances for help with a problem, fixup or recovery, should either kind of
-handler appear on the stack. However, this dual stack walk leads to following
-apparent anomaly:
-\begin{cfa}
-try {
-	throwResume E;
-} catch (E) {
-	// this handler runs
-}
-\end{cfa}
-because the @catch@ appears to handle a @throwResume@, but a @throwResume@ only
-matches with @catchResume@. The anomaly results because the unmatched
-@catchResuem@, calls @defaultResumptionHandler@, which in turn throws @E@.
-
-% I wonder if there would be some good central place for this.
-Note, termination and resumption handlers may be used together
+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.
+Like @catch@ clauses, @catchResume@ clauses have no effect if an exception
+is not raised.
+
+The matching rules are exactly the same as well.
+The first major difference here is that after
+@EXCEPTION_TYPE@$_i$ is matched and @NAME@$_i$ is bound to the exception,
+@HANDLER_BLOCK@$_i$ is executed right away without first unwinding the stack.
+After the block has finished running control jumps to the raise site, where
+the just handled exception came from, and continues executing after it,
+not after the try statement.
 
 \subsubsection{Resumption Marking}
@@ -502,5 +544,6 @@
 and run, its try block (the guarded statements) and every try statement
 searched before it are still on the stack. There presence can lead to
-the \emph{recursive resumption problem}.
+the recursive resumption problem.
+\todo{Is there a citation for the recursive resumption problem?}
 
 The recursive resumption problem is any situation where a resumption handler
@@ -516,17 +559,14 @@
 When this code is executed, the guarded @throwResume@ starts a
 search and matches the handler in the @catchResume@ clause. This
-call is placed on the stack above the try-block. Now the second raise in the handler
-searches the same try block, matches, and puts another instance of the
+call is placed on the stack above the try-block.
+Now the second raise in the handler searches the same try block,
+matches again and then puts another instance of the
 same handler on the stack leading to infinite recursion.
 
-While this situation is trivial and easy to avoid, much more complex cycles can
-form with multiple handlers and different exception types.  The key point is
-that the programmer's intuition expects every raise in a handler to start
-searching \emph{below} the @try@ statement, making it difficult to understand
-and fix the problem.
-
+While this situation is trivial and easy to avoid, much more complex cycles
+can form with multiple handlers and different exception types.
 To prevent all of these cases, each try statement is ``marked" from the
-time the exception search reaches it to either when a matching handler
-completes or when the search reaches the base
+time the exception search reaches it to either when a handler completes
+handling that exception or when the search reaches the base
 of the stack.
 While a try statement is marked, its handlers are never matched, effectively
@@ -540,8 +580,8 @@
 for instance, marking just the handlers that caught the exception,
 would also prevent recursive resumption.
-However, the rule selected mirrors what happens with termination,
-and hence, matches programmer intuition that a raise searches below a try.
-
-In detail, the marked try statements are the ones that would be removed from
+However, the rules selected mirrors what happens with termination,
+so this reduces the amount of rules and patterns a programmer has to know.
+
+The marked try statements are the ones that would be removed from
 the stack for a termination exception, \ie those on the stack
 between the handler and the raise statement.
@@ -609,26 +649,77 @@
 
 \subsection{Comparison with Reraising}
-Without conditional catch, the only approach to match in more detail is to reraise
-the exception after it has been caught, if it could not be handled.
+In languages without conditional catch, that is no ability to match an
+exception based on something other than its type, it can be mimicked
+by matching all exceptions of the right type, checking any additional
+conditions inside the handler and re-raising the exception if it does not
+match those.
+
+Here is a minimal example comparing both patterns, using @throw;@
+(no argument) to start a re-raise.
 \begin{center}
-\begin{tabular}{l|l}
+\begin{tabular}{l r}
 \begin{cfa}
 try {
-	do_work_may_throw();
-} catch(excep_t * ex; can_handle(ex)) {
-
-	handle(ex);
-
-
-
-}
+    do_work_may_throw();
+} catch(exception_t * exc ;
+		can_handle(exc)) {
+    handle(exc);
+}
+
+
+
 \end{cfa}
 &
 \begin{cfa}
 try {
-	do_work_may_throw();
-} catch(excep_t * ex) { 
-	if (can_handle(ex)) {
-		handle(ex);
+    do_work_may_throw();
+} catch(exception_t * exc) {
+    if (can_handle(exc)) {
+        handle(exc);
+    } else {
+        throw;
+    }
+}
+\end{cfa}
+\end{tabular}
+\end{center}
+At first glance catch-and-reraise may appear to just be a quality of life 
+feature, but there are some significant differences between the two
+stratagies.
+
+A simple difference that is more important for \CFA than many other languages
+is that the raise site changes, with a re-raise but does not with a
+conditional catch.
+This is important in \CFA because control returns to the raise site to run
+the per-site default handler. Because of this only a conditional catch can
+allow the original raise to continue.
+
+The more complex issue comes from the difference in how conditional
+catches and re-raises handle multiple handlers attached to a single try
+statement. A conditional catch will continue checking later handlers while
+a re-raise will skip them.
+If the different handlers could handle some of the same exceptions,
+translating a try statement that uses one to use the other can quickly
+become non-trivial:
+
+\noindent
+Original, with conditional catch:
+\begin{cfa}
+...
+} catch (an_exception * e ; check_a(e)) {
+	handle_a(e);
+} catch (exception_t * e ; check_b(e)) {
+	handle_b(e);
+}
+\end{cfa}
+Translated, with re-raise:
+\begin{cfa}
+...
+} catch (exception_t * e) {
+	an_exception * an_e = (virtual an_exception *)e;
+	if (an_e && check_a(an_e)) {
+		handle_a(an_e);
+	} else if (check_b(e)) {
+		handle_b(e);
 	} else {
 		throw;
@@ -636,119 +727,30 @@
 }
 \end{cfa}
-\end{tabular}
-\end{center}
-Notice catch-and-reraise increases complexity by adding additional data and
-code to the exception process. Nevertheless, catch-and-reraise can simulate
-conditional catch straightforwardly, when exceptions are disjoint, \ie no
-inheritance.
-
-However, catch-and-reraise simulation becomes unusable for exception inheritance.
-\begin{flushleft}
-\begin{cfa}[xleftmargin=6pt]
-exception E1;
-exception E2(E1); // inheritance
-\end{cfa}
-\begin{tabular}{l|l}
-\begin{cfa}
-try {
-	... foo(); ... // raise E1/E2
-	... bar(); ... // raise E1/E2
-} catch( E2 e; e.rtn == foo ) {
-	...
-} catch( E1 e; e.rtn == foo ) {
-	...
-} catch( E1 e; e.rtn == bar ) {
-	...
-}
-
-\end{cfa}
-&
-\begin{cfa}
-try {
-	... foo(); ...
-	... bar(); ...
-} catch( E2 e ) {
-	if ( e.rtn == foo ) { ...
-	} else throw; // reraise
-} catch( E1 e ) {
-	if (e.rtn == foo) { ...
-	} else if (e.rtn == bar) { ...
-	else throw; // reraise
-}
-\end{cfa}
-\end{tabular}
-\end{flushleft}
-The derived exception @E2@ must be ordered first in the catch list, otherwise
-the base exception @E1@ catches both exceptions. In the catch-and-reraise code
-(right), the @E2@ handler catches exceptions from both @foo@ and
-@bar@. However, the reraise misses the following catch clause. To fix this
-problem, an enclosing @try@ statement is need to catch @E2@ for @bar@ from the
-reraise, and its handler must duplicate the inner handler code for @bar@. To
-generalize, this fix for any amount of inheritance and complexity of try
-statement requires a technique called \emph{try-block
-splitting}~\cite{Krischer02}, which is not discussed in this thesis. It is
-sufficient to state that conditional catch is more expressive than
-catch-and-reraise in terms of complexity.
-
-\begin{comment}
-That is, they have the same behaviour in isolation.
-Two things can expose differences between these cases.
-
-One is the existence of multiple handlers on a single try statement.
-A reraise skips all later handlers for a try statement but a conditional
-catch does not.
-% Hence, if an earlier handler contains a reraise later handlers are
-% implicitly skipped, with a conditional catch they are not.
-Still, they are equivalently powerful,
-both can be used two mimic the behaviour of the other,
-as reraise can pack arbitrary code in the handler and conditional catches
-can put arbitrary code in the predicate.
-% I was struggling with a long explanation about some simple solutions,
-% like repeating a condition on later handlers, and the general solution of
-% merging everything together. I don't think it is useful though unless its
-% for a proof.
-% https://en.cppreference.com/w/cpp/language/throw
-
-The question then becomes ``Which is a better default?"
-We believe that not skipping possibly useful handlers is a better default.
-If a handler can handle an exception it should and if the handler can not
-handle the exception then it is probably safer to have that explicitly
-described in the handler itself instead of implicitly described by its
-ordering with other handlers.
-% Or you could just alter the semantics of the throw statement. The handler
-% index is in the exception so you could use it to know where to start
-% searching from in the current try statement.
-% No place for the `goto else;` metaphor.
-
-The other issue is all of the discussion above assumes that the only
-way to tell apart two raises is the exception being raised and the remaining
-search path.
-This is not true generally, the current state of the stack can matter in
-a number of cases, even only for a stack trace after an program abort.
-But \CFA has a much more significant need of the rest of the stack, the
-default handlers for both termination and resumption.
-
-% For resumption it turns out it is possible continue a raise after the
-% exception has been caught, as if it hadn't been caught in the first place.
-This becomes a problem combined with the stack unwinding used in termination
-exception handling.
-The stack is unwound before the handler is installed, and hence before any
-reraises can run. So if a reraise happens the previous stack is gone,
-the place on the stack where the default handler was supposed to run is gone,
-if the default handler was a local function it may have been unwound too.
-There is no reasonable way to restore that information, so the reraise has
-to be considered as a new raise.
-This is the strongest advantage conditional catches have over reraising,
-they happen before stack unwinding and avoid this problem.
-
-% The one possible disadvantage of conditional catch is that it runs user
-% code during the exception search. While this is a new place that user code
-% can be run destructors and finally clauses are already run during the stack
-% unwinding.
+(There is a simpler solution if @handle_a@ never raises exceptions,
+using nested try statements.)
+
+% } catch (an_exception * e ; check_a(e)) {
+%     handle_a(e);
+% } catch (exception_t * e ; !(virtual an_exception *)e && check_b(e)) {
+%     handle_b(e);
+% }
 %
-% https://www.cplusplus.com/reference/exception/current_exception/
-%   `exception_ptr current_exception() noexcept;`
-% https://www.python.org/dev/peps/pep-0343/
-\end{comment}
+% } catch (an_exception * e)
+%   if (check_a(e)) {
+%     handle_a(e);
+%   } else throw;
+% } catch (exception_t * e)
+%   if (check_b(e)) {
+%     handle_b(e);
+%   } else throw;
+% }
+In similar simple examples translating from re-raise to conditional catch
+takes less code but it does not have a general trivial solution either.
+
+So, given that the two patterns do not trivially translate into each other,
+it becomes a matter of which on should be encouraged and made the default.
+From the premise that if a handler that could handle an exception then it
+should, it follows that checking as many handlers as possible is preferred.
+So conditional catch and checking later handlers is a good default.
 
 \section{Finally Clauses}
@@ -766,5 +768,5 @@
 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.
@@ -786,7 +788,7 @@
 they have their own strengths, similar to top-level function and lambda
 functions with closures.
-Destructors take more work for their creation, but if there is clean-up code
+Destructors take more work to create, but if there is clean-up code
 that needs to be run every time a type is used, they are much easier
-to set-up.
+to set-up for each use. % It's automatic.
 On the other hand finally clauses capture the local context, so is easy to
 use when the clean-up is not dependent on the type of a variable or requires
@@ -804,5 +806,5 @@
 raise, this exception is not used in matching only to pass information about
 the cause of the cancellation.
-Finaly, since a cancellation only unwinds and forwards, there is no default handler.
+Finally, as no handler is provided, there is no default handler.
 
 After @cancel_stack@ is called the exception is copied into the EHM's memory
@@ -815,10 +817,10 @@
 After the main stack is unwound there is a program-level abort. 
 
-The reasons for this semantics in a sequential program is that there is no more code to execute.
-This semantics also applies to concurrent programs, too, even if threads are running.
-That is, if any threads starts a cancellation, it implies all threads terminate.
-Keeping the same behaviour in sequential and concurrent programs is simple.
-Also, even in concurrent programs there may not currently be any other stacks
-and even if other stacks do exist, main has no way to know where they are.
+The first reason for this behaviour is for sequential programs where there
+is only one stack, and hence to stack to pass information to.
+Second, even in concurrent programs, the main stack has no dependency
+on another stack and no reliable way to find another living stack.
+Finally, keeping the same behaviour in both sequential and concurrent
+programs is simple and easy to understand.
 
 \paragraph{Thread Stack}
@@ -850,5 +852,7 @@
 
 With explicit join and a default handler that triggers a cancellation, it is
-possible to cascade an error across any number of threads, cleaning up each
+possible to cascade an error across any number of threads,
+alternating between the resumption (possibly termination) and cancellation,
+cleaning up each
 in turn, until the error is handled or the main thread is reached.
 
@@ -863,5 +867,6 @@
 caller's context and passes it to the internal report.
 
-A coroutine only knows of two other coroutines, its starter and its last resumer.
+A coroutine only knows of two other coroutines,
+its starter and its last resumer.
 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
@@ -869,7 +874,6 @@
 
 With a default handler that triggers a cancellation, it is possible to
-cascade an error across any number of coroutines, cleaning up each in turn,
+cascade an error across any number of coroutines,
+alternating between the resumption (possibly termination) and cancellation,
+cleaning up each in turn,
 until the error is handled or a thread stack is reached.
-
-\PAB{Part of this I do not understand. A cancellation cannot be caught. But you
-talk about handling a cancellation in the last sentence. Which is correct?}
Index: doc/theses/andrew_beach_MMath/intro.tex
===================================================================
--- doc/theses/andrew_beach_MMath/intro.tex	(revision 315e5e373412e790b084d3570db5755620ef6682)
+++ doc/theses/andrew_beach_MMath/intro.tex	(revision 1a6a6f26a61c6a96404ba4a9bf6062bd5ba07959)
@@ -11,72 +11,50 @@
 
 % Now take a step back and explain what exceptions are generally.
+Exception handling provides dynamic inter-function control flow.
 A language's EHM is a combination of language syntax and run-time
-components that are used to construct, raise, and handle exceptions,
-including all control flow.
-Exceptions are an active mechanism for replacing passive error/return codes and return unions (Go and Rust).
-Exception handling provides dynamic inter-function control flow.
+components that construct, raise, propagate and handle exceptions,
+to provide all of that control flow.
 There are two forms of exception handling covered in this thesis:
 termination, which acts as a multi-level return,
 and resumption, which is a dynamic function call.
-% PAB: Maybe this sentence was suppose to be deleted?
-Termination handling is much more common,
-to the extent that it is often seen as the only form of handling.
-% PAB: I like this sentence better than the next sentence.
-% This separation is uncommon because termination exception handling is so
-% much more common that it is often assumed.
-% WHY: Mention other forms of continuation and \cite{CommonLisp} here?
-
-Exception handling relies on the concept of nested functions to create handlers that deal with exceptions.
+% About other works:
+Often, when this separation is not made, termination exceptions are assumed
+as they are more common and may be the only form of handling provided in
+a language.
+
+All types of exception handling link a raise with a handler.
+Both operations are usually language primitives, although raises can be
+treated as a primitive function that takes an exception argument.
+Handlers are more complex as they are added to and removed from the stack
+during execution, must specify what they can handle and give the code to
+handle the exception.
+
+Exceptions work with different execution models but for the descriptions
+that follow a simple call stack, with functions added and removed in a
+first-in-last-out order, is assumed.
+
+Termination exception handling searches the stack for the handler, then
+unwinds the stack to where the handler was found before calling it.
+The handler is run inside the function that defined it and when it finishes
+it returns control to that function.
 \begin{center}
-\begin{tabular}[t]{ll}
-\begin{lstlisting}[aboveskip=0pt,belowskip=0pt,language=CFA,{moredelim=**[is][\color{red}]{@}{@}}]
-void f( void (*hp)() ) {
-	hp();
-}
-void g( void (*hp)() ) {
-	f( hp );
-}
-void h( int @i@, void (*hp)() ) {
-	void @handler@() { // nested
-		printf( "%d\n", @i@ );
-	}
-	if ( i == 1 ) hp = handler;
-	if ( i > 0 ) h( i - 1, hp );
-	else g( hp );
-}
-h( 2, 0 );
-\end{lstlisting}
-&
-\raisebox{-0.5\totalheight}{\input{handler}}
-\end{tabular}
+\input{callreturn}
 \end{center}
-The nested function @handler@ in the second stack frame is explicitly passed to function @f@.
-When this handler is called in @f@, it uses the parameter @i@ in the second stack frame, which is accessible by an implicit lexical-link pointer.
-Setting @hp@ in @h@ at different points in the recursion, results in invoking a different handler.
-Exception handling extends this idea by eliminating explicit handler passing, and instead, performing a stack search for a handler that matches some criteria (conditional dynamic call), and calls the handler at the top of the stack.
-It is the runtime search $O(N)$ that differentiates an EHM call (raise) from normal dynamic call $O(1)$ via a function or virtual-member pointer.
-
-Termination exception handling searches the stack for a handler, unwinds the stack to the frame containing the matching handler, and calling the handler at the top of the stack.
-\begin{center}
-\input{termination}
-\end{center}
-Note, since the handler can reference variables in @h@, @h@ must remain on the stack for the handler call.
-After the handler returns, control continues after the lexical location of the handler in @h@ (static return)~\cite[p.~108]{Tennent77}.
-Unwinding allows recover to any previous
-function on the stack, skipping any functions between it and the
-function containing the matching handler.
-
-Resumption exception handling searches the stack for a handler, does \emph{not} unwind the stack to the frame containing the matching handler, and calls the handler at the top of the stack.
+
+Resumption exception handling searches the stack for a handler and then calls
+it without removing any other stack frames.
+The handler is run on top of the existing stack, often as a new function or
+closure capturing the context in which the handler was defined.
+After the handler has finished running it returns control to the function
+that preformed the raise, usually starting after the raise.
 \begin{center}
 \input{resumption}
 \end{center}
-After the handler returns, control continues after the resume in @f@ (dynamic return).
-Not unwinding allows fix up of the problem in @f@ by any previous function on the stack, without disrupting the current set of stack frames.
 
 Although a powerful feature, exception handling tends to be complex to set up
 and expensive to use
 so it is often limited to unusual or ``exceptional" cases.
-The classic example is error handling, where exceptions are used to
-remove error handling logic from the main execution path, while paying
+The classic example is error handling, exceptions can be used to
+remove error handling logic from the main execution path, and pay
 most of the cost only when the error actually occurs.
 
@@ -88,17 +66,17 @@
 some of the underlying tools used to implement and express exception handling
 in other languages are absent in \CFA.
-Still the resulting basic syntax resembles that of other languages:
-\begin{lstlisting}[language=CFA,{moredelim=**[is][\color{red}]{@}{@}}]
-@try@ {
+Still the resulting syntax resembles that of other languages:
+\begin{cfa}
+try {
 	...
 	T * object = malloc(request_size);
 	if (!object) {
-		@throw@ OutOfMemory{fixed_allocation, request_size};
+		throw OutOfMemory{fixed_allocation, request_size};
 	}
 	...
-} @catch@ (OutOfMemory * error) {
+} catch (OutOfMemory * error) {
 	...
 }
-\end{lstlisting}
+\end{cfa}
 % A note that yes, that was a very fast overview.
 The design and implementation of all of \CFA's EHM's features are
@@ -107,143 +85,166 @@
 
 % The current state of the project and what it contributes.
-The majority of the \CFA EHM is implemented in \CFA, except for a small amount of assembler code.
-In addition,
-a suite of tests and performance benchmarks were created as part of this project.
-The \CFA implementation techniques are generally applicable in other programming
+All of these features have been implemented in \CFA,
+covering both changes to the compiler and the run-time.
+In addition, a suite of test cases and performance benchmarks were created
+along side the implementation.
+The implementation techniques are generally applicable in other programming
 languages and much of the design is as well.
-Some parts of the EHM use features unique to \CFA, and hence,
-are harder to replicate in other programming languages.
-% Talk about other programming languages.
-Three well known programming languages with EHMs, %/exception handling
-C++, Java and Python are examined in the performance work. However, these languages focus on termination
-exceptions, so there is no comparison with resumption.
+Some parts of the EHM use other features unique to \CFA and would be
+harder to replicate in other programming languages.
 
 The contributions of this work are:
 \begin{enumerate}
 \item Designing \CFA's exception handling mechanism, adapting designs from
-other programming languages, and creating new features.
-\item Implementing stack unwinding for the \CFA EHM, including updating
-the \CFA compiler and run-time environment to generate and execute the EHM code.
-\item Designing and implementing a prototype virtual system.
+other programming languages and creating new features.
+\item Implementing stack unwinding and the \CFA EHM, including updating
+the \CFA compiler and the run-time environment.
+\item Designed and implemented a prototype virtual system.
 % I think the virtual system and per-call site default handlers are the only
 % "new" features, everything else is a matter of implementation.
-\item Creating tests and performance benchmarks to compare with EHM's in other languages.
+\item Creating tests to check the behaviour of the EHM.
+\item Creating benchmarks to check the performances of the EHM,
+as compared to other languages.
 \end{enumerate}
 
-%\todo{I can't figure out a good lead-in to the roadmap.}
-The thesis is organization as follows.
-The next section and parts of \autoref{c:existing} cover existing EHMs.
-New \CFA EHM features are introduced in \autoref{c:features},
+The rest of this thesis is organized as follows.
+The current state of exceptions is covered in \autoref{s:background}.
+The existing state of \CFA is also covered in \autoref{c:existing}.
+New EHM features are introduced in \autoref{c:features},
 covering their usage and design.
 That is followed by the implementation of these features in
 \autoref{c:implement}.
-Performance results are presented in \autoref{c:performance}.
-Summing up and possibilities for extending this project are discussed in \autoref{c:future}.
+Performance results are examined in \autoref{c:performance}.
+Possibilities to extend this project are discussed in \autoref{c:future}.
+Finally, the project is summarized in \autoref{c:conclusion}.
 
 \section{Background}
 \label{s:background}
 
-Exception handling is a well examined area in programming languages,
-with papers on the subject dating back the 70s~\cite{Goodenough75}.
+Exception handling has been examined before in programming languages,
+with papers on the subject dating back 70s.\cite{Goodenough75}
 Early exceptions were often treated as signals, which carried no information
-except their identity. Ada~\cite{Ada} still uses this system.
+except their identity. Ada still uses this system.\todo{cite Ada}
 
 The modern flag-ship for termination exceptions is \Cpp,
 which added them in its first major wave of non-object-orientated features
 in 1990.
-% https://en.cppreference.com/w/cpp/language/history
-While many EHMs have special exception types,
-\Cpp has the ability to use any type as an exception.
-However, this generality is not particularly useful, and has been pushed aside for classes, with a convention of inheriting from
+\todo{cite https://en.cppreference.com/w/cpp/language/history}
+Many EHMs have special exception types,
+however \Cpp has the ability to use any type as an exception.
+These were found to be not very useful and have been pushed aside for classes
+inheriting from
 \code{C++}{std::exception}.
-While \Cpp has a special catch-all syntax @catch(...)@, there is no way to discriminate its exception type, so nothing can
-be done with the caught value because nothing is known about it.
-Instead the base exception-type \code{C++}{std::exception} is defined with common functionality (such as
-the ability to print a message when the exception is raised but not caught) and all
+Although there is a special catch-all syntax (@catch(...)@) there are no
+operations that can be performed on the caught value, not even type inspection.
+Instead the base exception-type \code{C++}{std::exception} defines common
+functionality (such as
+the ability to describe the reason the exception was raised) and all
 exceptions have this functionality.
-Having a root exception-type seems to be the standard now, as the guaranteed functionality is worth
-any lost in flexibility from limiting exceptions types to classes.
-
-Java~\cite{Java} was the next popular language to use exceptions.
-Its exception system largely reflects that of \Cpp, except it requires
-exceptions to be a subtype of \code{Java}{java.lang.Throwable}
+That trade-off, restricting usable types to gain guaranteed functionality,
+is almost universal now, as without some common functionality it is almost
+impossible to actually handle any errors.
+
+Java was the next popular language to use exceptions. \todo{cite Java}
+Its exception system largely reflects that of \Cpp, except that requires
+you throw a child type of \code{Java}{java.lang.Throwable}
 and it uses checked exceptions.
-Checked exceptions are part of a function's interface defining all exceptions it or its called functions raise.
-Using this information, it is possible to statically verify if a handler exists for all raised exception, \ie no uncaught exceptions.
-Making exception information explicit, improves clarity and
-safety, but can slow down programming.
-For example, programming complexity increases when dealing with high-order methods or an overly specified
-throws clause. However some of the issues are more
-programming annoyances, such as writing/updating many exception signatures after adding or remove calls.
-Java programmers have developed multiple programming ``hacks'' to circumvent checked exceptions negating the robustness it is suppose to provide.
-For example, the ``catch-and-ignore" pattern, where the handler is empty because the exception does not appear relevant to the programmer versus
-repairing or recovering from the exception.
+Checked exceptions are part of a function's interface,
+the exception signature of the function.
+Every function that could be raised from a function, either directly or
+because it is not handled from a called function, is given.
+Using this information, it is possible to statically verify if any given
+exception is handled and guarantee that no exception will go unhandled.
+Making exception information explicit improves clarity and safety,
+but can slow down or restrict programming.
+For example, programming high-order functions becomes much more complex
+if the argument functions could raise exceptions.
+However, as odd it may seem, the worst problems are rooted in the simple
+inconvenience of writing and updating exception signatures.
+This has caused Java programmers to develop multiple programming ``hacks''
+to circumvent checked exceptions, negating their advantages.
+One particularly problematic example is the ``catch-and-ignore'' pattern,
+where an empty handler is used to handle an exception without doing any
+recovery or repair. In theory that could be good enough to properly handle
+the exception, but more often is used to ignore an exception that the       
+programmer does not feel is worth the effort of handling it, for instance if
+they do not believe it will ever be raised.
+If they are incorrect the exception will be silenced, while in a similar
+situation with unchecked exceptions the exception would at least activate    
+the language's unhandled exception code (usually program abort with an  
+error message).
 
 %\subsection
 Resumption exceptions are less popular,
-although resumption is as old as termination;
-hence, few
+although resumption is as old as termination; hence, few
 programming languages have implemented them.
 % http://bitsavers.informatik.uni-stuttgart.de/pdf/xerox/parc/techReports/
 %   CSL-79-3_Mesa_Language_Manual_Version_5.0.pdf
-Mesa~\cite{Mesa} is one programming languages that did. Experience with Mesa
-is quoted as being one of the reasons resumptions are not
+Mesa is one programming language that did.\todo{cite Mesa} Experience with Mesa
+is quoted as being one of the reasons resumptions were not
 included in the \Cpp standard.
 % https://en.wikipedia.org/wiki/Exception_handling
-As a result, resumption has ignored in main-stream programming languages.
-However, ``what goes around comes around'' and resumption is being revisited now (like user-level threading).
-While rejecting resumption might have been the right decision in the past, there are decades
-of developments in computer science that have changed the situation.
-Some of these developments, such as functional programming's resumption
-equivalent, algebraic effects\cite{Zhang19}, are enjoying significant success.
-A complete reexamination of resumptions is beyond this thesis, but their re-emergence is
-enough to try them in \CFA.
+Since then resumptions have been ignored in main-stream programming languages.
+However, resumption is being revisited in the context of decades of other
+developments in programming languages.
+While rejecting resumption may have been the right decision in the past,
+the situation has changed since then.
+Some developments, such as the function programming equivalent to resumptions,
+algebraic effects\cite{Zhang19}, are enjoying success.
+A complete reexamination of resumptions is beyond this thesis,
+but there reemergence is enough to try them in \CFA.
 % Especially considering how much easier they are to implement than
-% termination exceptions.
-
-%\subsection
-Functional languages tend to use other solutions for their primary EHM,
-but exception-like constructs still appear.
-Termination appears in error construct, which marks the result of an
-expression as an error; thereafter, the result of any expression that tries to use it is also an
-error, and so on until an appropriate handler is reached.
+% termination exceptions and how much Peter likes them.
+
+%\subsection
+Functional languages tend to use other solutions for their primary error
+handling mechanism, but exception-like constructs still appear.
+Termination appears in the error construct, which marks the result of an
+expression as an error; then the result of any expression that tries to use
+it also results in an error, and so on until an appropriate handler is reached.
 Resumption appears in algebraic effects, where a function dispatches its
 side-effects to its caller for handling.
 
 %\subsection
-Some programming languages have moved to a restricted kind of EHM
-called ``panic".
-In Rust~\cite{Rust}, a panic is just a program level abort that may be implemented by
-unwinding the stack like in termination exception handling.
+More recently exceptions seem to be vanishing from newer programming
+languages, replaced by ``panic".
+In Rust, a panic is just a program level abort that may be implemented by
+unwinding the stack like in termination exception handling.\todo{cite Rust}
 % https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
-In Go~\cite{Go}, a panic is very similar to a termination, except it only supports
+Go's panic through is very similar to a termination, except it only supports
 a catch-all by calling \code{Go}{recover()}, simplifying the interface at
-the cost of flexibility.
+the cost of flexibility.\todo{cite Go}
 
 %\subsection
 While exception handling's most common use cases are in error handling,
-here are other ways to handle errors with comparisons to exceptions.
+here are some other ways to handle errors with comparisons with exceptions.
 \begin{itemize}
 \item\emph{Error Codes}:
-This pattern has a function return an enumeration (or just a set of fixed values) to indicate
-if an error occurred and possibly which error it was.
-
-Error codes mix exceptional and normal values, artificially enlarging the type and/or value range.
-Some languages address this issue by returning multiple values or a tuple, separating the error code from the function result.
-However, the main issue with error codes is forgetting to checking them,
+This pattern has a function return an enumeration (or just a set of fixed
+values) to indicate if an error has occurred and possibly which error it was.
+
+Error codes mix exceptional/error and normal values, enlarging the range of
+possible return values. This can be addressed with multiple return values
+(or a tuple) or a tagged union.
+However, the main issue with error codes is forgetting to check them,
 which leads to an error being quietly and implicitly ignored.
-Some new languages have tools that issue warnings, if the error code is
-discarded to avoid this problem.
-Checking error codes also results in bloating the main execution path, especially if an error is not dealt with locally and has to be cascaded down the call stack to a higher-level function..
+Some new languages and tools will try to issue warnings when an error code
+is discarded to avoid this problem.
+Checking error codes also bloats the main execution path,
+especially if the error is not handled immediately hand has to be passed
+through multiple functions before it is addressed.
 
 \item\emph{Special Return with Global Store}:
-Some functions only return a boolean indicating success or failure
-and store the exact reason for the error in a fixed global location.
-For example, many C routines return non-zero or -1, indicating success or failure,
-and write error details into the C standard variable @errno@.
-
-This approach avoids the multiple results issue encountered with straight error codes
-but otherwise has many (if not more) of the disadvantages.
-For example, everything that uses the global location must agree on all possible errors and global variable are unsafe with concurrency.
+Similar to the error codes pattern but the function itself only returns
+that there was an error
+and store the reason for the error in a fixed global location.
+For example many routines in the C standard library will only return some
+error value (such as -1 or a null pointer) and the error code is written into
+the standard variable @errno@.
+
+This approach avoids the multiple results issue encountered with straight
+error codes but otherwise has the same disadvantages and more.
+Every function that reads or writes to the global store must agree on all
+possible errors and managing it becomes more complex with concurrency.
 
 \item\emph{Return Union}:
@@ -254,39 +255,44 @@
 so that one type can be used everywhere in error handling code.
 
-This pattern is very popular in functional or any semi-functional language with
-primitive support for tagged unions (or algebraic data types).
-% We need listing Rust/rust to format code snipits from it.
+This pattern is very popular in any functional or semi-functional language
+with primitive support for tagged unions (or algebraic data types).
+% We need listing Rust/rust to format code snippets from it.
 % Rust's \code{rust}{Result<T, E>}
-The main advantage is providing for more information about an
-error, other than one of a fix-set of ids.
-While some languages use checked union access to force error-code checking,
-it is still possible to bypass the checking.
-The main disadvantage is again significant error code on the main execution path and cascading through called functions.
+The main advantage is that an arbitrary object can be used to represent an
+error so it can include a lot more information than a simple error code.
+The disadvantages include that the it does have to be checked along the main
+execution and if there aren't primitive tagged unions proper usage can be
+hard to enforce.
 
 \item\emph{Handler Functions}:
-This pattern implicitly associates functions with errors.
-On error, the function that produced the error implicitly calls another function to
+This pattern associates errors with functions.
+On error, the function that produced the error calls another function to
 handle it.
 The handler function can be provided locally (passed in as an argument,
 either directly as as a field of a structure/object) or globally (a global
 variable).
-C++ uses this approach as its fallback system if exception handling fails, \eg
-\snake{std::terminate_handler} and for a time \snake{std::unexpected_handler}
-
-Handler functions work a lot like resumption exceptions, without the dynamic handler search.
-Therefore, setting setting up the handler can be more complex/expensive, especially if the handle must be passed through multiple function calls, but cheaper to call $O(1)$, and hence,
-are more suited to frequent exceptional situations.
-% The exception being global handlers if they are rarely change as the time
-% in both cases shrinks towards zero.
+C++ uses this approach as its fallback system if exception handling fails,
+such as \snake{std::terminate_handler} and, for a time,
+\snake{std::unexpected_handler}.
+
+Handler functions work a lot like resumption exceptions,
+but without the dynamic search for a handler.
+Since setting up the handler can be more complex/expensive,
+especially when the handler has to be passed through multiple layers of
+function calls, but cheaper (constant time) to call,
+they are more suited to more frequent (less exceptional) situations.
 \end{itemize}
 
 %\subsection
 Because of their cost, exceptions are rarely used for hot paths of execution.
-Therefore, there is an element of self-fulfilling prophecy for implementation
-techniques to make exceptions cheap to set-up at the cost
-of expensive usage.
-This cost differential is less important in higher-level scripting languages, where use of exceptions for other tasks is more common.
-An iconic example is Python's @StopIteration@ exception that is thrown by
-an iterator to indicate that it is exhausted, especially when combined with Python's heavy
-use of the iterator-based for-loop.
+Hence, there is an element of self-fulfilling prophecy as implementation
+techniques have been focused on making them cheap to set-up,
+happily making them expensive to use in exchange.
+This difference is less important in higher-level scripting languages,
+where using exception for other tasks is more common.
+An iconic example is Python's \code{Python}{StopIteration} exception that
+is thrown by an iterator to indicate that it is exhausted.
+When paired with Python's iterator-based for-loop this will be thrown every
+time the end of the loop is reached.
+\todo{Cite Python StopIteration and for-each loop.}
 % https://docs.python.org/3/library/exceptions.html#StopIteration
Index: doc/theses/andrew_beach_MMath/uw-ethesis.tex
===================================================================
--- doc/theses/andrew_beach_MMath/uw-ethesis.tex	(revision 315e5e373412e790b084d3570db5755620ef6682)
+++ doc/theses/andrew_beach_MMath/uw-ethesis.tex	(revision 1a6a6f26a61c6a96404ba4a9bf6062bd5ba07959)
@@ -210,6 +210,4 @@
 \lstMakeShortInline@
 \lstset{language=CFA,style=cfacommon,basicstyle=\linespread{0.9}\tt}
-% PAB causes problems with inline @=
-%\lstset{moredelim=**[is][\protect\color{red}]{@}{@}}
 % Annotations from Peter:
 \newcommand{\PAB}[1]{{\color{blue}PAB: #1}}
