# Changeset 73d0c54

Ignore:
Timestamp:
Apr 21, 2021, 3:39:14 PM (5 months ago)
Branches:
arm-eh, jacob/cs343-translation, master, new-ast-unique-expr
Children:
b39e6566
Parents:
665edf40 (diff), 7711064 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Files:
4 deleted
18 edited
2 moved

### Legend:

Unmodified
Removed

 r665edf40 #include class __attribute__((aligned(128))) bench_sem { Fibre * volatile ptr = nullptr; public: inline bool wait() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { /* paranoid */ assert( expected == nullptr ); if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_park(); return true; } } } } inline bool post() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) return false; if(expected == nullptr) { if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_unpark( expected ); return true; } } } } }; struct Partner { unsigned long long count  = 0;

 r665edf40 uint64_t dmigs = 0; uint64_t gmigs = 0; }; class __attribute__((aligned(128))) bench_sem { Fibre * volatile ptr = nullptr; public: inline bool wait() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { /* paranoid */ assert( expected == nullptr ); if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_park(); return true; } } } } inline bool post() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) return false; if(expected == nullptr) { if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_unpark( expected ); return true; } } } } };

 r665edf40 #include #include #include #include #include (*p){ "Benchmark Processor", this.cl }; } #if !defined(__CFA_NO_STATISTICS__) print_stats_at_exit( this.cl, CFA_STATS_READY_Q ); #endif }

 r665edf40 #include                                                                                // timespec #include                                                                    // timeval typedef __uint128_t __lehmer64_state_t; static inline uint64_t __lehmer64( __lehmer64_state_t & state ) { state *= 0xda942042e4dd58b5; return state >> 64; } enum { TIMEGRAN = 1000000000LL };                                       // nanosecond granularity, except for timeval } class Fibre; int fibre_park(); int fibre_unpark( Fibre * ); Fibre * fibre_self(); class __attribute__((aligned(128))) bench_sem { Fibre * volatile ptr = nullptr; public: inline bool wait() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { /* paranoid */ assert( expected == nullptr ); if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_park(); return true; } } } } inline bool post() { static Fibre * const ready  = reinterpret_cast(1ull); for(;;) { Fibre * expected = this->ptr; if(expected == ready) return false; if(expected == nullptr) { if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { return false; } } else { if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { fibre_unpark( expected ); return true; } } } } }; // ========================================================================================== #include this->help       = help; this->variable   = reinterpret_cast(&variable); this->parse_fun  = reinterpret_cast(static_cast(parse)); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" this->parse_fun  = reinterpret_cast(static_cast(parse)); #pragma GCC diagnostic pop } this->help       = help; this->variable   = reinterpret_cast(&variable); this->parse_fun  = reinterpret_cast(parse); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" this->parse_fun  = reinterpret_cast(parse); #pragma GCC diagnostic pop } };
• ## doc/theses/andrew_beach_MMath/Makefile

 r665edf40 ### Makefile for Andrew Beach's Masters Thesis DOC = uw-ethesis.pdf BASE = ${DOC:%.pdf=%} # remove suffix # directory for latex clutter files BUILD = build TEXSRC =$(wildcard *.tex) FIGSRC = $(wildcard *.fig) BIBSRC =$(wildcard *.bib) STYSRC = $(wildcard *.sty) CLSSRC =$(wildcard *.cls) TEXLIB = .:../../LaTeXmacros:${BUILD}: # common latex macros BIBLIB = .:../../bibliography # common citation repository DOC=uw-ethesis.pdf BUILD=out TEXSRC=$(wildcard *.tex) FIGSRC=$(wildcard *.fig) BIBSRC=$(wildcard *.bib) STYSRC=$(wildcard *.sty) CLSSRC=$(wildcard *.cls) TEXLIB= .:../../LaTeXmacros:${BUILD}: BIBLIB= .:../../bibliography MAKEFLAGS = --no-print-directory # --silent VPATH =${BUILD} # Since tex programs like to add their own file extensions: BASE= ${DOC:%.pdf=%} RAWSRC=${TEXSRC} ${BIBSRC}${STYSRC} ${CLSSRC} FIGTEX=${FIGSRC:%.fig=${BUILD}/%.tex} ### Special Rules: .PHONY: all clean deepclean .PRECIOUS: %.dvi %.ps # do not delete intermediate files ### Commands: LATEX = TEXINPUTS=${TEXLIB} && export TEXINPUTS && latex -halt-on-error -output-directory=${BUILD} BIBTEX = BIBINPUTS=${BIBLIB} bibtex GLOSSARY = INDEXSTYLE=${BUILD} makeglossaries-lite LATEX=TEXINPUTS=${TEXLIB} latex -halt-on-error -output-directory=${BUILD} BIBTEX=BIBINPUTS=${BIBLIB} bibtex GLOSSARY=INDEXSTYLE=${BUILD} makeglossaries-lite ### Rules and Recipes: ### Rules and Recipies: all:${DOC} ${BUILD}/%.dvi:${TEXSRC} ${FIGSRC:.fig=.tex}${BIBSRC} ${STYSRC}${CLSSRC} Makefile | ${BUILD} # The main rule, it does all the tex/latex processing.${BUILD}/${BASE}.dvi:${RAWSRC} ${FIGTEX} Makefile |${BUILD} ${LATEX}${BASE} ${BIBTEX}${BUILD}/${BASE}${LATEX} ${BASE} # Convert xfig output to tex. (Generates \special declarations.)${FIGTEX}: ${BUILD}/%.tex: %.fig |${BUILD} fig2dev -L eepic $< >$@ # Step through dvi & postscript to handle xfig specials. %.pdf : ${BUILD}/%.dvi dvipdf$^ $@${BUILD}: mkdir $@ %.pdf :${BUILD}/%.ps | ${BUILD} ps2pdf$< %.ps : %.dvi | ${BUILD} dvips$< -o $@ %.tex : %.fig |${BUILD} fig2dev -L eepic $< >${BUILD}/$@ %.ps : %.fig |${BUILD} fig2dev -L ps $< >${BUILD}/$@ %.pstex : %.fig |${BUILD} fig2dev -L pstex $< >${BUILD}/$@ fig2dev -L pstex_t -p${BUILD}/$@$< > ${BUILD}/$@_t clean: @rm -frv ${BUILD} *.fig.bak -@rm -rv${BUILD} deepclean: clean -@rm -fv ${DOC} -@rm -v${DOC}
