Changeset 9cdfa5fb


Ignore:
Timestamp:
Sep 10, 2021, 10:43:15 AM (3 years ago)
Author:
Andrew Beach <ajbeach@…>
Branches:
ADT, ast-experimental, enum, forall-pointer-decay, master, pthread-emulation, qualifiedEnum
Children:
63b3279
Parents:
d0b9247
Message:

Andrew MMath: Used (most of) Gregor's feedback to update the thesis. There are still a few \todo items as well as a general request for examples.

Location:
doc/theses/andrew_beach_MMath
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • doc/theses/andrew_beach_MMath/conclusion.tex

    rd0b9247 r9cdfa5fb  
    33% Just a little knot to tie the paper together.
    44
    5 In the previous chapters this thesis presents the design and implementation
     5In the previous chapters, this thesis presents the design and implementation
    66of \CFA's exception handling mechanism (EHM).
    77Both the design and implementation are based off of tools and
    88techniques developed for other programming languages but they were adapted to
    99better fit \CFA's feature set and add a few features that do not exist in
    10 other EHMs;
     10other EHMs,
    1111including conditional matching, default handlers for unhandled exceptions
    1212and cancellation though coroutines and threads back to the program main stack.
  • doc/theses/andrew_beach_MMath/existing.tex

    rd0b9247 r9cdfa5fb  
    66compatibility with C and its programmers.  \CFA is designed to have an
    77orthogonal feature-set based closely on the C programming paradigm
    8 (non-object-oriented) and these features can be added incrementally to an
    9 existing C code-base allowing programmers to learn \CFA on an as-needed basis.
     8(non-object-oriented), and these features can be added incrementally to an
     9existing C code-base,
     10allowing programmers to learn \CFA on an as-needed basis.
    1011
    1112Only those \CFA features pertaining to this thesis are discussed.
     
    4546\CFA adds a reference type to C as an auto-dereferencing pointer.
    4647They work very similarly to pointers.
    47 Reference-types are written the same way as a pointer-type but each
     48Reference-types are written the same way as pointer-types, but each
    4849asterisk (@*@) is replaced with a ampersand (@&@);
    49 this includes cv-qualifiers and multiple levels of reference.
    50 
    51 Generally, references act like pointers with an implicate dereferencing
     50this includes cv-qualifiers (\snake{const} and \snake{volatile})
     51%\todo{Should I go into even more detail on cv-qualifiers.}
     52and multiple levels of reference.
     53
     54Generally, references act like pointers with an implicit dereferencing
    5255operation added to each use of the variable.
    5356These automatic dereferences may be disabled with the address-of operator
     
    8386Mutable references may be assigned to by converting them to a pointer
    8487with a @&@ and then assigning a pointer to them, as in @&ri = &j;@ above.
    85 % ???
    8688
    8789\section{Operators}
     
    9395For example,
    9496infixed multiplication is @?*?@, while prefix dereference is @*?@.
    95 This syntax make it easy to tell the difference between prefix operations
    96 (such as @++?@) and post-fix operations (@?++@).
     97This syntax makes it easy to tell the difference between prefix operations
     98(such as @++?@) and postfix operations (@?++@).
    9799
    98100As an example, here are the addition and equality operators for a point type.
     
    104106}
    105107\end{cfa}
    106 Note that this syntax works effectively but a textual transformation,
     108Note that this syntax works effectively as a textual transformation;
    107109the compiler converts all operators into functions and then resolves them
    108110normally. This means any combination of types may be used,
     
    113115%\subsection{Constructors and Destructors}
    114116In \CFA, constructors and destructors are operators, which means they are
    115 functions with special operator names rather than type names in \Cpp.
     117functions with special operator names, rather than type names as in \Cpp.
    116118Both constructors and destructors can be implicity called by the compiler,
    117119however the operator names allow explicit calls.
     
    137139@b@ because of the explicit call and @a@ implicitly.
    138140@c@ will be initalized with the second constructor.
    139 Currently, there is no general way to skip initialation.
     141Currently, there is no general way to skip initialization.
    140142% I don't use @= anywhere in the thesis.
    141143
     
    202204do_twice(i);
    203205\end{cfa}
    204 Any object with a type fulfilling the assertion may be passed as an argument to
     206Any value with a type fulfilling the assertion may be passed as an argument to
    205207a @do_twice@ call.
    206208
     
    222224function. The matched assertion function is then passed as a function pointer
    223225to @do_twice@ and called within it.
    224 The global definition of @do_once@ is ignored, however if quadruple took a
     226The global definition of @do_once@ is ignored, however if @quadruple@ took a
    225227@double@ argument, then the global definition would be used instead as it
    226228would then be a better match.\cite{Moss19}
    227229
    228230To avoid typing long lists of assertions, constraints can be collected into
    229 convenient a package called a @trait@, which can then be used in an assertion
     231a convenient package called a @trait@, which can then be used in an assertion
    230232instead of the individual constraints.
    231233\begin{cfa}
     
    241243functions and variables, and are usually used to create a shorthand for, and
    242244give descriptive names to, common groupings of assertions describing a certain
    243 functionality, like @sumable@, @listable@, \etc.
     245functionality, like @summable@, @listable@, \etc.
    244246
    245247Polymorphic structures and unions are defined by qualifying an aggregate type
    246248with @forall@. The type variables work the same except they are used in field
    247 declarations instead of parameters, returns, and local variable declarations.
     249declarations instead of parameters, returns and local variable declarations.
    248250\begin{cfa}
    249251forall(dtype T)
     
    261263
    262264\section{Control Flow}
    263 \CFA has a number of advanced control-flow features: @generator@, @coroutine@, @monitor@, @mutex@ parameters, and @thread@.
     265\CFA has a number of advanced control-flow features: @generator@, @coroutine@,
     266@monitor@, @mutex@ parameters, and @thread@.
    264267The two features that interact with
    265268the exception system are @coroutine@ and @thread@; they and their supporting
     
    268271\subsection{Coroutine}
    269272A coroutine is a type with associated functions, where the functions are not
    270 required to finish execution when control is handed back to the caller. Instead
     273required to finish execution when control is handed back to the caller.
     274Instead,
    271275they may suspend execution at any time and be resumed later at the point of
    272 last suspension. (Generators are stackless and coroutines are stackful.) These
     276last suspension.
     277Coroutine
    273278types are not concurrent but share some similarities along with common
    274 underpinnings, so they are combined with the \CFA threading library. Further
    275 discussion in this section only refers to the coroutine because generators are
    276 similar.
     279underpinnings, so they are combined with the \CFA threading library.
     280% I had mention of generators, but they don't actually matter here.
    277281
    278282In \CFA, a coroutine is created using the @coroutine@ keyword, which is an
     
    322326\end{cfa}
    323327
    324 When the main function returns the coroutine halts and can no longer be
     328When the main function returns, the coroutine halts and can no longer be
    325329resumed.
    326330
    327331\subsection{Monitor and Mutex Parameter}
    328 Concurrency does not guarantee ordering; without ordering results are
     332Concurrency does not guarantee ordering; without ordering, results are
    329333non-deterministic. To claw back ordering, \CFA uses monitors and @mutex@
    330334(mutual exclusion) parameters. A monitor is another kind of aggregate, where
     
    332336@mutex@ parameters.
    333337
    334 A function that requires deterministic (ordered) execution, acquires mutual
     338A function that requires deterministic (ordered) execution acquires mutual
    335339exclusion on a monitor object by qualifying an object reference parameter with
    336 @mutex@.
     340the @mutex@ qualifier.
    337341\begin{cfa}
    338342void example(MonitorA & mutex argA, MonitorB & mutex argB);
     
    344348
    345349\subsection{Thread}
    346 Functions, generators, and coroutines are sequential so there is only a single
     350Functions, generators and coroutines are sequential, so there is only a single
    347351(but potentially sophisticated) execution path in a program. Threads introduce
    348352multiple execution paths that continue independently.
    349353
    350354For threads to work safely with objects requires mutual exclusion using
    351 monitors and mutex parameters. For threads to work safely with other threads,
     355monitors and mutex parameters. For threads to work safely with other threads
    352356also requires mutual exclusion in the form of a communication rendezvous, which
    353357also supports internal synchronization as for mutex objects. For exceptions,
  • doc/theses/andrew_beach_MMath/features.tex

    rd0b9247 r9cdfa5fb  
    55and begins with a general overview of EHMs. It is not a strict
    66definition of all EHMs nor an exhaustive list of all possible features.
    7 However it does cover the most common structure and features found in them.
     7However, it does cover the most common structure and features found in them.
    88
    99\section{Overview of EHMs}
     
    4242
    4343The @try@ statements of \Cpp, Java and Python are common examples. All three
    44 also show another common feature of handlers, they are grouped by the guarded
     44also show another common feature of handlers: they are grouped by the guarded
    4545region.
    4646
     
    101101between different sub-hierarchies.
    102102This design is used in \CFA even though it is not a object-orientated
    103 language; so different tools are used to create the hierarchy.
     103language, so different tools are used to create the hierarchy.
    104104
    105105% Could I cite the rational for the Python IO exception rework?
     
    118118For effective exception handling, additional information is often passed
    119119from the raise to the handler and back again.
    120 So far, only communication of the exceptions' identity is covered.
     120So far, only communication of the exception's identity is covered.
    121121A common communication method for adding information to an exception
    122122is putting fields into the exception instance
     
    129129\section{Virtuals}
    130130\label{s:virtuals}
     131%\todo{Maybe explain what "virtual" actually means.}
    131132Virtual types and casts are not part of \CFA's EHM nor are they required for
    132133an EHM.
     
    152153% A type's descendants are its children and its children's descendants.
    153154
    154 For the purposes of illustration, a proposed -- but unimplemented syntax --
     155For the purposes of illustration, a proposed, but unimplemented, syntax
    155156will be used. Each virtual type is represented by a trait with an annotation
    156157that makes it a virtual type. This annotation is empty for a root type, which
     
    177178\end{minipage}
    178179
    179 Every virtual type also has a list of virtual members and a unique id,
    180 both are stored in a virtual table.
     180Every virtual type also has a list of virtual members and a unique id.
     181Both are stored in a virtual table.
    181182Every instance of a virtual type also has a pointer to a virtual table stored
    182183in it, although there is no per-type virtual table as in many other languages.
    183184
    184 The list of virtual members is built up down the tree. Every virtual type
     185The list of virtual members is accumulated from the root type down the tree.
     186Every virtual type
    185187inherits the list of virtual members from its parent and may add more
    186188virtual members to the end of the list which are passed on to its children.
     
    198200% Consider adding a diagram, but we might be good with the explanation.
    199201
    200 As @child_type@ is a child of @root_type@ it has the virtual members of
     202As @child_type@ is a child of @root_type@, it has the virtual members of
    201203@root_type@ (@to_string@ and @size@) as well as the one it declared
    202204(@irrelevant_function@).
     
    206208The names ``size" and ``align" are reserved for the size and alignment of the
    207209virtual type, and are always automatically initialized as such.
    208 The other special case are uses of the trait's polymorphic argument
     210The other special case is uses of the trait's polymorphic argument
    209211(@T@ in the example), which are always updated to refer to the current
    210 virtual type. This allows functions that refer to to polymorphic argument
     212virtual type. This allows functions that refer to the polymorphic argument
    211213to act as traditional virtual methods (@to_string@ in the example), as the
    212214object can always be passed to a virtual method in its virtual table.
    213215
    214 Up until this point the virtual system is similar to ones found in
    215 object-oriented languages but this is where \CFA diverges.
     216Up until this point, the virtual system is similar to ones found in
     217object-oriented languages, but this is where \CFA diverges.
    216218Objects encapsulate a single set of methods in each type,
    217219universally across the entire program,
     
    223225
    224226In \CFA, types do not encapsulate any code.
    225 Whether or not satisfies any given assertion, and hence any trait, is
     227Whether or not a type satisfies any given assertion, and hence any trait, is
    226228context sensitive. Types can begin to satisfy a trait, stop satisfying it or
    227229satisfy the same trait at any lexical location in the program.
    228 In this sense, an type's implementation in the set of functions and variables
     230In this sense, a type's implementation in the set of functions and variables
    229231that allow it to satisfy a trait is ``open" and can change
    230232throughout the program.
     
    248250\end{cfa}
    249251
    250 Like any variable they may be forward declared with the @extern@ keyword.
     252Like any variable, they may be forward declared with the @extern@ keyword.
    251253Forward declaring virtual tables is relatively common.
    252254Many virtual types have an ``obvious" implementation that works in most
     
    259261Initialization is automatic.
    260262The type id and special virtual members ``size" and ``align" only depend on
    261 the virtual type, which is fixed given the type of the virtual table and
     263the virtual type, which is fixed given the type of the virtual table, and
    262264so the compiler fills in a fixed value.
    263 The other virtual members are resolved, using the best match to the member's
     265The other virtual members are resolved using the best match to the member's
    264266name and type, in the same context as the virtual table is declared using
    265267\CFA's normal resolution rules.
    266268
    267 While much of the virtual infrastructure is created, it is currently only used
     269While much of the virtual infrastructure has been created,
     270it is currently only used
    268271internally for exception handling. The only user-level feature is the virtual
    269272cast, which is the same as the \Cpp \code{C++}{dynamic_cast}.
     
    274277Note, the syntax and semantics matches a C-cast, rather than the function-like
    275278\Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be
    276 a pointer to a virtual type.
     279pointers to virtual types.
    277280The cast dynamically checks if the @EXPRESSION@ type is the same or a sub-type
    278281of @TYPE@, and if true, returns a pointer to the
    279282@EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
     283This allows the expression to be used as both a cast and a type check.
    280284
    281285\section{Exceptions}
    282286
    283287The syntax for declaring an exception is the same as declaring a structure
    284 except the keyword that is swapped out:
     288except the keyword:
    285289\begin{cfa}
    286290exception TYPE_NAME {
     
    289293\end{cfa}
    290294
    291 Fields are filled in the same way as a structure as well. However an extra
     295Fields are filled in the same way as a structure as well. However, an extra
    292296field is added that contains the pointer to the virtual table.
    293297It must be explicitly initialized by the user when the exception is
     
    299303
    300304\begin{minipage}[t]{0.4\textwidth}
    301 Header:
     305Header (.hfa):
    302306\begin{cfa}
    303307exception Example {
     
    310314\end{minipage}
    311315\begin{minipage}[t]{0.6\textwidth}
    312 Source:
     316Implementation (.cfa):
    313317\begin{cfa}
    314318vtable(Example) example_base_vtable
     
    319323%\subsection{Exception Details}
    320324This is the only interface needed when raising and handling exceptions.
    321 However it is actually a short hand for a more complex
    322 trait based interface.
     325However, it is actually a shorthand for a more complex
     326trait-based interface.
    323327
    324328The language views exceptions through a series of traits.
     
    336340completing the virtual system). The imaginary assertions would probably come
    337341from a trait defined by the virtual system, and state that the exception type
    338 is a virtual type, is a descendant of @exception_t@ (the base exception type)
     342is a virtual type,
     343that that the type is a descendant of @exception_t@ (the base exception type)
    339344and allow the user to find the virtual table type.
    340345
     
    355360};
    356361\end{cfa}
    357 Both traits ensure a pair of types is an exception type, its virtual table
    358 type
     362Both traits ensure a pair of types is an exception type and
     363its virtual table type,
    359364and defines one of the two default handlers. The default handlers are used
    360 as fallbacks and are discussed in detail in \vref{s:ExceptionHandling}.
     365as fallbacks and are discussed in detail in \autoref{s:ExceptionHandling}.
    361366
    362367However, all three of these traits can be tricky to use directly.
    363368While there is a bit of repetition required,
    364369the largest issue is that the virtual table type is mangled and not in a user
    365 facing way. So these three macros are provided to wrap these traits to
     370facing way. So, these three macros are provided to wrap these traits to
    366371simplify referring to the names:
    367372@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
     
    371376The second (optional) argument is a parenthesized list of polymorphic
    372377arguments. This argument is only used with polymorphic exceptions and the
    373 list is be passed to both types.
     378list is passed to both types.
    374379In the current set-up, the two types always have the same polymorphic
    375 arguments so these macros can be used without losing flexibility.
    376 
    377 For example consider a function that is polymorphic over types that have a
     380arguments, so these macros can be used without losing flexibility.
     381
     382For example, consider a function that is polymorphic over types that have a
    378383defined arithmetic exception:
    379384\begin{cfa}
     
    388393These twin operations are the core of \CFA's exception handling mechanism.
    389394This section covers the general patterns shared by the two operations and
    390 then goes on to cover the details each individual operation.
     395then goes on to cover the details of each individual operation.
    391396
    392397Both operations follow the same set of steps.
     
    407412\label{s:Termination}
    408413Termination handling is the familiar kind of handling
    409 and used in most programming
     414used in most programming
    410415languages with exception handling.
    411416It is a dynamic, non-local goto. If the raised exception is matched and
     
    483488Since it is so general, a more specific handler can be defined,
    484489overriding the default behaviour for the specific exception types.
     490%\todo{Examples?}
    485491
    486492\subsection{Resumption}
     
    542548@EXCEPTION_TYPE@$_i$ is matched and @NAME@$_i$ is bound to the exception,
    543549@HANDLER_BLOCK@$_i$ is executed right away without first unwinding the stack.
    544 After the block has finished running control jumps to the raise site, where
     550After the block has finished running, control jumps to the raise site, where
    545551the just handled exception came from, and continues executing after it,
    546552not after the try statement.
     553%\todo{Examples?}
    547554
    548555\subsubsection{Resumption Marking}
     
    551558not unwind the stack. A side effect is that, when a handler is matched
    552559and run, its try block (the guarded statements) and every try statement
    553 searched before it are still on the stack. There presence can lead to
     560searched before it are still on the stack. Their presence can lead to
    554561the recursive resumption problem.\cite{Buhr00a}
    555562% Other possible citation is MacLaren77, but the form is different.
     
    585592\end{center}
    586593
    587 There are other sets of marking rules that could be used,
    588 for instance, marking just the handlers that caught the exception,
     594There are other sets of marking rules that could be used.
     595For instance, marking just the handlers that caught the exception
    589596would also prevent recursive resumption.
    590 However, the rules selected mirrors what happens with termination,
     597However, the rules selected mirror what happens with termination,
    591598so this reduces the amount of rules and patterns a programmer has to know.
    592599
     
    628635// Handle a failure relating to f2 further down the stack.
    629636\end{cfa}
    630 In this example the file that experienced the IO error is used to decide
     637In this example, the file that experienced the IO error is used to decide
    631638which handler should be run, if any at all.
    632639
     
    657664
    658665\subsection{Comparison with Reraising}
    659 In languages without conditional catch, that is no ability to match an
    660 exception based on something other than its type, it can be mimicked
     666In languages without conditional catch -- that is, no ability to match an
     667exception based on something other than its type -- it can be mimicked
    661668by matching all exceptions of the right type, checking any additional
    662669conditions inside the handler and re-raising the exception if it does not
     
    664671
    665672Here is a minimal example comparing both patterns, using @throw;@
    666 (no argument) to start a re-raise.
     673(no operand) to start a re-raise.
    667674\begin{center}
    668675\begin{tabular}{l r}
     
    692699\end{tabular}
    693700\end{center}
    694 At first glance catch-and-reraise may appear to just be a quality of life
     701At first glance, catch-and-reraise may appear to just be a quality-of-life
    695702feature, but there are some significant differences between the two
    696 stratagies.
     703strategies.
    697704
    698705A simple difference that is more important for \CFA than many other languages
    699 is that the raise site changes, with a re-raise but does not with a
     706is that the raise site changes with a re-raise, but does not with a
    700707conditional catch.
    701708This is important in \CFA because control returns to the raise site to run
    702 the per-site default handler. Because of this only a conditional catch can
     709the per-site default handler. Because of this, only a conditional catch can
    703710allow the original raise to continue.
    704711
     
    753760%   } else throw;
    754761% }
    755 In similar simple examples translating from re-raise to conditional catch
    756 takes less code but it does not have a general trivial solution either.
     762In similar simple examples, translating from re-raise to conditional catch
     763takes less code but it does not have a general, trivial solution either.
    757764
    758765So, given that the two patterns do not trivially translate into each other,
    759766it becomes a matter of which on should be encouraged and made the default.
    760 From the premise that if a handler that could handle an exception then it
     767From the premise that if a handler could handle an exception then it
    761768should, it follows that checking as many handlers as possible is preferred.
    762 So conditional catch and checking later handlers is a good default.
     769So, conditional catch and checking later handlers is a good default.
    763770
    764771\section{Finally Clauses}
    765772\label{s:FinallyClauses}
    766 Finally clauses are used to preform unconditional clean-up when leaving a
     773Finally clauses are used to perform unconditional cleanup when leaving a
    767774scope and are placed at the end of a try statement after any handler clauses:
    768775\begin{cfa}
     
    782789Execution of the finally block should always finish, meaning control runs off
    783790the end of the block. This requirement ensures control always continues as if
    784 the finally clause is not present, \ie finally is for cleanup not changing
     791the finally clause is not present, \ie finally is for cleanup, not changing
    785792control flow.
    786793Because of this requirement, local control flow out of the finally block
    787794is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or
    788795@return@ that causes control to leave the finally block. Other ways to leave
    789 the finally block, such as a long jump or termination are much harder to check,
    790 and at best requiring additional run-time overhead, and so are only
     796the finally block, such as a @longjmp@ or termination are much harder to check,
     797and at best require additional run-time overhead, and so are only
    791798discouraged.
    792799
    793 Not all languages with unwinding have finally clauses. Notably \Cpp does
     800Not all languages with unwinding have finally clauses. Notably, \Cpp does
    794801without it as destructors, and the RAII design pattern, serve a similar role.
    795802Although destructors and finally clauses can be used for the same cases,
     
    798805Destructors take more work to create, but if there is clean-up code
    799806that needs to be run every time a type is used, they are much easier
    800 to set-up for each use. % It's automatic.
    801 On the other hand finally clauses capture the local context, so is easy to
    802 use when the clean-up is not dependent on the type of a variable or requires
     807to set up for each use. % It's automatic.
     808On the other hand, finally clauses capture the local context, so are easy to
     809use when the cleanup is not dependent on the type of a variable or requires
    803810information from multiple variables.
    804811
     
    807814Cancellation is a stack-level abort, which can be thought of as as an
    808815uncatchable termination. It unwinds the entire current stack, and if
    809 possible forwards the cancellation exception to a different stack.
     816possible, forwards the cancellation exception to a different stack.
    810817
    811818Cancellation is not an exception operation like termination or resumption.
    812819There is no special statement for starting a cancellation; instead the standard
    813 library function @cancel_stack@ is called passing an exception. Unlike a
    814 raise, this exception is not used in matching only to pass information about
     820library function @cancel_stack@ is called, passing an exception. Unlike a
     821raise, this exception is not used in matching, only to pass information about
    815822the cause of the cancellation.
    816823Finally, as no handler is provided, there is no default handler.
    817824
    818 After @cancel_stack@ is called the exception is copied into the EHM's memory
     825After @cancel_stack@ is called, the exception is copied into the EHM's memory
    819826and the current stack is unwound.
    820827The behaviour after that depends on the kind of stack being cancelled.
    821828
    822829\paragraph{Main Stack}
    823 The main stack is the one used by the program main at the start of execution,
     830The main stack is the one used by
     831the program's main function at the start of execution,
    824832and is the only stack in a sequential program.
    825 After the main stack is unwound there is a program-level abort.
     833After the main stack is unwound, there is a program-level abort.
    826834
    827835The first reason for this behaviour is for sequential programs where there
    828 is only one stack, and hence to stack to pass information to.
     836is only one stack, and hence no stack to pass information to.
    829837Second, even in concurrent programs, the main stack has no dependency
    830838on another stack and no reliable way to find another living stack.
     
    842850and an implicit join (from a destructor call). The explicit join takes the
    843851default handler (@defaultResumptionHandler@) from its calling context while
    844 the implicit join provides its own; which does a program abort if the
     852the implicit join provides its own, which does a program abort if the
    845853@ThreadCancelled@ exception cannot be handled.
    846854
  • doc/theses/andrew_beach_MMath/future.tex

    rd0b9247 r9cdfa5fb  
    33
    44The following discussion covers both possible interesting research
    5 that could follow from this work as long as simple implementation
     5that could follow from this work as well as simple implementation
    66improvements.
    77
     
    1010\CFA is a developing programming language. As such, there are partially or
    1111unimplemented features (including several broken components)
    12 that I had to workaround while building the EHM largely in
     12that I had to work around while building the EHM largely in
    1313the \CFA language (some C components). Below are a few of these issues
    1414and how implementing/fixing them would affect the EHM.
    15 In addition there are some simple improvements that had no interesting
     15In addition, there are some simple improvements that had no interesting
    1616research attached to them but would make using the language easier.
    1717\begin{itemize}
     
    2828Termination handlers cannot use local control-flow transfers, \eg by @break@,
    2929@return@, \etc. The reason is that current code generation hoists a handler
    30 into a nested function for convenience (versus assemble-code generation at the
     30into a nested function for convenience (versus assembly-code generation at the
    3131try statement). Hence, when the handler runs, it can still access local
    3232variables in the lexical scope of the try statement. Still, it does mean
    3333that seemingly local control flow is not in fact local and crosses a function
    3434boundary.
    35 Making the termination handlers code within the surrounding
     35Making the termination handler's code within the surrounding
    3636function would remove this limitation.
    3737% Try blocks are much more difficult to do practically (requires our own
    3838% assembly) and resumption handlers have some theoretical complexity.
    3939\item
    40 There is no detection of colliding unwinds. It is possible for clean-up code
    41 run during an unwind to trigger another unwind that escapes the clean-up code
    42 itself; such as a termination exception caught further down the stack or a
     40There is no detection of colliding unwinds. It is possible for cleanup code
     41run during an unwind to trigger another unwind that escapes the cleanup code
     42itself, such as a termination exception caught further down the stack or a
    4343cancellation. There do exist ways to handle this case, but currently there is
    4444no detection and the first unwind will simply be forgotten, often leaving
     
    6464Other features of the virtual system could also remove some of the
    6565special cases around exception virtual tables, such as the generation
    66 of the @msg@ function, could be removed.
     66of the @msg@ function.
    6767
    6868The full virtual system might also include other improvement like associated
     
    7474\section{Additional Raises}
    7575Several other kinds of exception raises were considered beyond termination
    76 (@throw@), resumption (@throwResume@), and reraise.
     76(@throw@), resumption (@throwResume@), and re-raise.
    7777
    7878The first is a non-local/concurrent raise providing asynchronous exceptions,
     
    110110passed on.
    111111
    112 However checked exceptions were never seriously considered for this project
     112Checked exceptions were never seriously considered for this project
    113113because they have significant trade-offs in usability and code reuse in
    114114exchange for the increased safety.
     
    116116higher-order functions from the functions the user passed into the
    117117higher-order function. There are no well known solutions to this problem
    118 that were satisfactory for \CFA (which carries some of C's flexibility
    119 over safety design) so additional research is needed.
     118that were satisfactory for \CFA (which carries some of C's
     119flexibility-over-safety design) so additional research is needed.
    120120
    121121Follow-up work might add some form of checked exceptions to \CFA,
     
    140140Zero-cost resumptions is still an open problem. First, because libunwind does
    141141not support a successful-exiting stack-search without doing an unwind.
    142 Workarounds are possible but awkward. Ideally an extension to libunwind could
     142Workarounds are possible but awkward. Ideally, an extension to libunwind could
    143143be made, but that would either require separate maintenance or gaining enough
    144144support to have it folded into the official library itself.
    145145
    146 Also new techniques to skip previously searched parts of the stack need to be
     146Also, new techniques to skip previously searched parts of the stack need to be
    147147developed to handle the recursive resume problem and support advanced algebraic
    148148effects.
  • doc/theses/andrew_beach_MMath/implement.tex

    rd0b9247 r9cdfa5fb  
    1414\label{s:VirtualSystem}
    1515% Virtual table rules. Virtual tables, the pointer to them and the cast.
    16 While the \CFA virtual system currently has only one public features, virtual
     16While the \CFA virtual system currently has only two public features, virtual
    1717cast and virtual tables,
    18 % ??? refs (see the virtual cast feature \vpageref{p:VirtualCast}),
    1918substantial structure is required to support them,
    2019and provide features for exception handling and the standard library.
     
    3534as part of field-by-field construction.
    3635
    37 \subsection{Type Id}
    38 Every virtual type has a unique id.
     36\subsection{Type ID}
     37Every virtual type has a unique ID.
    3938These are used in type equality, to check if the representation of two values
    4039are the same, and to access the type's type information.
     
    4443
    4544Our approach for program uniqueness is using a static declaration for each
    46 type id, where the run-time storage address of that variable is guaranteed to
     45type ID, where the run-time storage address of that variable is guaranteed to
    4746be unique during program execution.
    48 The type id storage can also be used for other purposes,
     47The type ID storage can also be used for other purposes,
    4948and is used for type information.
    5049
    51 The problem is that a type id may appear in multiple TUs that compose a
    52 program (see \autoref{ss:VirtualTable}); so the initial solution would seem
    53 to be make it external in each translation unit. Hovever, the type id must
     50The problem is that a type ID may appear in multiple TUs that compose a
     51program (see \autoref{ss:VirtualTable}), so the initial solution would seem
     52to be make it external in each translation unit. Hovever, the type ID must
    5453have a declaration in (exactly) one of the TUs to create the storage.
    5554No other declaration related to the virtual type has this property, so doing
    5655this through standard C declarations would require the user to do it manually.
    5756
    58 Instead the linker is used to handle this problem.
     57Instead, the linker is used to handle this problem.
    5958% I did not base anything off of C++17; they are solving the same problem.
    6059A new feature has been added to \CFA for this purpose, the special attribute
    6160\snake{cfa_linkonce}, which uses the special section @.gnu.linkonce@.
    62 When used as a prefix (\eg @.gnu.linkonce.example@) the linker does
     61When used as a prefix (\eg @.gnu.linkonce.example@), the linker does
    6362not combine these sections, but instead discards all but one with the same
    6463full name.
    6564
    66 So each type id must be given a unique section name with the linkonce
    67 prefix. Luckily \CFA already has a way to get unique names, the name mangler.
     65So, each type ID must be given a unique section name with the \snake{linkonce}
     66prefix. Luckily, \CFA already has a way to get unique names, the name mangler.
    6867For example, this could be written directly in \CFA:
    6968\begin{cfa}
     
    7473__attribute__((section(".gnu.linkonce._X1fFv___1"))) void _X1fFv___1() {}
    7574\end{cfa}
    76 This is done internally to access the name manglers.
     75This is done internally to access the name mangler.
    7776This attribute is useful for other purposes, any other place a unique
    7877instance required, and should eventually be made part of a public and
     
    8180\subsection{Type Information}
    8281
    83 There is data stored at the type id's declaration, the type information.
    84 The type information currently is only the parent's type id or, if the
     82There is data stored at the type ID's declaration, the type information.
     83The type information currently is only the parent's type ID or, if the
    8584type has no parent, the null pointer.
    86 The ancestors of a virtual type are found by traversing type ids through
     85The ancestors of a virtual type are found by traversing type IDs through
    8786the type information.
    8887An example using helper macros looks like:
     
    105104\item
    106105Generate a new structure definition to store the type
    107 information. The layout is the same in each case, just the parent's type id,
     106information. The layout is the same in each case, just the parent's type ID,
    108107but the types used change from instance to instance.
    109108The generated name is used for both this structure and, if relevant, the
     
    115114\item
    116115The definition is generated and initialized.
    117 The parent id is set to the null pointer or to the address of the parent's
     116The parent ID is set to the null pointer or to the address of the parent's
    118117type information instance. Name resolution handles the rest.
    119118\item
     
    151150file as if it was a forward declaration, except no definition is required.
    152151
    153 This technique is used for type-id instances. A link-once definition is
     152This technique is used for type ID instances. A link-once definition is
    154153generated each time the structure is seen. This will result in multiple
    155154copies but the link-once attribute ensures all but one are removed for a
     
    168167\subsection{Virtual Table}
    169168\label{ss:VirtualTable}
    170 Each virtual type has a virtual table type that stores its type id and
     169%\todo{Clarify virtual table type vs. virtual table instance.}
     170Each virtual type has a virtual table type that stores its type ID and
    171171virtual members.
    172172Each virtual type instance is bound to a table instance that is filled with
     
    176176
    177177The layout always comes in three parts (see \autoref{f:VirtualTableLayout}).
    178 The first section is just the type id at the head of the table. It is always
     178The first section is just the type ID at the head of the table. It is always
    179179there to ensure that it can be found even when the accessing code does not
    180180know which virtual type it has.
    181 The second section are all the virtual members of the parent, in the same
     181The second section is all the virtual members of the parent, in the same
    182182order as they appear in the parent's virtual table. Note that the type may
    183183change slightly as references to the ``this" change. This is limited to
     
    199199This, combined with the fixed offset to the virtual table pointer, means that
    200200for any virtual type, it is always safe to access its virtual table and,
    201 from there, it is safe to check the type id to identify the exact type of the
     201from there, it is safe to check the type ID to identify the exact type of the
    202202underlying object, access any of the virtual members and pass the object to
    203203any of the method-like virtual members.
     
    207207the context of the declaration.
    208208
    209 The type id is always fixed; with each virtual table type having
    210 exactly one possible type id.
     209The type ID is always fixed, with each virtual table type having
     210exactly one possible type ID.
    211211The virtual members are usually filled in by type resolution.
    212212The best match for a given name and type at the declaration site is used.
    213213There are two exceptions to that rule: the @size@ field, the type's size,
    214 is set using a @sizeof@ expression and the @align@ field, the
     214is set using a @sizeof@ expression, and the @align@ field, the
    215215type's alignment, is set using an @alignof@ expression.
    216216
    217217Most of these tools are already inside the compiler. Using simple
    218 code transformations early on in compilation, allows most of that work to be
     218code transformations early on in compilation allows most of that work to be
    219219handed off to the existing tools. \autoref{f:VirtualTableTransformation}
    220 shows an example transformation, this example shows an exception virtual table.
     220shows an example transformation; this example shows an exception virtual table.
    221221It also shows the transformation on the full declaration.
    222222For a forward declaration, the @extern@ keyword is preserved and the
     
    312312        struct __cfavir_type_id * const * child );
    313313\end{cfa}
    314 The type id for the target type of the virtual cast is passed in as
     314The type ID for the target type of the virtual cast is passed in as
    315315@parent@ and
    316316the cast target is passed in as @child@.
     
    322322The virtual cast either returns the original pointer or the null pointer
    323323as the new type.
    324 So the function does the parent check and returns the appropriate value.
    325 The parent check is a simple linear search of child's ancestors using the
     324The function does the parent check and returns the appropriate value.
     325The parent check is a simple linear search of the child's ancestors using the
    326326type information.
    327327
     
    329329% The implementation of exception types.
    330330
    331 Creating exceptions can roughly divided into two parts,
     331Creating exceptions can be roughly divided into two parts:
    332332the exceptions themselves and the virtual system interactions.
    333333
     
    361361
    362362All types associated with a virtual type,
    363 the types of the virtual table and the type id,
     363the types of the virtual table and the type ID,
    364364are generated when the virtual type (the exception) is first found.
    365 The type id (the instance) is generated with the exception, if it is
     365The type ID (the instance) is generated with the exception, if it is
    366366a monomorphic type.
    367 However, if the exception is polymorphic, then a different type id has to
     367However, if the exception is polymorphic, then a different type ID has to
    368368be generated for every instance. In this case, generation is delayed
    369369until a virtual table is created.
     
    372372When a virtual table is created and initialized, two functions are created
    373373to fill in the list of virtual members.
    374 The first is a copy function that adapts the exception's copy constructor
     374The first is the @copy@ function that adapts the exception's copy constructor
    375375to work with pointers, avoiding some issues with the current copy constructor
    376376interface.
    377 Second is the msg function that returns a C-string with the type's name,
     377Second is the @msg@ function that returns a C-string with the type's name,
    378378including any polymorphic parameters.
    379379
     
    402402
    403403% Discussing multiple frame stack unwinding:
    404 Unwinding across multiple stack frames is more complex because that
     404Unwinding across multiple stack frames is more complex, because that
    405405information is no longer contained within the current function.
    406406With separate compilation,
    407407a function does not know its callers nor their frame layout.
    408408Even using the return address, that information is encoded in terms of
    409 actions in code, intermixed with the actions required finish the function.
     409actions in code, intermixed with the actions required to finish the function.
    410410Without changing the main code path it is impossible to select one of those
    411411two groups of actions at the return site.
    412412
    413 The traditional unwinding mechanism for C is implemented by saving a snap-shot
    414 of a function's state with @setjmp@ and restoring that snap-shot with
     413The traditional unwinding mechanism for C is implemented by saving a snapshot
     414of a function's state with @setjmp@ and restoring that snapshot with
    415415@longjmp@. This approach bypasses the need to know stack details by simply
    416 reseting to a snap-shot of an arbitrary but existing function frame on the
    417 stack. It is up to the programmer to ensure the snap-shot is valid when it is
    418 reset and that all required clean-up from the unwound stacks is performed.
     416reseting to a snapshot of an arbitrary but existing function frame on the
     417stack. It is up to the programmer to ensure the snapshot is valid when it is
     418reset and that all required cleanup from the unwound stacks is performed.
    419419This approach is fragile and requires extra work in the surrounding code.
    420420
    421421With respect to the extra work in the surrounding code,
    422 many languages define clean-up actions that must be taken when certain
    423 sections of the stack are removed. Such as when the storage for a variable
     422many languages define cleanup actions that must be taken when certain
     423sections of the stack are removed, such as when the storage for a variable
    424424is removed from the stack, possibly requiring a destructor call,
    425425or when a try statement with a finally clause is
    426426(conceptually) popped from the stack.
    427 None of these cases should be handled by the user --- that would contradict the
    428 intention of these features --- so they need to be handled automatically.
     427None of these cases should be handled by the user -- that would contradict the
     428intention of these features -- so they need to be handled automatically.
    429429
    430430To safely remove sections of the stack, the language must be able to find and
    431 run these clean-up actions even when removing multiple functions unknown at
     431run these cleanup actions even when removing multiple functions unknown at
    432432the beginning of the unwinding.
    433433
     
    529529provided storage object. It has two public fields: the @exception_class@,
    530530which is described above, and the @exception_cleanup@ function.
    531 The clean-up function is used by the EHM to clean-up the exception, if it
     531The cleanup function is used by the EHM to clean up the exception. If it
    532532should need to be freed at an unusual time, it takes an argument that says
    533533why it had to be cleaned up.
     
    551551of the most recent stack frame. It continues to call personality functions
    552552traversing the stack from newest to oldest until a function finds a handler or
    553 the end of the stack is reached. In the latter case, raise exception returns
    554 @_URC_END_OF_STACK@.
    555 
    556 Second, when a handler is matched, raise exception moves to the clean-up
    557 phase and walks the stack a second time.
     553the end of the stack is reached. In the latter case,
     554@_Unwind_RaiseException@ returns @_URC_END_OF_STACK@.
     555
     556Second, when a handler is matched, @_Unwind_RaiseException@
     557moves to the cleanup phase and walks the stack a second time.
    558558Once again, it calls the personality functions of each stack frame from newest
    559559to oldest. This pass stops at the stack frame containing the matching handler.
    560 If that personality function has not install a handler, it is an error.
    561 
    562 If an error is encountered, raise exception returns either
     560If that personality function has not installed a handler, it is an error.
     561
     562If an error is encountered, @_Unwind_RaiseException@ returns either
    563563@_URC_FATAL_PHASE1_ERROR@ or @_URC_FATAL_PHASE2_ERROR@ depending on when the
    564564error occurred.
     
    571571        _Unwind_Stop_Fn, void *);
    572572\end{cfa}
    573 It also unwinds the stack but it does not use the search phase. Instead another
     573It also unwinds the stack but it does not use the search phase. Instead,
     574another
    574575function, the stop function, is used to stop searching. The exception is the
    575 same as the one passed to raise exception. The extra arguments are the stop
     576same as the one passed to @_Unwind_RaiseException@.
     577The extra arguments are the stop
    576578function and the stop parameter. The stop function has a similar interface as a
    577579personality function, except it is also passed the stop parameter.
     
    721723one list per stack, with the
    722724list head stored in the exception context. Within each linked list, the most
    723 recently thrown exception is at the head followed by older thrown
     725recently thrown exception is at the head, followed by older thrown
    724726exceptions. This format allows exceptions to be thrown, while a different
    725727exception is being handled. The exception at the head of the list is currently
     
    732734exception into managed memory. After the exception is handled, the free
    733735function is used to clean up the exception and then the entire node is
    734 passed to free, returning the memory back to the heap.
     736passed to @free@, returning the memory back to the heap.
    735737
    736738\subsection{Try Statements and Catch Clauses}
     
    757759The three functions passed to try terminate are:
    758760\begin{description}
    759 \item[try function:] This function is the try block, it is where all the code
     761\item[try function:] This function is the try block. It is where all the code
    760762from inside the try block is placed. It takes no parameters and has no
    761763return value. This function is called during regular execution to run the try
     
    766768from the conditional part of each handler and runs each check, top to bottom,
    767769in turn, to see if the exception matches this handler.
    768 The match is performed in two steps, first a virtual cast is used to check
     770The match is performed in two steps: first, a virtual cast is used to check
    769771if the raised exception is an instance of the declared exception type or
    770772one of its descendant types, and then the condition is evaluated, if
    771773present.
    772774The match function takes a pointer to the exception and returns 0 if the
    773 exception is not handled here. Otherwise the return value is the id of the
     775exception is not handled here. Otherwise, the return value is the ID of the
    774776handler that matches the exception.
    775777
     
    782784\end{description}
    783785All three functions are created with GCC nested functions. GCC nested functions
    784 can be used to create closures,
     786can be used to create closures;
    785787in other words,
    786 functions that can refer to variables in their lexical scope even
     788functions that can refer to variables in their lexical scope even though
    787789those variables are part of a different function.
    788790This approach allows the functions to refer to all the
     
    869871At each node, the EHM checks to see if the try statement the node represents
    870872can handle the exception. If it can, then the exception is handled and
    871 the operation finishes, otherwise the search continues to the next node.
     873the operation finishes; otherwise, the search continues to the next node.
    872874If the search reaches the end of the list without finding a try statement
    873875with a handler clause
     
    879881if the exception is handled and false otherwise.
    880882The handler function checks each of its internal handlers in order,
    881 top-to-bottom, until it funds a match. If a match is found that handler is
     883top-to-bottom, until it finds a match. If a match is found that handler is
    882884run, after which the function returns true, ignoring all remaining handlers.
    883885If no match is found the function returns false.
    884 The match is performed in two steps, first a virtual cast is used to see
     886The match is performed in two steps. First a virtual cast is used to see
    885887if the raised exception is an instance of the declared exception type or one
    886 of its descendant types, if so then it is passed to the custom predicate
     888of its descendant types, if so, then the second step is to see if the
     889exception passes the custom predicate
    887890if one is defined.
    888891% You need to make sure the type is correct before running the predicate
     
    936939% Recursive Resumption Stuff:
    937940\autoref{f:ResumptionMarking} shows search skipping
    938 (see \vpageref{s:ResumptionMarking}), which ignores parts of
     941(see \autoref{s:ResumptionMarking}), which ignores parts of
    939942the stack
    940943already examined, and is accomplished by updating the front of the list as
     
    951954This structure also supports new handlers added while the resumption is being
    952955handled. These are added to the front of the list, pointing back along the
    953 stack --- the first one points over all the checked handlers ---
     956stack -- the first one points over all the checked handlers --
    954957and the ordering is maintained.
    955958
     
    979982%\autoref{code:cleanup}
    980983A finally clause is handled by converting it into a once-off destructor.
    981 The code inside the clause is placed into GCC nested-function
     984The code inside the clause is placed into a GCC nested-function
    982985with a unique name, and no arguments or return values.
    983986This nested function is
    984987then set as the cleanup function of an empty object that is declared at the
    985988beginning of a block placed around the context of the associated try
    986 statement (see \autoref{f:FinallyTransformation}).
     989statement, as shown in \autoref{f:FinallyTransformation}.
    987990
    988991\begin{figure}
     
    10241027% Stack selections, the three internal unwind functions.
    10251028
    1026 Cancellation also uses libunwind to do its stack traversal and unwinding,
    1027 however it uses a different primary function: @_Unwind_ForcedUnwind@. Details
    1028 of its interface can be found in the Section~\vref{s:ForcedUnwind}.
     1029Cancellation also uses libunwind to do its stack traversal and unwinding.
     1030However, it uses a different primary function: @_Unwind_ForcedUnwind@. Details
     1031of its interface can be found in Section~\vref{s:ForcedUnwind}.
    10291032
    10301033The first step of cancellation is to find the cancelled stack and its type:
  • doc/theses/andrew_beach_MMath/intro.tex

    rd0b9247 r9cdfa5fb  
    2525All types of exception handling link a raise with a handler.
    2626Both operations are usually language primitives, although raises can be
    27 treated as a primitive function that takes an exception argument.
    28 Handlers are more complex as they are added to and removed from the stack
    29 during execution, must specify what they can handle and give the code to
     27treated as a function that takes an exception argument.
     28Handlers are more complex, as they are added to and removed from the stack
     29during execution, must specify what they can handle and must give the code to
    3030handle the exception.
    3131
     
    4141\input{termination}
    4242\end{center}
     43%\todo{What does the right half of termination.fig mean?}
    4344
    4445Resumption exception handling searches the stack for a handler and then calls
     
    4647The handler is run on top of the existing stack, often as a new function or
    4748closure capturing the context in which the handler was defined.
    48 After the handler has finished running it returns control to the function
     49After the handler has finished running, it returns control to the function
    4950that preformed the raise, usually starting after the raise.
    5051\begin{center}
     
    5354
    5455Although a powerful feature, exception handling tends to be complex to set up
    55 and expensive to use
     56and expensive to use,
    5657so it is often limited to unusual or ``exceptional" cases.
    57 The classic example is error handling, exceptions can be used to
     58The classic example is error handling; exceptions can be used to
    5859remove error handling logic from the main execution path, and pay
    5960most of the cost only when the error actually occurs.
     
    6364The \CFA EHM implements all of the common exception features (or an
    6465equivalent) found in most other EHMs and adds some features of its own.
    65 The design of all the features had to be adapted to \CFA's feature set as
     66The design of all the features had to be adapted to \CFA's feature set, as
    6667some of the underlying tools used to implement and express exception handling
    6768in other languages are absent in \CFA.
    68 Still the resulting syntax resembles that of other languages:
     69Still, the resulting syntax resembles that of other languages:
    6970\begin{cfa}
    7071try {
     
    8889covering both changes to the compiler and the run-time.
    8990In addition, a suite of test cases and performance benchmarks were created
    90 along side the implementation.
     91alongside the implementation.
    9192The implementation techniques are generally applicable in other programming
    9293languages and much of the design is as well.
     
    100101\item Implementing stack unwinding and the \CFA EHM, including updating
    101102the \CFA compiler and the run-time environment.
    102 \item Designed and implemented a prototype virtual system.
     103\item Designing and implementing a prototype virtual system.
    103104% I think the virtual system and per-call site default handlers are the only
    104105% "new" features, everything else is a matter of implementation.
    105106\item Creating tests to check the behaviour of the EHM.
    106 \item Creating benchmarks to check the performances of the EHM,
     107\item Creating benchmarks to check the performance of the EHM,
    107108as compared to other languages.
    108109\end{enumerate}
     
    110111The rest of this thesis is organized as follows.
    111112The current state of exceptions is covered in \autoref{s:background}.
    112 The existing state of \CFA is also covered in \autoref{c:existing}.
     113The existing state of \CFA is covered in \autoref{c:existing}.
    113114New EHM features are introduced in \autoref{c:features},
    114115covering their usage and design.
     
    137138inheriting from
    138139\code{C++}{std::exception}.
    139 Although there is a special catch-all syntax (@catch(...)@) there are no
     140Although there is a special catch-all syntax (@catch(...)@), there are no
    140141operations that can be performed on the caught value, not even type inspection.
    141 Instead the base exception-type \code{C++}{std::exception} defines common
     142Instead, the base exception-type \code{C++}{std::exception} defines common
    142143functionality (such as
    143144the ability to describe the reason the exception was raised) and all
     
    148149
    149150Java was the next popular language to use exceptions.\cite{Java8}
    150 Its exception system largely reflects that of \Cpp, except that requires
     151Its exception system largely reflects that of \Cpp, except that it requires
    151152you throw a child type of \code{Java}{java.lang.Throwable}
    152153and it uses checked exceptions.
    153154Checked exceptions are part of a function's interface,
    154155the exception signature of the function.
    155 Every function that could be raised from a function, either directly or
     156Every exception that could be raised from a function, either directly or
    156157because it is not handled from a called function, is given.
    157158Using this information, it is possible to statically verify if any given
    158 exception is handled and guarantee that no exception will go unhandled.
     159exception is handled, and guarantee that no exception will go unhandled.
    159160Making exception information explicit improves clarity and safety,
    160161but can slow down or restrict programming.
     
    169170recovery or repair. In theory that could be good enough to properly handle
    170171the exception, but more often is used to ignore an exception that the       
    171 programmer does not feel is worth the effort of handling it, for instance if
     172programmer does not feel is worth the effort of handling, for instance if
    172173they do not believe it will ever be raised.
    173 If they are incorrect the exception will be silenced, while in a similar
     174If they are incorrect, the exception will be silenced, while in a similar
    174175situation with unchecked exceptions the exception would at least activate   
    175 the language's unhandled exception code (usually program abort with an 
     176the language's unhandled exception code (usually, a program abort with an
    176177error message).
    177178
    178179%\subsection
    179180Resumption exceptions are less popular,
    180 although resumption is as old as termination; hence, few
     181although resumption is as old as termination; that is, few
    181182programming languages have implemented them.
    182183% http://bitsavers.informatik.uni-stuttgart.de/pdf/xerox/parc/techReports/
     
    186187included in the \Cpp standard.
    187188% https://en.wikipedia.org/wiki/Exception_handling
    188 Since then resumptions have been ignored in main-stream programming languages.
     189Since then, resumptions have been ignored in main-stream programming languages.
    189190However, resumption is being revisited in the context of decades of other
    190191developments in programming languages.
    191192While rejecting resumption may have been the right decision in the past,
    192193the situation has changed since then.
    193 Some developments, such as the function programming equivalent to resumptions,
     194Some developments, such as the functional programming equivalent to resumptions,
    194195algebraic effects\cite{Zhang19}, are enjoying success.
    195 A complete reexamination of resumptions is beyond this thesis,
    196 but there reemergence is enough to try them in \CFA.
     196A complete reexamination of resumption is beyond this thesis,
     197but their reemergence is enough reason to try them in \CFA.
    197198% Especially considering how much easier they are to implement than
    198199% termination exceptions and how much Peter likes them.
     
    208209
    209210%\subsection
    210 More recently exceptions seem to be vanishing from newer programming
     211More recently exceptions, seem to be vanishing from newer programming
    211212languages, replaced by ``panic".
    212213In Rust, a panic is just a program level abort that may be implemented by
     
    218219
    219220%\subsection
    220 While exception handling's most common use cases are in error handling,
     221As exception handling's most common use cases are in error handling,
    221222here are some other ways to handle errors with comparisons with exceptions.
    222223\begin{itemize}
     
    233234is discarded to avoid this problem.
    234235Checking error codes also bloats the main execution path,
    235 especially if the error is not handled immediately hand has to be passed
     236especially if the error is not handled immediately and has to be passed
    236237through multiple functions before it is addressed.
    237238
    238239\item\emph{Special Return with Global Store}:
    239240Similar to the error codes pattern but the function itself only returns
    240 that there was an error
    241 and store the reason for the error in a fixed global location.
    242 For example many routines in the C standard library will only return some
     241that there was an error,
     242and stores the reason for the error in a fixed global location.
     243For example, many routines in the C standard library will only return some
    243244error value (such as -1 or a null pointer) and the error code is written into
    244245the standard variable @errno@.
     
    253254Success is one tag and the errors are another.
    254255It is also possible to make each possible error its own tag and carry its own
    255 additional information, but the two branch format is easy to make generic
     256additional information, but the two-branch format is easy to make generic
    256257so that one type can be used everywhere in error handling code.
    257258
     
    261262% Rust's \code{rust}{Result<T, E>}
    262263The main advantage is that an arbitrary object can be used to represent an
    263 error so it can include a lot more information than a simple error code.
     264error, so it can include a lot more information than a simple error code.
    264265The disadvantages include that the it does have to be checked along the main
    265 execution and if there aren't primitive tagged unions proper usage can be
     266execution, and if there aren't primitive tagged unions proper, usage can be
    266267hard to enforce.
    267268
     
    274275variable).
    275276C++ uses this approach as its fallback system if exception handling fails,
    276 such as \snake{std::terminate_handler} and, for a time,
    277 \snake{std::unexpected_handler}.
     277such as \snake{std::terminate} and, for a time,
     278\snake{std::unexpected}.\footnote{\snake{std::unexpected} was part of the
     279Dynamic Exception Specification, which has been removed from the standard
     280as of C++20.\cite{CppExceptSpec}}
    278281
    279282Handler functions work a lot like resumption exceptions,
     
    291294happily making them expensive to use in exchange.
    292295This difference is less important in higher-level scripting languages,
    293 where using exception for other tasks is more common.
     296where using exceptions for other tasks is more common.
    294297An iconic example is Python's
    295 \code{Python}{StopIteration}\cite{PythonExceptions} exception that
     298\code{Python}{StopIteration}\cite{PythonExceptions} exception, that
    296299is thrown by an iterator to indicate that it is exhausted.
    297 When paired with Python's iterator-based for-loop this will be thrown every
     300When paired with Python's iterator-based for-loop, this will be thrown every
    298301time the end of the loop is reached.\cite{PythonForLoop}
  • doc/theses/andrew_beach_MMath/performance.tex

    rd0b9247 r9cdfa5fb  
    55Instead, the focus was to get the features working. The only performance
    66requirement is to ensure the tests for correctness run in a reasonable
    7 amount of time. Hence, a few basic performance tests were performed to
     7amount of time. Hence, only a few basic performance tests were performed to
    88check this requirement.
    99
     
    1313one with termination and one with resumption.
    1414
    15 C++ is the most comparable language because both it and \CFA use the same
     15GCC C++ is the most comparable language because both it and \CFA use the same
    1616framework, libunwind.
    1717In fact, the comparison is almost entirely in quality of implementation.
     
    4646the number used in the timing runs is given with the results per test.
    4747The Java tests run the main loop 1000 times before
    48 beginning the actual test to ``warm-up" the JVM.
     48beginning the actual test to ``warm up" the JVM.
    4949% All other languages are precompiled or interpreted.
    5050
     
    5454unhandled exceptions in \Cpp and Java as that would cause the process to
    5555terminate.
    56 Luckily, performance on the ``give-up and kill the process" path is not
     56Luckily, performance on the ``give up and kill the process" path is not
    5757critical.
    5858
     
    7676using gcc-10 10.3.0 as a backend.
    7777g++-10 10.3.0 is used for \Cpp.
    78 Java tests are complied and run with version 11.0.11.
    79 Python used version 3.8.10.
     78Java tests are complied and run with Oracle OpenJDK version 11.0.11.
     79Python used CPython version 3.8.10.
    8080The machines used to run the tests are:
    8181\begin{itemize}[nosep]
     
    8585      \lstinline{@} 2.5 GHz running Linux v5.11.0-25
    8686\end{itemize}
    87 Representing the two major families of hardware architecture.
     87These represent the two major families of hardware architecture.
    8888
    8989\section{Tests}
     
    9393
    9494\paragraph{Stack Traversal}
    95 This group measures the cost of traversing the stack,
     95This group of tests measures the cost of traversing the stack
    9696(and in termination, unwinding it).
    9797Inside the main loop is a call to a recursive function.
     
    147147This group of tests measures the cost for setting up exception handling,
    148148if it is
    149 not used (because the exceptional case did not occur).
     149not used because the exceptional case did not occur.
    150150Tests repeatedly cross (enter, execute and leave) a try statement but never
    151151perform a raise.
     
    222222for that language and the result is marked N/A.
    223223There are also cases where the feature is supported but measuring its
    224 cost is impossible. This happened with Java, which uses a JIT that optimize
    225 away the tests and it cannot be stopped.\cite{Dice21}
     224cost is impossible. This happened with Java, which uses a JIT that optimizes
     225away the tests and cannot be stopped.\cite{Dice21}
    226226These tests are marked N/C.
    227227To get results in a consistent range (1 second to 1 minute is ideal,
     
    230230results and has a value in the millions.
    231231
    232 An anomaly in some results came from \CFA's use of gcc nested functions.
     232An anomaly in some results came from \CFA's use of GCC nested functions.
    233233These nested functions are used to create closures that can access stack
    234234variables in their lexical scope.
    235 However, if they do so, then they can cause the benchmark's run-time to
     235However, if they do so, then they can cause the benchmark's run time to
    236236increase by an order of magnitude.
    237237The simplest solution is to make those values global variables instead
    238 of function local variables.
     238of function-local variables.
    239239% Do we know if editing a global inside nested function is a problem?
    240240Tests that had to be modified to avoid this problem have been marked
     
    312312\CFA, \Cpp and Java.
    313313% To be exact, the Match All and Match None cases.
     314%\todo{Not true in Python.}
    314315The most likely explanation is that, since exceptions
    315316are rarely considered to be the common case, the more optimized languages
     
    346347Performance is similar to Empty Traversal in all languages that support finally
    347348clauses. Only Python seems to have a larger than random noise change in
    348 its run-time and it is still not large.
     349its run time and it is still not large.
    349350Despite the similarity between finally clauses and destructors,
    350 finally clauses seem to avoid the spike that run-time destructors have.
     351finally clauses seem to avoid the spike that run time destructors have.
    351352Possibly some optimization removes the cost of changing contexts.
    352353
     
    356357This results in a significant jump.
    357358
    358 Other languages experience a small increase in run-time.
     359Other languages experience a small increase in run time.
    359360The small increase likely comes from running the checks,
    360361but they could avoid the spike by not having the same kind of overhead for
     
    362363
    363364\item[Cross Handler]
    364 Here \CFA falls behind \Cpp by a much more significant margin.
    365 This is likely due to the fact \CFA has to insert two extra function
    366 calls, while \Cpp does not have to do execute any other instructions.
     365Here, \CFA falls behind \Cpp by a much more significant margin.
     366This is likely due to the fact that \CFA has to insert two extra function
     367calls, while \Cpp does not have to execute any other instructions.
    367368Python is much further behind.
    368369
     
    375376\item[Conditional Match]
    376377Both of the conditional matching tests can be considered on their own.
    377 However for evaluating the value of conditional matching itself, the
     378However, for evaluating the value of conditional matching itself, the
    378379comparison of the two sets of results is useful.
    379 Consider the massive jump in run-time for \Cpp going from match all to match
     380Consider the massive jump in run time for \Cpp going from match all to match
    380381none, which none of the other languages have.
    381 Some strange interaction is causing run-time to more than double for doing
     382Some strange interaction is causing run time to more than double for doing
    382383twice as many raises.
    383 Java and Python avoid this problem and have similar run-time for both tests,
     384Java and Python avoid this problem and have similar run time for both tests,
    384385possibly through resource reuse or their program representation.
    385 However \CFA is built like \Cpp and avoids the problem as well, this matches
     386However, \CFA is built like \Cpp, and avoids the problem as well.
     387This matches
    386388the pattern of the conditional match, which makes the two execution paths
    387389very similar.
     
    391393\subsection{Resumption \texorpdfstring{(\autoref{t:PerformanceResumption})}{}}
    392394
    393 Moving on to resumption, there is one general note,
     395Moving on to resumption, there is one general note:
    394396resumption is \textit{fast}. The only test where it fell
    395397behind termination is Cross Handler.
    396398In every other case, the number of iterations had to be increased by a
    397 factor of 10 to get the run-time in an appropriate range
     399factor of 10 to get the run time in an appropriate range
    398400and in some cases resumption still took less time.
    399401
     
    408410
    409411\item[D'tor Traversal]
    410 Resumption does have the same spike in run-time that termination has.
    411 The run-time is actually very similar to Finally Traversal.
     412Resumption does have the same spike in run time that termination has.
     413The run time is actually very similar to Finally Traversal.
    412414As resumption does not unwind the stack, both destructors and finally
    413415clauses are run while walking down the stack during the recursive returns.
     
    416418\item[Finally Traversal]
    417419Same as D'tor Traversal,
    418 except termination did not have a spike in run-time on this test case.
     420except termination did not have a spike in run time on this test case.
    419421
    420422\item[Other Traversal]
     
    427429The only test case where resumption could not keep up with termination,
    428430although the difference is not as significant as many other cases.
    429 It is simply a matter of where the costs come from,
    430 both termination and resumption have some work to set-up or tear-down a
     431It is simply a matter of where the costs come from:
     432both termination and resumption have some work to set up or tear down a
    431433handler. It just so happens that resumption's work is slightly slower.
    432434
     
    434436Resumption shows a slight slowdown if the exception is not matched
    435437by the first handler, which follows from the fact the second handler now has
    436 to be checked. However the difference is not large.
     438to be checked. However, the difference is not large.
    437439
    438440\end{description}
     
    448450More experiments could try to tease out the exact trade-offs,
    449451but the prototype's only performance goal is to be reasonable.
    450 It has already in that range, and \CFA's fixup routine simulation is
     452It is already in that range, and \CFA's fixup routine simulation is
    451453one of the faster simulations as well.
    452 Plus exceptions add features and remove syntactic overhead,
    453 so even at similar performance resumptions have advantages
     454Plus, exceptions add features and remove syntactic overhead,
     455so even at similar performance, resumptions have advantages
    454456over fixup routines.
  • doc/theses/andrew_beach_MMath/uw-ethesis-frontpgs.tex

    rd0b9247 r9cdfa5fb  
    137137This thesis covers the design and implementation of the \CFA EHM,
    138138along with a review of the other required \CFA features.
    139 The EHM includes common features of termination exception handling and
    140 similar support for resumption exception handling.
     139The EHM includes common features of termination exception handling,
     140which abandons and recovers from an operation,
     141and similar support for resumption exception handling,
     142which repairs and continues with an operation.
    141143The design of both has been adapted to utilize other tools \CFA provides,
    142144as well as fit with the assertion based interfaces of the language.
     
    144146The EHM has been implemented into the \CFA compiler and run-time environment.
    145147Although it has not yet been optimized, performance testing has shown it has
    146 comparable performance to other EHM's,
     148comparable performance to other EHMs,
    147149which is sufficient for use in current \CFA programs.
    148150
  • doc/theses/andrew_beach_MMath/uw-ethesis.bib

    rd0b9247 r9cdfa5fb  
    4040}
    4141
     42@misc{CppExceptSpec,
     43    author={C++ Community},
     44    key={Cpp Reference Exception Specification},
     45    howpublished={\href{https://en.cppreference.com/w/cpp/language/except_spec}{https://\-en.cppreference.com/\-w/\-cpp/\-language/\-except\_spec}},
     46    addendum={Accessed 2021-09-08},
     47}
     48
    4249@misc{RustPanicMacro,
    4350    author={The Rust Team},
Note: See TracChangeset for help on using the changeset viewer.