• ## doc/theses/andrew_beach_MMath/features.tex

 r665edf40 This chapter covers the design and user interface of the \CFA exception-handling mechanism (EHM). % or exception system. While an EHM is free to add many features, the following overview covers the basic features that all EHMs use, but it is not an exhaustive list of everything an EHM can do. We will begin with an overview of EHMs in general. It is not a strict definition of all EHMs nor an exaustive list of all possible features. However it does cover the most common structure and features found in them. % We should cover what is an exception handling mechanism and what is an These terms are sometimes also known as throw and catch but this work uses throw/catch as a particular kind of raise/handle. These are the two parts a programmer writes and so are the only two pieces of the EHM that have language syntax. These are the two parts that the user will write themselves and may be the only two pieces of the EHM that have any syntax in the language. \subparagraph{Raise} The raise is the starting point for exception handling and usually how \PAB{This sentence is cut off.} Some well known examples include the @throw@ statement of \Cpp and Java and the \lstinline[language=Python]{raise} statement from Python. For this overview, a raise starts the handling of an exception, which is called \newterm{raising} an exception. This simple description is sufficient for the overview. The raise is the starting point for exception handling. It marks the beginning of exception handling by \newterm{raising} an excepion, which passes it to the EHM. Some well known examples include the @throw@ statements of \Cpp and Java and the \codePy{raise} statement from Python. In real systems a raise may preform some other work (such as memory management) but for the purposes of this overview that can be ignored. \subparagraph{Handle} The purpose of raising an exception is to run user code to address (handle) the issue found at the raise point. The @try@ statement of \Cpp illustrates a common approach for specifying multiple handlers. A handler has three common features: the scope in which it applies, an exception label that describes what exceptions it can handle, and code to run that deals with the raised issue. Each handler can handle exceptions raised in the region matching its exception label. For multiple matches, different EHMs have different rules for matching an exception to a handler label, such as best match" or first found". The purpose of most exception operations is to run some user code to handle that exception. This code is given, with some other information, in a handler. A handler has three common features: the previously mentioned user code, a region of code they cover and an exception label/condition that matches certain exceptions. Only raises inside the covered region and raising exceptions that match the label can be handled by a given handler. Different EHMs will have different rules to pick a handler if multipe handlers could be used such as best match" or first found". The @try@ statements of \Cpp, Java and Python are common examples. All three also show another common feature of handlers, they are grouped by the covered region. \paragraph{Propagation} After an exception is raised, comes the most complex step for the EHM: finding and setting up the handler. This propagation of exception from raise to handler can be broken up into three different tasks: searching, matching, and installing the handler so it can execute. After an exception is raised comes what is usually the biggest step for the EHM: finding and setting up the handler. The propogation from raise to handler can be broken up into three different tasks: searching for a handler, matching against the handler and installing the handler. \subparagraph{Searching} The EHM searches for possible handlers that can be used to handle the exception. Searching is usually independent of the exception that is thrown and instead depends on the call stack: current function, its caller and repeating down the stack. The EHM begins by searching for handlers that might be used to handle the exception. Searching is usually independent of the exception that was thrown as it looks for handlers that have the raise site in their covered region. This includes handlers in the current function, as well as any in callers on the stack that have the function call in their covered region. \subparagraph{Matching} For each handler found, it compares the raised exception with the handler label to see which one is the best match, and hence, which one should be used to handle the exception. In languages where the best match is the first match, these two steps are often intertwined, \ie a match check is performed immediately after the search finds Each handler found has to be matched with the raised exception. The exception label defines a condition that be use used with exception and decides if there is a match or not. In languages where the first match is used this step is intertwined with searching, a match check is preformed immediately after the search finds a possible handler. \subparagraph{Installing} After a handler is chosen, it must be made ready to run. This step varies widely to fit with the rest of the design of the EHM. The installation step might be trivial or it can be After a handler is chosen it must be made ready to run. The implementation can vary widely to fit with the rest of the design of the EHM. The installation step might be trivial or it could be the most expensive step in handling an exception. The latter tends to be the case when stack unwinding is involved. An alternate action occurs if no appropriate handler is found, then some implicit action is performed. This step is only required with unchecked exceptions as checked exceptions (Java) promise a handler is always found. The implicit action also installs a handler but it is a default handle that may be installed differently. If a matching handler is not guarantied to be found the EHM will need a different course of action here in the cases where no handler matches. This is only required with unchecked exceptions as checked exceptions (such as in Java) can make than guaranty. This different action can also be installing a handler but it is usually an implicat and much more general one. \subparagraph{Hierarchy} Some EHM (\CFA, Java) organize exceptions in a hierarchical structure. This strategy is borrowed from object-orientated languages where the A common way to organize exceptions is in a hierarchical structure. This is especially true in object-orientated languages where the exception hierarchy is a natural extension of the object hierarchy. Consider the following hierarchy of exceptions: \begin{center} \input{exceptionHierarchy} \input{exception-hierarchy} \end{center} A handler labelled with any given exception can handle exceptions of that type or any child type of that exception. The root of the exception hierarchy (here \lstinline[language=C++]{exception}) acts as a catch-all, leaf types catch single types (here \codeC{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 between different sub-hierarchies. This capability had to be adapted for \CFA, which is a non-object-orientated language. 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 language using different tools to create the hierarchy. % Could I cite the rational for the Python IO exception rework? \paragraph{Completion} After the handler has returned, the entire exception operation has to complete and continue executing somewhere. This step is usually simple, After the handler has finished the entire exception operation has to complete and continue executing somewhere else. This step is usually simple, both logically and in its implementation, as the installation of the handler usually does the preparation. The EHM can return control to different places, where the most common are after the handler definition or after the raise. is usually set up to do most of the work. The EHM can return control to many different places, the most common are after the handler definition and after the raise. \paragraph{Communication} For effective exception handling, additional information is usually passed from the raise, where this basic model only communicates the exception's identity. A common methods for communication is putting fields into an exception and allowing a handler to access these fields via an exception instance in the handler's scope. For effective exception handling, additional information is usually passed from the raise to the handler. So far only communication of the exceptions' identity has been covered. A common method is putting fields into the exception instance and giving the handler access to them. \section{Virtuals} Virtual types and casts are not part of an EHM nor are they required for an EHM. But as pointed out, an object-oriented-style hierarchy is an excellent way of organizing exceptions. Hence, a minimal virtual system has been added to \CFA to support hierarchical exceptions. Virtual types and casts are not part of \CFA's EHM nor are they required for any EHM. But \CFA uses a hierarchial system of exceptions and this feature is leveraged to create that. % Maybe talk about why the virtual system is so minimal. % Created for but not a part of the exception system. The virtual system supports multiple trees" of types. Each tree is a simple hierarchy with a single root type. Each type in a tree has exactly one parent -- except for the root type with zero parents -- and any one parent -- except for the root type which has zero parents -- and any number of children. Any type that belongs to any of these trees is called a virtual type. % A type's ancestors are its parent and its parent's ancestors. % The root type has no ancestors. % A type's descendents are its children and its children's descendents. Every virtual type has a list of virtual members. Children inherit their parent's virtual members but may add new members to it. It is important to note that these are virtual members, not virtual methods of an object type. However, as \CFA has function pointers, they can be used to mimic virtual methods. % A type's decendents are its children and its children's decendents. Every virtual type also has a list of virtual members. Children inherit their parent's list of virtual members but may add new members to it. It is important to note that these are virtual members, not virtual methods of object-orientated programming, and can be of any type. However, since \CFA has function pointers and they are allowed, virtual members can be used to mimic virtual methods. Each virtual type has a unique id. The unique id for the virtual type and all its virtual members are combined into a virtual-table type. Each virtual type has a pointer to a virtual table This unique id and all the virtual members are combined into a virtual table type. Each virtual type has a pointer to a virtual table as a hidden field. Up to this point, a virtual system is similar to ones found in object-oriented languages but this is where \CFA diverges. Objects encapsulate a Up until this point the virtual system is similar to ones found in object-orientated languages but this where \CFA diverges. Objects encapsulate a single set of behaviours in each type, universally across the entire program, and indeed all programs that use that type definition. In this sense, the and indeed all programs that use that type definition. In this sense the types are closed" and cannot be altered. However, \CFA types do not encapsulate any behaviour. Instead, traits are used and types can satisfy a trait, stop satisfying a trait, or satisfy the same trait in a different way depending on the lexical context. In this sense, the types are open" as their behaviour can change in different scopes. This capability means it is impossible to pick a single set of functions that represent the type's virtual members. Hence, \CFA does not have a single virtual table for a type. A user can define different virtual tables, which are filled in at their declaration and given a name. That name is used as the virtual table, even if it is defined locally inside a function, although lifetime issues must be considered. Specifically, an object of a virtual type is bound" to a virtual table instance, which In \CFA types do not encapsulate any behaviour. Traits are local and types can begin to statify a trait, stop satifying a trait or satify the same trait in a different way at any lexical location in the program. In this sense they are open" as they can change at any time. This means it is implossible to pick a single set of functions that repersent the type's implementation across the program. \CFA side-steps this issue by not having a single virtual table for each type. A user can define virtual tables which are filled in at their declaration and given a name. Anywhere that name is visible, even if it was defined locally inside a function (although that means it will not have a static lifetime), it can be used. Specifically, a virtual type is bound" to a virtual table which sets the virtual members for that object. The virtual members can be accessed through the object. \Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be a pointer to a virtual type. The cast dynamically checks if the @EXPRESSION@ type is the same or a subtype The cast dynamically checks if the @EXPRESSION@ type is the same or a sub-type of @TYPE@, and if true, returns a pointer to the @EXPRESSION@ object, otherwise it returns @0p@ (null pointer). \end{cfa} The trait is defined over two types, the exception type and the virtual table type. These type should have a one-to-one relationship: each exception type has only one virtual type. This should be one-to-one: each exception type has only one virtual table type and vice versa. The only assertion in the trait is @get_exception_vtable@, which takes a pointer of the exception type and returns a reference to the virtual-table type-instance. returns a reference to the virtual table type instance. % TODO: This section, and all references to get_exception_vtable, are % out-of-data. Perhaps wait until the update is finished before rewriting it. The function @get_exception_vtable@ is actually a constant function. Regardless of the value passed in (including the null pointer) it returns a reference to the virtual-table instance for that type. The reason it is a function instead of a constant is to make type annotations easier to write using the exception type rather than the virtual-table type, which usually has a mangled name because it is an internal component of the EHM. Regardless of the value passed in (including the null pointer) it should return a reference to the virtual table instance for that type. The reason it is a function instead of a constant is that it make type annotations easier to write as you can use the exception type instead of the virtual table type; which usually has a mangled name. % Also \CFA's trait system handles functions better than constants and doing % it this way reduce the amount of boiler plate we need. % I did have a note about how it is the programmer's responsibility to make % sure the function is implemented correctly. But this is true of every % similar system I know of (except Ada's I guess) so I took it out. There are two more exception traits defined as follows: % similar system I know of (except Agda's I guess) so I took it out. There are two more traits for exceptions defined as follows: \begin{cfa} trait is_termination_exception( }; \end{cfa} These traits ensure a given type and virtual type are an exception type and defines one of the two default handlers. The default handlers are used in the main exception-handling operations and discussed in detail in \VRef{s:ExceptionHandling}. However, all three of these traits are tricky to use directly. Both traits ensure a pair of types are an exception type and its virtual table and defines one of the two default handlers. The default handlers are used as fallbacks and are discussed in detail in \VRef{s:ExceptionHandling}. However, all three of these traits can be tricky to use directly. While there is a bit of repetition required, the largest issue is that the virtual-table type is mangled and not in a user facing way. So three macros are provided to wrap these traits to simplify referring to the names: the largest issue is that the virtual table type is mangled and not in a user 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@. These macros take one or two arguments. The first argument is the name of the exception type. The macro passes the unmangled and mangled form to the trait. All three take one or two arguments. The first argument is the name of the exception type. The macro passes its unmangled and mangled form to the trait. The second (optional) argument is a parenthesized list of polymorphic arguments. This argument is only used with polymorphic exceptions and the list is passed to both types. In the current set-up, the base name and the polymorphic arguments have to match so these macros can be used without losing flexibility. list is be passed to both types. In the current set-up, the two types always have the same polymorphic arguments so these macros can be used without losing flexibility. For example consider a function that is polymorphic over types that have a defined arithmetic exception: \begin{cfa} forall(Num | @IS_EXCEPTION(Arithmetic, Num)@) forall(Num | IS_EXCEPTION(Arithmetic, (Num))) void some_math_function(Num & left, Num & right); \end{cfa} where the function may raise exception @Arithmetic@ or any of its decedents. \section{Exception Handling} \label{s:ExceptionHandling} \CFA provides two kinds of exception handling: termination and resumption. These twin mechanisms are the core of the \CFA EHM and multiple features are provided to support them. This section covers the general patterns shared by the two kinds of exceptions and then covers the individual detail operations. Both mechanisms follow the same set of steps to do their operations. Both start with the user performing an exception raise. Then there is the handler search. If one is found, than the exception is caught and the handler is run. When the handler returns, control returns to an location appropriate for each kind of exception. \begin{sloppypar} If the search fails, an appropriate default handler, @defaultTermiationHandler@ or @defaultResumptionHandler@, is run and  control returns to the appropriate location. \end{sloppypar} These twin operations are the core of \CFA's exception handling mechanism. This section will cover the general patterns shared by the two operations and then go on to cover the details each individual operation. Both operations follow the same set of steps. Both start with the user preforming a raise on an exception. Then the exception propogates up the stack. If a handler is found the exception is caught and the handler is run. After that control returns to normal execution. If the search fails a default handler is run and then control returns to normal execution after the raise. This general description covers what the two kinds have in common. Differences include how propogation is preformed, where exception continues after an exception is caught and handled and which default handler is run. \subsection{Termination} \label{s:Termination} Termination handling is familiar and used in most programming Termination handling is the familiar kind and used in most programming languages with exception handling. It is a dynamic, non-local goto. The raise starts searching, and if matched and handled, the stack is unwound and control (usually) continues in the function on the call stack containing the handler. Terminate is commonly used for an error where recovery is impossible in the function performing the raise. It is dynamic, non-local goto. If the raised exception is matched and handled the stack is unwound and control will (usually) continue the function on the call stack that defined the handler. Termination is commonly used when an error has occurred and recovery is impossible locally. % (usually) Control can continue in the current function but then a different \end{cfa} The expression must return a reference to a termination exception, where the termination exception is any type that satisfies trait @is_termination_exception@ at the call site.  Through \CFA's trait system, the trait functions are implicitly passed into the hidden throw code and available to the exception system while handling the exception. A new @defaultTerminationHandler@ can be defined in any scope to change the throw's unhandled behaviour (see below). The throw must copy the provided exception into managed memory because the stack is unwounded. The lifetime of the exception copy is managed by the exception runtime. It is the user's responsibility to ensure the original exception is cleaned up, where allocating it on the unwound stack is sufficient. The exception search walks the stack matching with the copied exception. termination exception is any type that satisfies the trait @is_termination_exception@ at the call site. Through \CFA's trait system the trait functions are implicity passed into the throw code and the EHM. A new @defaultTerminationHandler@ can be defined in any scope to change the throw's behavior (see below). The throw will copy the provided exception into managed memory to ensure the exception is not destroyed if the stack is unwound. It is the user's responsibility to ensure the original exception is cleaned up wheither the stack is unwound or not. Allocating it on the stack is usually sufficient. Then propogation starts with the search. \CFA uses a first match" rule so matching is preformed with the copied exception as the search continues. It starts from the throwing function and proceeds to the base of the stack, from callee to caller. At each stack frame, a check is made for termination handlers defined by the At each stack frame, a check is made for resumption handlers defined by the @catch@ clauses of a @try@ statement. \begin{cfa} try { GUARDED_BLOCK } catch (EXCEPTION_TYPE$$$_1$$$ [* NAME$$$_1$$$]) { } catch (EXCEPTION_TYPE$$$_1$$$ * [NAME$$$_1$$$]) { HANDLER_BLOCK$$$_1$$$ } catch (EXCEPTION_TYPE$$$_2$$$ [* NAME$$$_2$$$]) { } catch (EXCEPTION_TYPE$$$_2$$$ * [NAME$$$_2$$$]) { HANDLER_BLOCK$$$_2$$$ } \end{cfa} When viewed on its own, a @try@ statement with @catch@ clauses simply executes the statements in the @GUARDED_BLOCK@, and when those are finished, the try statement finishes. However, while the guarded statements are being executed, including any invoked functions, a termination exception may be thrown. If that exception is not handled by a try statement further up the stack, the handlers following the try block are now searched for a matching termination exception-type from top to bottom. Exception matching checks each @catch@ clasue from top to bottom, if the representation of the thrown exception-type is the same or a descendant type of the exception types in the @catch@ clauses. If it is the same or a descendant of @EXCEPTION_TYPE@$_i$, then the optional @NAME@$_i$ is When viewed on its own, a try statement will simply execute the statements in @GUARDED_BLOCK@ and when those are finished the try statement finishes. However, while the guarded statements are being executed, including any invoked functions, all the handlers in the statement are now on the search path. If a termination exception is thrown and not handled further up the stack they will be matched against the exception. Exception matching checks the handler in each catch clause in the order they appear, top to bottom. If the representation of the thrown exception type is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ (if provided) is bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$ are executed. If control reaches the end of the handler, the exception is freed and control continues after the @try@ statement. If no termination handler is found during the search, the default termination handler visible at the raise is called.  Through \CFA's trait-system the best default-handler match at the throw sight is used.  This function is passed the copied exception given to the raise. After the default handler is run, control continues after the @throw@ statement. There is a global @defaultTerminationHandler@ function that that is polymorphic over all exception types allowing new default handlers to be defined for different exception types and so different exception types can have different default handlers.  The global default termination-handler performs a cancellation \see{\VRef{s:Cancellation}} on the current stack with the copied exception. freed and control continues after the try statement. If no termination handler is found during the search then the default handler (@defaultTerminationHandler@) is run. Through \CFA's trait system the best match at the throw sight will be used. This function is run and is passed the copied exception. After the default handler is run control continues after the throw statement. There is a global @defaultTerminationHandler@ that is polymorphic over all exception types. Since it is so general a more specific handler can be defined and will be used for those types, effectively overriding the handler for particular exception type. The global default termination handler performs a cancellation \see{\VRef{s:Cancellation}} on the current stack with the copied exception. \subsection{Resumption} \label{s:Resumption} Resumption exception-handling is a less common counterpart to termination but is just as old~\cite{Goodenough75} and is simpler to understand. It is a dynamic, non-local function call (like Lisp). If the throw is successful, a closure is taken from up the stack and executed, after which the throwing function continues executing. Resumption is used when an error occurred, and if the error is repaired, Resumption exception handling is less common than termination 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 matched a closure will be taken from up the stack and executed, after which the raising function will continue executing. These are most often used when an error occurred and if the error is repaired then the function can continue. An alternative approach is explicitly passing fixup functions with local closures up the stack to be called when an error occurs. However, fixup functions significantly expand the parameters list of functions, even when the fixup function is not used by a function but must be passed to other called functions. A resumption raise is started with the @throwResume@ statement: \begin{cfa} throwResume EXPRESSION; \end{cfa} Like termination, the expression must return a reference to a resumption exception, where the resumption exception is any type that satisfies the trait @is_termination_exception@ at the call site. The assertions for this trait are available to 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 runtime, no exception copy is made, as the stack is not unwound. Hence, the exception and any values on the stack remain in scope while the resumption is handled. The exception searches walks the stack matching with the provided exception. It starts from the resuming function and proceeds to the base of the stack, from callee to caller. At run-time, no exception copy is made. As the stack is not unwound the exception and any values on the stack will remain in scope while the resumption is handled. The EHM then begins propogation. The search starts from the raise in the resuming function and proceeds to the base of the stack, from callee to caller. At each stack frame, a check is made for resumption handlers defined by the @catchResume@ clauses of a @try@ statement. try { GUARDED_BLOCK } catchResume (EXCEPTION_TYPE$$$_1$$$ [* NAME$$$_1$$$]) { } catchResume (EXCEPTION_TYPE$$$_1$$$ * [NAME$$$_1$$$]) { HANDLER_BLOCK$$$_1$$$ } catchResume (EXCEPTION_TYPE$$$_2$$$ [* NAME$$$_2$$$]) { } catchResume (EXCEPTION_TYPE$$$_2$$$ * [NAME$$$_2$$$]) { HANDLER_BLOCK$$$_2$$$ } \end{cfa} Termination and resumption handlers may be intermixed in a @try@ statement but the kind of throw must match with kind of handler for it to be considered as a possible match. Like termination, when viewed on its own, a @try@ statement with @catchResume@ clauses simply executes the statements in the @GUARDED_BLOCK@, and when those are finished, the try statement finishes. However, while the guarded statements are being executed, including any invoked functions, a resumption exception may be thrown. If that exception is not handled by a try statement further up the stack, the handlers following the try block are now searched for a matching resumption exception-type from top to bottom. Like termination, exception matching checks each @catch@ clasue from top to bottom, if the representation of the thrown exception-type is the same or a descendant type of the exception types in the @catchResume@ clauses. If it is the same or a descendant of @EXCEPTION_TYPE@$_i$, then the optional @NAME@$_i$ is bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$ are executed. If control reaches the end of the handler, the exception is freed and control continues after the @throwResume@ statement. Like termination, if no resumption handler is found during the search, the default resumption handler visible at the raise is called, which is the best match at the according to \CFA's overloading rules. This function is passed the exception given to the raise. After the default handler is run, execution continues after the @throwResume@ statement. There is a global @defaultResumptionHandler@ that is polymorphic over all resumption and preforms a termination throw on the exception. The @defaultTerminationHandler@ for that throw is matched at the original throw statement (the resumption @throwResume@) and it can be customized by % I wonder if there would be some good central place for this. 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 will only interact with exceptions from the matching type of raise. When a try statement is executed it simply executes the statements in the @GUARDED_BLOCK@ and then finishes. However, while the guarded statements are being executed, including any invoked functions, all the handlers in the statement are now on the search path. If a resumption exception is reported and not handled further up the stack they will be matched against the exception. Exception matching checks the handler in each catch clause in the order they appear, top to bottom. If the representation of the thrown exception type is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ (if provided) is bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$ are executed. If control reaches the end of the handler, execution continues after the the raise statement that raised the handled exception. Like termination, if no resumption handler is found, the default handler visible at the throw statement is called. It will use the best match at the call sight according to \CFA's overloading rules. The default handler is passed the exception given to the throw. When the default handler finishes execution continues after the raise statement. There is a global @defaultResumptionHandler@ is polymorphic over all termination exceptions and preforms a termination throw on the exception. The @defaultTerminationHandler@ for that raise is matched at the original raise statement (the resumption @throwResume@) and it can be customized by introducing a new or better match as well. \subsection{Resumption Marking} \subsubsection{Resumption Marking} A key difference between resumption and termination is that resumption does not unwind the stack. A side effect is that when a handler is matched and run its try block (the guarded statements) and every try statement not unwind the stack. A side effect that is that when a handler is matched and run it's try block (the guarded statements) and every try statement searched before it are still on the stack. This can lead to the recursive resumption problem. } \end{cfa} When this code is executed the guarded @throwResume@ starts a search and matches the handler in the @catchResume@ clause. The handler is called and placed on the stack on top of the try-block. The second throw in the handler searches the same try block and calls another instance of the When this code is executed the guarded @throwResume@ will throw, start a search and match the handler in the @catchResume@ clause. This will be call and placed on the stack on top of the try-block. The second throw then throws and will search the same try block and put call another instance of the same handler leading to an infinite loop. While this situation is trivial and easy to avoid, much more complex cycles This situation is trivial and easy to avoid, but much more complex cycles can form with multiple handlers and different exception types. To prevent this case, examined try statements on the stack are marked, so that subsequent resumption searches skip over them and continue with the next unmarked section of the stack. Unmarking occurs when that exception is handled or the search completes without finding a handler. % This might need a diagram. But it is an important part of the justification % of the design of the traversal order. To prevent all of these cases we mark try statements on the stack. A try statement is marked when a match check is preformed with it and an exception. The statement will be unmarked when the handling of that exception is completed or the search completes without finding a handler. While a try statement is marked its handlers are never matched, effectify skipping over it to the next try statement. \begin{center} %\begin{verbatim} %       throwResume2 ----------. %            |                 | % generated from handler       | %            |                 | %         handler              | %            |                 | %        throwResume1 -----.   : %            |             |   : %           try            |   : search skip %            |             |   : %        catchResume  <----'   : %            |                 | %\end{verbatim} \input{stackMarking} \input{stack-marking} \end{center} The resulting search can be understood by thinking about what is searched for termination. When a throw happens in a handler, a termination handler skips everything from the original throw to the original catch because that part of the stack is unwound. A resumption handler skips the same section of stack because it is marked. A throw in a resumption default-handler performs the same search as the original @throwResume@ because for resumption nothing has been unwound. The symmetry between resumption masking and termination searching is why this pattern was picked. Other patterns, such as marking just the handlers that caught, also work but the symmetry seems to match programmer intuition. These rules mirror what happens with termination. When a termination throw happens in a handler the search will not look at any handlers from the original throw to the original catch because that part of the stack has been unwound. A resumption raise in the same situation wants to search the entire stack, but it will not try to match the exception with try statements in the section that would have been unwound as they are marked. The symmetry between resumption termination is why this pattern was picked. Other patterns, such as marking just the handlers that caught, also work but lack the symmetry means there are less rules to remember. \section{Conditional Catch} Both termination and resumption handler-clauses can be given an additional condition to further control which exceptions is handled: \begin{cfa} catch (EXCEPTION_TYPE [* NAME] @; CONDITION@) Both termination and resumption handler clauses can be given an additional condition to further control which exceptions they handle: \begin{cfa} catch (EXCEPTION_TYPE * [NAME] ; CONDITION) \end{cfa} First, the same semantics is used to match the exception type. Second, if the exception matches, @CONDITION@ is executed. The condition expression may reference all names in the scope of the try block and @NAME@ reference all names in scope at the beginning of the try block and @NAME@ introduced in the handler clause. If the condition is true, then the handler matches. Otherwise, the exception search continues as if the exception type did not match. Conditional catch allows fine-gain matching based on object values as well as exception types. For example, assume the exception hierarchy @OpenFailure@ $\rightarrow$ @CreateFailure@ and these exceptions are raised by function @open@. \begin{cfa} try { f1 = open( ... ); // open raises CreateFailure/OpenFailure f2 = open( ... ); //    with the associate file The condition matching allows finer matching by allowing the match to check more kinds of information than just the exception type. \begin{cfa} try { handle1 = open( f1, ... ); handle2 = open( f2, ... ); handle3 = open( f3, ... ); ... } catch( CreateFailure * f ; @fd( f ) == f1@ ) { // only handle IO failure for f1 } catch( OpenFailure * f ; @fd( f ) == f2@ ) { // only handle IO failure for f2 } \end{cfa} Here, matching is very precise on the I/O exception and particular file with an open problem. This capability cannot be easily mimiced within the handler. \begin{cfa} try { f1 = open( ... ); f2 = open( ... ); ... } catch( CreateFailure * f ) { if ( @fd( f ) == f1@ ) ... else // reraise } catch( OpenFailure * f ) { if ( @fd( f ) == f2@ ) ... else // reraise } \end{cfa} When an exception @CreateFailure@ is raised, the first handler catches the derived exception and reraises it if the object is inappropriate. The reraise immediately terminates the current guarded block, which precludes the handler for the base exception @OpenFailure@ from consideration for object @f2@. Therefore, the catch first, then reraise'' approach is an incomplete substitute for conditional catch. \section{Reraise} \label{s:Rethrowing} \colour{red}{From Andrew: I recommend we talk about why the language doesn't have rethrows/reraises instead.} } catch( IOFailure * f ; fd( f ) == f1 ) { // Only handle IO failure for f1. } catch( IOFailure * f ; fd( f ) == f3 ) { // Only handle IO failure for f3. } // Can't handle a failure relating to f2 here. \end{cfa} In this example the file that experianced the IO error is used to decide which handler should be run, if any at all. \begin{comment} % I know I actually haven't got rid of them yet, but I'm going to try % to write it as if I had and see if that makes sense: \section{Reraising} \label{s:Reraising} Within the handler block or functions called from the handler block, it is possible to reraise the most recently caught exception with @throw@ or is part of an unwound stack frame. To prevent this problem, a new default handler is generated that does a program-level abort. \PAB{I don't see how this is different from the normal throw/throwResume.} \end{comment} \subsection{Comparison with Reraising} A more popular way to allow handlers to match in more detail is to reraise the exception after it has been caught if it could not be handled here. On the surface these two features seem interchangable. If we used @throw;@ to start a termination reraise then these two statements would have the same behaviour: \begin{cfa} try { do_work_may_throw(); } catch(exception_t * exc ; can_handle(exc)) { handle(exc); } \end{cfa} \begin{cfa} try { do_work_may_throw(); } catch(exception_t * exc) { if (can_handle(exc)) { handle(exc); } else { throw; } } \end{cfa} If there are further handlers after this handler only the first version will check them. If multiple handlers on a single try block could handle the same exception the translations get more complex but they are equivilantly powerful. Until stack unwinding comes into the picture. In termination handling, a conditional catch happens before the stack is unwound, but a reraise happens afterwards. Normally this might only cause you to loose some debug information you could get from a stack trace (and that can be side stepped entirely by collecting information during the unwind). But for \CFA there is another issue, if the exception isn't handled the default handler should be run at the site of the original raise. There are two problems with this: the site of the original raise doesn't exist anymore and the default handler might not exist anymore. The site will always be removed as part of the unwinding, often with the entirety of the function it was in. The default handler could be a stack allocated nested function removed during the unwind. This means actually trying to pretend the catch didn't happening, continuing the original raise instead of starting a new one, is infeasible. That is the expected behaviour for most languages and we can't replicate that behaviour. \section{Finally Clauses} Finally clauses are used to perform unconditional clean-up when leaving a scope and appear at the end of a try statement after any catch clauses: \label{s:FinallyClauses} Finally clauses are used to preform unconditional clean-up when leaving a scope and are placed at the end of a try statement after any handler clauses: \begin{cfa} try { 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. Execution of the finally block should always finish, meaning control runs off the end of the block. This requirement ensures execution always continues as if the finally clause is not present, \ie @finally@ is for cleanup not changing control flow. Because of this requirement, local control flow out of the finally block the end of the block. This requirement ensures control always continues as if the finally clause is not present, \ie finally is for cleanup not changing control flow. Because of this requirement, local control flow out of the finally block is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or @return@ that causes control to leave the finally block. Other ways to leave the finally block, such as a long jump or termination are much harder to check, and at best require additional run-time overhead, and so are and at best requiring additional run-time overhead, and so are only discouraged. Not all languages with exceptions have finally clauses. Notably \Cpp does without it as destructors serve a similar role. Although destructors and finally clauses can be used in many of the same areas, they have their own Not all languages with unwinding have finally clauses. Notably \Cpp does without it as descructors serve a similar role. Although destructors and finally clauses can be used in many of the same areas they have their own use cases like top-level functions and lambda functions with closures. Destructors take a bit more work to set up but are much easier to reuse while finally clauses are good for one-off situations and can easily include local information. finally clauses are good for one-off uses and can easily include local information. \section{Cancellation} \label{s:Cancellation} Cancellation is a stack-level abort, which can be thought of as an uncatchable termination. It unwinds the entire stack, and when possible, forwards the cancellation exception to a different stack. Cancellation is a stack-level abort, which can be thought of as as an uncatchable termination. It unwinds the entire current stack, and if possible forwards the cancellation exception to a different stack. Cancellation is not an exception operation like termination or resumption. There is no special statement for starting a cancellation; instead the standard library function @cancel_stack@ is called passing an exception. Unlike a throw, this exception is not used in matching only to pass information about raise, this exception is not used in matching only to pass information about the cause of the cancellation. (This semantics also means matching cannot fail so there is no default handler.) After @cancel_stack@ is called, the exception is copied into the EHM's memory and the current stack is (This also means matching cannot fail so there is no default handler.) After @cancel_stack@ is called the exception is copied into the EHM's memory and the current stack is unwound. After that it depends one which stack is being cancelled. \begin{description} \item[Main Stack:] The main stack is the one used by the program main at the start of execution, and is the only stack in a sequential program. Even in a concurrent program, the main stack is often used as the environment to start the concurrent threads. Hence, when the main stack is cancelled there is nowhere else in the program to go. Hence, after the main stack is unwound, there is a program-level abort. and is the only stack in a sequential program. After the main stack is unwound there is a program-level abort. There are two reasons for this. The first is that it obviously had to do this in a sequential program as there is nothing else to notify and the simplicity of keeping the same behaviour in sequential and concurrent programs is good. Also, even in concurrent programs there is no stack that an innate connection to, so it would have be explicitly managed. \item[Thread Stack:] A thread stack is created for a \CFA @thread@ object or object that satisfies the @is_thread@ trait. A thread only has two points of communication that must happen: start and join. A thread must be running to perform a cancellation (a thread cannot cancel another thread). Therefore, a cancellation must occur after start and before join, so join is used for cancellation communication. After the stack is unwound, the thread halts and waits for another thread to join with it. The joining thread checks for a cancellation, and if present, resumes exception @ThreadCancelled@. \begin{sloppypar} There is a subtle difference between the explicit join (@join@ function) and implicit join (from a @thread@'s destructor call). The explicit join takes the default handler (@defaultResumptionHandler@) from its calling context, which is used if the exception is not caught. The implicit join does a program abort instead. \end{sloppypar} \PAB{uC++ does not have these issues, but catch(...) is not working.} \begin{lstlisting}[language=uC++] #include using namespace std; struct Cl { ~Cl() { cout << "C" << endl; } }; _Coroutine C { void main() { Cl c; try { cancel(); } catch( ... ) { cout << "..." << endl; } _Finally { cout << "F" << endl; } } public: void mem() { resume(); } }; _Task T { void main() { Cl c; try { cancel(); } catch( ... ) { cout << "..." << endl; } _Finally { cout << "F" << endl; } } }; int main() { C c; cout << "here1" << endl; c.mem(); cout << "here2" << endl; { T t; } cout << "here3" << endl; } \end{lstlisting} \PAB{This discussion should be its own section.} This semantics is for safety. If an unwind is triggered while another unwind is underway only one of them can proceed as they both want to consume" the stack. Letting both try to proceed leads to very undefined behaviour. Both termination and cancellation involve unwinding and, since the default @defaultResumptionHandler@ preforms a termination that could more easily happen in an implicate join inside a destructor. So there is an error message and an abort instead. \todo{Perhaps have a more general disucssion of unwind collisions before this point.} The recommended way to avoid the abort is to handle the initial resumption from the implicate join. If required you may put an explicate join inside a finally clause to disable the check and use the local @defaultResumptionHandler@ instead. \item[Coroutine Stack:] A coroutine stack is created for a @coroutine@ object or object that satisfies the @is_coroutine@ trait. A coroutine only knows of two other coroutines, its starter and its last resumer. Of the two the last resumer has the tightest coupling to the coroutine it activated and the most up-to-date information. Hence, cancellation of the active coroutine is forwarded to the last resumer after the stack is unwound. When the resumer restarts, it resumes exception @CoroutineCancelled@, which is polymorphic over the coroutine type and has a pointer to the cancelled coroutine. The resume function also has an assertion that the @defaultResumptionHandler@ for the exception. So it will use the default handler like a regular throw. A thread stack is created for a \CFA @thread@ object or object that satisfies the @is_thread@ trait. After a thread stack is unwound there exception is stored until another thread attempts to join with it. Then the exception @ThreadCancelled@, which stores a reference to the thread and to the exception passed to the cancellation, is reported from the join. There is one difference between an explicit join (with the @join@ function) and an implicit join (from a destructor call). The explicit join takes the default handler (@defaultResumptionHandler@) from its calling context while the implicit join provides its own which does a program abort if the @ThreadCancelled@ exception cannot be handled. Communication is done at join because a thread only has to have to points of communication with other threads: start and join. Since a thread must be running to perform a cancellation (and cannot be cancelled from another stack), the cancellation must be after start and before the join. So join is the one that we will use. % TODO: Find somewhere to discuss unwind collisions. The difference between the explicit and implicit join is for safety and debugging. It helps prevent unwinding collisions by avoiding throwing from a destructor and prevents cascading the error across multiple threads if the user is not equipped to deal with it. Also you can always add an explicit join if that is the desired behaviour. \item[Coroutine Stack:] A coroutine stack is created for a @coroutine@ object or object that satisfies the @is_coroutine@ trait. After a coroutine stack is unwound control returns to the resume function that most recently resumed it. The resume statement reports a @CoroutineCancelled@ exception, which contains a references to the cancelled coroutine and the exception used to cancel it. The resume function also takes the @defaultResumptionHandler@ from the caller's context and passes it to the internal report. A coroutine knows of two other coroutines, its starter and its last resumer. The starter has a much more distant connection while the last resumer just (in terms of coroutine state) called resume on this coroutine, so the message is passed to the latter. \end{description} \PAB{You should have more test programs that compare \CFA EHM to uC++ EHM.}
• ## doc/theses/andrew_beach_MMath/uw-ethesis.tex

 r665edf40 %% Created On       : Wed Apr  6 14:53:29 2016 %% Last Modified By : Peter A. Buhr %% Last Modified On : Sat Mar 27 09:55:55 2021 %% Update Count     : 4796 %% Last Modified On : Tue Apr 20 23:25:56 2021 %% Update Count     : 4888 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % math escape $...$ (dollar symbol) \input{common}                                          % common CFA document macros \setlength{\gcolumnposn}{3in} \CFAStyle                                                                                               % use default CFA format-style \lstset{language=CFA}                                                                   % CFA default lnaguage \section{Enumeration} An \newterm{enumeration} is a compile-time mechanism to give names to constants. There is no runtime manifestation of an enumeration. Their purpose is code-readability and maintenance -- changing an enum's value automatically updates all name usages during compilation. An enumeration defines a type containing a set of names, each called an \newterm{enumeration constant} (shortened to \newterm{enum}) with a fixed (©const©) value. \begin{cfa} enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; // enumeration type definition, set of 7 names An \newterm{enumeration} is a compile-time mechanism to alias names to constants, like ©typedef© is a mechanism to alias names to types. Its purpose is to define a restricted-value type providing code-readability and maintenance -- changing an enum's value automatically updates all name usages during compilation. An enumeration type is a set of names, each called an \newterm{enumeration constant} (shortened to \newterm{enum}) aliased to a fixed value (constant). \begin{cfa} enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; // enumeration type definition, set of 7 names & values Days days = Mon; // enumeration type declaration and initialization \end{cfa} The set of enums are injected into the scope of the definition and use the variable namespace. The set of enums are injected into the variable namespace at the definition scope. Hence, enums may be overloaded with enum/variable/function names. \begin{cfa} double Bar;                     $\C{// overload Foo.Bar, Goo.Bar}\CRT$ \end{cfa} An anonymous enumeration is used to inject enums with specific values into a scope: An anonymous enumeration injects enums with specific values into a scope. \begin{cfa} enum { Prime = 103, BufferSize = 1024 }; \end{cfa} An enumeration is better than using the C \Index{preprocessor} An enumeration is better than using C \Index{preprocessor} or constant declarations. \begin{cquote} \begin{tabular}{@{}l@{\hspace{4em}}l@{}} \begin{cfa} #define Mon 0 #define Sun 6 \end{cfa} or C constant declarations \begin{cfa} const int Mon = 0, ..., Sun = 6; \end{cfa} & \begin{cfa} const int Mon = 0, ..., Sun = 6; \end{cfa} \end{tabular} \end{cquote} because the enumeration is succinct, has automatic numbering, can appear in ©case© labels, does not use storage, and is part of the language type-system. Finally, the type of an enum is implicitly or explicitly specified and the constant value can be implicitly or explicitly specified. \subsection{Enum type} While an enumeration defines a new set-type of names, its underlying enums can be any ©const© type, and an enum's value comes from this type. \CFA provides an automatic conversion from an enum to its base type, \eg comparing/printing an enum compares/prints its value rather than the enum name. The type of enums can be any type, and an enum's value comes from this type. Because an enum is a constant, it cannot appear in a mutable context, \eg ©Mon = Sun© is disallowed, and has no address (it is an rvalue). Therefore, an enum is automatically converted to its constant's base-type, \eg comparing/printing an enum compares/prints its value rather than the enum name; there is no mechanism to print the enum name. The default enum type is ©int©. Hence, ©Days© is the set type ©Mon©, ©Tue©, ...\,, ©Sun©, while the type of each enum is ©int© and each enum represents a fixed integral value. If no values are specified for an integral enum type, the enums are automatically numbered by one from left to right starting at zero. Hence, the value of enum ©Mon© is 0, ©Tue© is 1, ...\,, ©Sun© is 6. If a value is specified, numbering continues by one from that value. It an enum value is an expression, the compiler performs constant-folding to obtain a constant value. Other integral types with associated values can be explicitly specified. If an enum value is specified, numbering continues by one from that value for subsequent unnumbered enums. If an enum value is an expression, the compiler performs constant-folding to obtain a constant value. \CFA allows other integral types with associated values. \begin{cfa} enum( @char@ ) Letter { A @= 'A'@,  B,  C,  I @= 'I'@,  J,  K }; \end{cfa} For enumeration ©Letter©, enum ©A©'s value is explicitly set to ©'A'©, with ©B© and ©C© implicitly numbered with increasing values from ©'A'©, and similarly for enums ©I©, ©J©, and ©K©. Note, an enum is an immutable constant, \ie ©A = B© is disallowed; by transitivity, an enum's type is implicitly ©const©. Hence, a constant/enum cannot appear in a mutuable context nor is a constant/enum addressable (rvalue). Non-integral enum types have the restriction that all enums \emph{must} be explicitly specified, \ie incrementing by one for the next enum is not done even if supported by the enum type, \eg ©double©. Non-integral enum types must be explicitly initialized, \eg ©double© is not automatically numbered by one. \begin{cfa} // non-integral numeric enum( double ) Math { PI_2 = 1.570796, PI = 3.141597,  E = 2.718282 } enum( @double@ ) Math { PI_2 = 1.570796, PI = 3.141597,  E = 2.718282 } // pointer enum( char * ) Name { Fred = "Fred",  Mary = "Mary",  Jane = "Jane" }; enum( @char *@ ) Name { Fred = "Fred",  Mary = "Mary",  Jane = "Jane" }; int i, j, k; enum( int * ) ptr { I = &i,  J = &j,  K = &k }; enum( int & ) ref { I = i,  J = j,  K = k }; enum( @int *@ ) ptr { I = &i,  J = &j,  K = &k }; enum( @int &@ ) ref { I = i,  J = j,  K = k }; // tuple enum( [int, int] ) { T = [ 1, 2 ] }; enum( @[int, int]@ ) { T = [ 1, 2 ] }; // function void f() {...}   void g() {...} enum( void (*)() ) funs { F = f,  F = g }; enum( @void (*)()@ ) funs { F = f,  F = g }; // aggregate struct S { int i, j; }; enum( S ) s { A = { 3,  4 }, B = { 7,  8 } }; enum( @S@ ) s { A = { 3,  4 }, B = { 7,  8 } }; // enumeration enum( Letter ) Greek { Alph = A, Beta = B, /* more enums */  }; // alphabet intersection enum( @Letter@ ) Greek { Alph = A, Beta = B, /* more enums */  }; // alphabet intersection \end{cfa} Enumeration ©Greek© may have more or less enums than ©Letter©, but the enum values \emph{must} be from ©Letter©. m = Alph;               $\C{// {\color{red}disallowed}}$ m = 3.141597;   $\C{// {\color{red}disallowed}}$ d = E;                  $\C{// allowed, conversion to base type}$ d = m;                  $\C{// {\color{red}disallowed}}$ d = m;                  $\C{// allowed}$ d = Alph;               $\C{// {\color{red}disallowed}}$ Letter l = A;   $\C{// allowed}$ A constructor \emph{cannot} be used to initialize enums because a constructor executes at runtime. A fallback is to substitute C-style initialization overriding the constructor with ©@=©. \begin{cfa} enum( struct vec3 ) Axis { Up $@$= { 1, 0, 0 }, Left $@$= ..., Front $@$= ... } A fallback is explicit C-style initialization using ©@=©. \begin{cfa} enum( struct vec3 ) Axis { Up $@$= { 1, 0, 0 }, Left $@$= { 0, 1, 0 }, Front $@$= { 0, 0, 1 } } \end{cfa} Finally, enumeration variables are assignable and comparable only if the appropriate operators are defined for its enum type. \Index{Plan-9}\index{inheritance!enumeration} inheritance may be used with enumerations. \begin{cfa} enum( const char * ) Name2 { @inline Name@, Jack = "Jack", Jill = "Jill" }; enum @/* inferred */@  Name3 { @inline Name@, @inline Name2@, Sue = "Sue", Tom = "Tom" }; enum( char * ) Name2 { @inline Name@, Jack = "Jack", Jill = "Jill" }; enum @/* inferred */@  Name3 { @inline Name2@, Sue = "Sue", Tom = "Tom" }; \end{cfa} Enumeration ©Name2© inherits all the enums and their values from enumeration ©Name© by containment, and a ©Name© enumeration is a subtype of enumeration ©Name2©. The enum type for the inheriting type must be the same as the inherited type; hence the enum type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for ©Name3©. When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important. When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important, \eg the placement of ©Sue© and ©Tom© before or after ©inline Name2©. Specifically, the inheritance relationship for ©Name©s is: j( Fred );    j( Jill );    j( Sue );    j( 'W' ); \end{cfa} Note, the validity of calls is the same for call by reference as for call by value, and ©const© restrictions are the same as for other types. Note, the validity of calls is the same for call-by-reference as for call-by-value, and ©const© restrictions are the same as for other types. Enums cannot be created at runtime, so inheritence problems, such as contra-variance do not apply. \begin{cfa} // Fred is a subset of char * enum char * Fred { A = "A", B = "B", C = "C" }; enum( char *) Fred { A = "A", B = "B", C = "C" }; // Jack is a subset of Fred enum enum Fred Jack { W = A, Y = C}; enum( enum Fred ) Jack { W = A, Y = C}; // Mary is a superset of Fred enum Mary { inline Fred, D = "hello" }; The format of numeric input values in the same as C constants without a trailing type suffix, as the input value-type is denoted by the input variable. For ©_Bool© type, the constants are ©true© and ©false©. For ©bool© type, the constants are ©true© and ©false©. For integral types, any number of digits, optionally preceded by a sign (©+© or ©-©), where a \begin{itemize} In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a special case. However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their polymorphic parameters, and user-defined pointer-like types may need a null value. Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©. Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©bool©. Why just 0 and 1? Why not other integers? No other integers have special status in C. \begin{figure} \begin{cfa} #include #include coroutine Fibonacci { #include #include @@ @coroutine@ Fibonacci { int fn; $\C{// used for communication}$ }; void ?{}( Fibonacci * this ) { this->fn = 0; } void main( Fibonacci * this ) { void main( Fibonacci & fib ) with( fib ) { $\C{// called on first resume}$ int fn1, fn2; $\C{// retained between resumes}$ this->fn = 0; $\C{// case 0}$ fn1 = this->fn; suspend(); $\C{// return to last resume}$ this->fn = 1; $\C{// case 1}$ fn2 = fn1; fn1 = this->fn; suspend(); $\C{// return to last resume}$ for ( ;; ) { $\C{// general case}$ this->fn = fn1 + fn2; fn2 = fn1; fn1 = this->fn; suspend(); $\C{// return to last resume}$ } // for } int next( Fibonacci * this ) { resume( this ); $\C{// transfer to last suspend}$ return this->fn; fn = 0;  fn1 = fn; $\C{// 1st case}$ @suspend;@ $\C{// restart last resume}$ fn = 1;  fn2 = fn1;  fn1 = fn; $\C{// 2nd case}$ @suspend;@ $\C{// restart last resume}$ for () { fn = fn1 + fn2;  fn2 = fn1;  fn1 = fn; $\C{// general case}$ @suspend;@ $\C{// restart last resume}$ } } int next( Fibonacci & fib ) with( fib ) { @resume( fib );@ $\C{// restart last suspend}$ return fn; } int main() { Fibonacci f1, f2; for ( int i = 1; i <= 10; i += 1 ) { sout | next( &f1 ) | ' ' | next( &f2 ); } // for } \end{cfa} for ( 10 ) { $\C{// print N Fibonacci values}$ sout | next( f1 ) | next( f2 ); } } \end{cfa} \vspace*{-5pt} \caption{Fibonacci Coroutine} \label{f:FibonacciCoroutine} \begin{figure} \begin{cfa} #include #include #include #include monitor global_t { int value; }; void ?{}(global_t * this) { this->value = 0; } static global_t global; void increment3( global_t * mutex this ) { this->value += 1; } void increment2( global_t * mutex this ) { increment3( this ); } void increment( global_t * mutex this ) { increment2( this ); } #include #include @@ @monitor@ AtomicCnt { int counter; }; void ?{}( AtomicCnt & c, int init = 0 ) with(c) { counter = init; } int inc( AtomicCnt & @mutex@ c, int inc = 1 ) with(c) { return counter += inc; } int dec( AtomicCnt & @mutex@ c, int dec = 1 ) with(c) { return counter -= dec; } forall( ostype & | ostream( ostype ) ) { $\C{// print any stream}$ ostype & ?|?( ostype & os, AtomicCnt c ) { return os | c.counter; } void ?|?( ostype & os, AtomicCnt c ) { (ostype &)(os | c.counter); ends( os ); } } AtomicCnt global; $\C{// shared}$ thread MyThread {}; void main( MyThread* this ) { for(int i = 0; i < 1_000_000; i++) { increment( &global ); void main( MyThread & ) { for ( i; 100_000 ) { inc( global ); dec( global ); } } int main(int argc, char* argv[]) { processor p; int main() { enum { Threads = 4 }; processor p[Threads - 1]; $\C{// + starting processor}$ { MyThread f[4]; MyThread t[Threads]; } sout | global.value; sout | global; $\C{// print 0}$ } \end{cfa} \caption{Atomic-Counter Monitor} \caption{f:AtomicCounterMonitor} \label{f:AtomicCounterMonitor} \end{figure} [ int, long double ] remquo( long double, long double ); float div( float, float, int * );$\indexc{div}$ $\C{// alternative name for remquo}$ double div( double, double, int * ); long double div( long double, long double, int * ); [ int, float ] div( float, float ); [ int, double ] div( double, double ); long double _Complex log( long double _Complex ); float log2( float );$\indexc{log2}$ int log2( unsigned int );$\indexc{log2}$ long int log2( unsigned long int ); long long int log2( unsigned long long int ) float log2( float ); double log2( double ); long double log2( long double ); \leavevmode \begin{cfa}[aboveskip=0pt,belowskip=0pt] // n / align * align signed char floor( signed char n, signed char align ); unsigned char floor( unsigned char n, unsigned char align ); short int floor( short int n, short int align ); unsigned short int floor( unsigned short int n, unsigned short int align ); int floor( int n, int align ); unsigned int floor( unsigned int n, unsigned int align ); long int floor( long int n, long int align ); unsigned long int floor( unsigned long int n, unsigned long int align ); long long int floor( long long int n, long long int align ); unsigned long long int floor( unsigned long long int n, unsigned long long int align ); // (n + (align - 1)) / align signed char ceiling_div( signed char n, char align ); unsigned char ceiling_div( unsigned char n, unsigned char align ); short int ceiling_div( short int n, short int align ); unsigned short int ceiling_div( unsigned short int n, unsigned short int align ); int ceiling_div( int n, int align ); unsigned int ceiling_div( unsigned int n, unsigned int align ); long int ceiling_div( long int n, long int align ); unsigned long int ceiling_div( unsigned long int n, unsigned long int align ); long long int ceiling_div( long long int n, long long int align ); unsigned long long int ceiling_div( unsigned long long int n, unsigned long long int align ); // floor( n + (n % align != 0 ? align - 1 : 0), align ) signed char ceiling( signed char n, signed char align ); unsigned char ceiling( unsigned char n, unsigned char align ); short int ceiling( short int n, short int align ); unsigned short int ceiling( unsigned short int n, unsigned short int align ); int ceiling( int n, int align ); unsigned int ceiling( unsigned int n, unsigned int align ); long int ceiling( long int n, long int align ); unsigned long int ceiling( unsigned long int n, unsigned long int align ); long long int ceiling( long long int n, long long int align ); unsigned long long int ceiling( unsigned long long int n, unsigned long long int align ); float floor( float );$\indexc{floor}$ double floor( double ); \begin{cfa}[aboveskip=0pt,belowskip=0pt] struct Duration { int64_t tv; $\C{// nanoseconds}$ int64_t tn; $\C{// nanoseconds}$ }; void ?{}( Duration & dur ); void ?{}( Duration & dur, zero_t ); void ?{}( Duration & dur, timeval t ) void ?{}( Duration & dur, timespec t ) Duration ?=?( Duration & dur, zero_t ); Duration ?=?( Duration & dur, timeval t ) Duration ?=?( Duration & dur, timespec t ) Duration +?( Duration rhs ); Duration ?%=?( Duration & lhs, Duration rhs ); _Bool ?==?( Duration lhs, Duration rhs ); _Bool ?!=?( Duration lhs, Duration rhs ); _Bool ?? ( Duration lhs, Duration rhs ); _Bool ?>=?( Duration lhs, Duration rhs ); _Bool ?==?( Duration lhs, zero_t ); _Bool ?!=?( Duration lhs, zero_t ); _Bool ?? ( Duration lhs, zero_t ); _Bool ?>=?( Duration lhs, zero_t ); bool ?==?( Duration lhs, zero_t ); bool ?!=?( Duration lhs, zero_t ); bool ?? ( Duration lhs, zero_t ); bool ?>=?( Duration lhs, zero_t ); bool ?==?( Duration lhs, Duration rhs ); bool ?!=?( Duration lhs, Duration rhs ); bool ?? ( Duration lhs, Duration rhs ); bool ?>=?( Duration lhs, Duration rhs ); Duration abs( Duration rhs ); int64_t ?w( Duration dur ); double ?dns( Duration dur ); double ?dus( Duration dur ); double ?dms( Duration dur ); double ?ds( Duration dur ); double ?dm( Duration dur ); double ?dh( Duration dur ); double ?dd( Duration dur ); double ?dw( Duration dur ); Duration max( Duration lhs, Duration rhs ); Duration min( Duration lhs, Duration rhs ); forall( ostype & | ostream( ostype ) ) ostype & ?|?( ostype & os, Duration dur ); \end{cfa} \begin{cfa}[aboveskip=0pt,belowskip=0pt] void ?{}( timeval & t ); void ?{}( timeval & t, zero_t ); void ?{}( timeval & t, time_t sec, suseconds_t usec ); void ?{}( timeval & t, time_t sec ); void ?{}( timeval & t, zero_t ); void ?{}( timeval & t, Time time ); timeval ?+?( timeval & lhs, timeval rhs ); timeval ?-?( timeval & lhs, timeval rhs ); _Bool ?==?( timeval lhs, timeval rhs ); _Bool ?!=?( timeval lhs, timeval rhs ); bool ?==?( timeval lhs, timeval rhs ); bool ?!=?( timeval lhs, timeval rhs ); \end{cfa} \begin{cfa}[aboveskip=0pt,belowskip=0pt] void ?{}( timespec & t ); void ?{}( timespec & t, zero_t ); void ?{}( timespec & t, time_t sec, __syscall_slong_t nsec ); void ?{}( timespec & t, time_t sec ); void ?{}( timespec & t, zero_t ); void ?{}( timespec & t, Time time ); timespec ?+?( timespec & lhs, timespec rhs ); timespec ?-?( timespec & lhs, timespec rhs ); _Bool ?==?( timespec lhs, timespec rhs ); _Bool ?!=?( timespec lhs, timespec rhs ); bool ?==?( timespec lhs, timespec rhs ); bool ?!=?( timespec lhs, timespec rhs ); \end{cfa} \begin{cfa}[aboveskip=0pt,belowskip=0pt] struct Time { uint64_t tv; $\C{// nanoseconds since UNIX epoch}$ uint64_t tn; $\C{// nanoseconds since UNIX epoch}$ }; void ?{}( Time & time ); void ?{}( Time & time, zero_t ); void ?{}( Time & time, timeval t ); void ?{}( Time & time, timespec t ); Time ?=?( Time & time, zero_t ); void ?{}( Time & time, timeval t ); Time ?=?( Time & time, timeval t ); void ?{}( Time & time, timespec t ); Time ?=?( Time & time, timespec t ); Time ?-?( Time lhs, Duration rhs ); Time ?-=?( Time & lhs, Duration rhs ); _Bool ?==?( Time lhs, Time rhs ); _Bool ?!=?( Time lhs, Time rhs ); _Bool ??( Time lhs, Time rhs ); _Bool ?>=?( Time lhs, Time rhs ); bool ?==?( Time lhs, Time rhs ); bool ?!=?( Time lhs, Time rhs ); bool ??( Time lhs, Time rhs ); bool ?>=?( Time lhs, Time rhs ); int64_t ?ns( Time t ); char * yy_mm_dd( Time time, char * buf ); char * ?ymd( Time time, char * buf ) { // short form return yy_mm_dd( time, buf ); } // ymd char * ?ymd( Time time, char * buf ); // short form char * mm_dd_yy( Time time, char * buf ); char * ?mdy( Time time, char * buf ) { // short form return mm_dd_yy( time, buf ); } // mdy char * ?mdy( Time time, char * buf ); // short form char * dd_mm_yy( Time time, char * buf ); char * ?dmy( Time time, char * buf ) { // short form return dd_mm_yy( time, buf );; } // dmy char * ?dmy( Time time, char * buf ); // short form size_t strftime( char * buf, size_t size, const char * fmt, Time time ); forall( dtype ostype | ostream( ostype ) ) ostype & ?|?( ostype & os, Time time ); forall( ostype & | ostream( ostype ) ) ostype & ?|?( ostype & os, Time time ); \end{cfa} \leavevmode \begin{cfa}[aboveskip=0pt,belowskip=0pt] struct Clock { Duration offset; $\C{// for virtual clock: contains offset from real-time}$ int clocktype; $\C{// implementation only -1 (virtual), CLOCK\_REALTIME}$ struct Clock { $\C{// virtual clock}$ Duration offset; $\C{// offset from computer real-time}$ }; void resetClock( Clock & clk ); void resetClock( Clock & clk, Duration adj ); void ?{}( Clock & clk ); void ?{}( Clock & clk, Duration adj ); Duration getResNsec(); $\C{// with nanoseconds}$ Duration getRes(); $\C{// without nanoseconds}$ Time getTimeNsec(); $\C{// with nanoseconds}$ Time getTime(); $\C{// without nanoseconds}$ Time getTime( Clock & clk ); Time ?()( Clock & clk ); timeval getTime( Clock & clk ); tm getTime( Clock & clk ); void ?{}( Clock & clk ); $\C{// create no offset}$ void ?{}( Clock & clk, Duration adj ); $\C{// create with offset}$ void reset( Clock & clk, Duration adj ); $\C{// change offset}$ Duration resolutionHi(); $\C{// clock resolution in nanoseconds (fine)}$ Duration resolution(); $\C{// clock resolution without nanoseconds (coarse)}$ Time timeHiRes(); $\C{// real time with nanoseconds}$ Time time(); $\C{// real time without nanoseconds}$ Time time( Clock & clk ); $\C{// real time for given clock}$ Time ?()( Clock & clk ); $\C{//\ \ \ \ alternative syntax}$ timeval time( Clock & clk ); $\C{// convert to C time format}$ tm time( Clock & clk ); Duration processor(); $\C{// non-monotonic duration of kernel thread}$ Duration program(); $\C{// non-monotonic duration of program CPU}$ Duration boot(); $\C{// monotonic duration since computer boot}$ \end{cfa} forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype * os, Int mp ); \end{cfa} The following factorial programs contrast using GMP with the \CFA and C interfaces, where the output from these programs appears in \VRef[Figure]{f:MultiPrecisionFactorials}. \VRef[Figure]{f:MultiPrecisionFactorials} shows \CFA and C factorial programs using the GMP interfaces. (Compile with flag \Indexc{-lgmp} to link with the GMP library.) \begin{figure} \begin{cquote} \begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}} \multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}}    & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\ \multicolumn{1}{@{}c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}@{}}   \\ \hline \begin{cfa} sout | 0 | fact; for ( unsigned int i = 1; i <= 40; i += 1 ) { for ( i; 40 ) { fact *= i; sout | i | fact; \end{tabular} \end{cquote} \begin{figure} \small \begin{cfa} Factorial Numbers